Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0a349a7928 | ||
|
|
dfdedb1591 | ||
|
|
e00746d834 | ||
|
|
8af9bb777e | ||
|
|
a729251c9c | ||
|
|
921e1a1437 | ||
|
|
b000734800 | ||
|
|
010f1af16c | ||
|
|
4507c2689d | ||
|
|
c1476a3337 | ||
|
|
3c7d4bfd41 | ||
|
|
78b0c6befd | ||
|
|
f8827cc4a4 | ||
|
|
0c8e1c7b69 | ||
|
|
af5a4db694 | ||
|
|
0371a8b802 | ||
|
|
c8380de521 | ||
|
|
3fe37b93bc | ||
|
|
204c852af1 | ||
|
|
ff01c7c7b4 | ||
|
|
19410e9f96 | ||
|
|
2de927a60f | ||
|
|
9ce77a2c16 | ||
|
|
77988d5562 | ||
|
|
c9660ae269 | ||
|
|
08c12c2959 | ||
|
|
36513b18d2 | ||
|
|
eabf81c1af | ||
|
|
5dc98745de | ||
|
|
4be4ab9101 | ||
|
|
83381b9623 | ||
|
|
0c197a791d | ||
|
|
9fbfe309a9 | ||
|
|
1af5cca417 | ||
|
|
b79dda7f03 | ||
|
|
4f1164c418 | ||
|
|
2cddf912e2 | ||
|
|
4125752d2f | ||
|
|
95bc3bc8e7 | ||
|
|
e9c743f020 | ||
|
|
cdfc10c6e7 | ||
|
|
a97ac9aac3 | ||
|
|
a4d1c56537 | ||
|
|
362349e75a | ||
|
|
1a901424ae | ||
|
|
d570a3a3ee | ||
|
|
d0819fccc2 | ||
|
|
76ddbdd5ec | ||
|
|
b5bcd18b47 | ||
|
|
312dd60320 | ||
|
|
9dd9d37460 | ||
|
|
3ad7379800 | ||
|
|
debc231e9f | ||
|
|
7fe689202f | ||
|
|
22f73e67e8 | ||
|
|
3166331cf3 | ||
|
|
db106dd049 | ||
|
|
267700c73b | ||
|
|
58d0b5bcc5 | ||
|
|
1b896bc45d | ||
|
|
841f663ed5 | ||
|
|
a8ab3a2899 | ||
|
|
57545ae80f | ||
|
|
0407229e05 | ||
|
|
070f89068d | ||
|
|
c352d629c0 |
@@ -0,0 +1,37 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [master]
|
||||
pull_request:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
name: Test and build
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Test, compile, build and audit all variants
|
||||
run: pnpm verify:production
|
||||
@@ -2,82 +2,167 @@ name: Build and Release
|
||||
|
||||
on: workflow_dispatch
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
# Serializes publishes so two runs can never interleave the
|
||||
# fetch-existing-manifest / upload-manifest sequence.
|
||||
concurrency:
|
||||
group: oss-extension-release
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
PUBLIC_BASE_URL: https://aliyun-oss.yaklang.com/chrome-extension
|
||||
OSS_ENDPOINT: https://oss-accelerate.aliyuncs.com
|
||||
OSS_BUCKET: yaklang
|
||||
MANIFEST_MAX_VERSIONS: '10'
|
||||
|
||||
jobs:
|
||||
build-and-publish:
|
||||
publish:
|
||||
name: Build, package and publish to OSS
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '18'
|
||||
cache: 'yarn'
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: yarn install --frozen-lockfile
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Build project
|
||||
run: yarn build
|
||||
- name: Test, compile and build all variants
|
||||
run: pnpm verify:production
|
||||
|
||||
- name: Get version
|
||||
- name: Read version
|
||||
id: version
|
||||
run: |
|
||||
VERSION=$(jq -r '.version' build/manifest.json)
|
||||
echo "version=${VERSION}" >> $GITHUB_OUTPUT
|
||||
echo "build_time=$(date +'%Y-%m-%d %H:%M:%S')" >> $GITHUB_OUTPUT
|
||||
echo "version=$(jq -r .version package.json)" >> "$GITHUB_OUTPUT"
|
||||
echo "build_time=$(date +'%Y-%m-%d %H:%M:%S')" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Zip build artifacts
|
||||
- name: Package release artifacts
|
||||
run: node scripts/package-release.mjs --dist=dist --public-base-url=${PUBLIC_BASE_URL}
|
||||
|
||||
- name: Upload release artifacts to OSS (immutable)
|
||||
run: |
|
||||
cd build
|
||||
zip -r ../extension.zip .
|
||||
node scripts/publish-oss.mjs release \
|
||||
--release-entry=dist/release-entry.json \
|
||||
--dist=dist \
|
||||
--endpoint=${OSS_ENDPOINT} \
|
||||
--bucket=${OSS_BUCKET}
|
||||
env:
|
||||
OSS_KEY_ID: ${{ secrets.OSS_KEY_ID }}
|
||||
OSS_KEY_SECRET: ${{ secrets.OSS_KEY_SECRET }}
|
||||
|
||||
- name: Create Release
|
||||
id: create_release
|
||||
uses: actions/create-release@v1
|
||||
- name: Fetch existing manifest
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# Query parameter busts the CDN's 5-minute manifest cache.
|
||||
url="${PUBLIC_BASE_URL}/manifest.json?mirror_build=${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"
|
||||
code=$(curl --compressed -sS -o dist/existing-manifest.json -w '%{http_code}' --retry 4 --retry-all-errors "$url")
|
||||
if [ "$code" = "200" ]; then
|
||||
echo "Existing manifest fetched."
|
||||
elif [ "$code" = "404" ]; then
|
||||
rm -f dist/existing-manifest.json
|
||||
echo "No existing manifest (first release)."
|
||||
else
|
||||
echo "Unexpected HTTP ${code} fetching ${url}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Build bounded manifest
|
||||
run: |
|
||||
existing=""
|
||||
if [ -f dist/existing-manifest.json ]; then
|
||||
existing="--existing-manifest=dist/existing-manifest.json"
|
||||
fi
|
||||
node scripts/build-manifest.mjs \
|
||||
--release-entry=dist/release-entry.json \
|
||||
${existing} \
|
||||
--max-versions=${MANIFEST_MAX_VERSIONS} \
|
||||
--output=dist/manifest.json \
|
||||
--checksum-output=dist/manifest.json.sha256.txt
|
||||
|
||||
- name: Publish manifest to OSS
|
||||
run: |
|
||||
node scripts/publish-oss.mjs manifest \
|
||||
--manifest=dist/manifest.json \
|
||||
--manifest-checksum=dist/manifest.json.sha256.txt \
|
||||
--endpoint=${OSS_ENDPOINT} \
|
||||
--bucket=${OSS_BUCKET}
|
||||
env:
|
||||
OSS_KEY_ID: ${{ secrets.OSS_KEY_ID }}
|
||||
OSS_KEY_SECRET: ${{ secrets.OSS_KEY_SECRET }}
|
||||
|
||||
- name: Upload release entry for verification
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: release-entry
|
||||
path: dist/release-entry.json
|
||||
|
||||
- name: Create GitHub Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
tag_name: v${{ steps.version.outputs.version }}
|
||||
release_name: Release v${{ steps.version.outputs.version }}
|
||||
name: Release v${{ steps.version.outputs.version }}
|
||||
body: |
|
||||
Branch: ${{ github.ref_name }}
|
||||
Commit: ${{ github.sha }}
|
||||
Build Time: ${{ steps.version.outputs.build_time }}
|
||||
draft: false
|
||||
prerelease: false
|
||||
Manifest: ${{ env.PUBLIC_BASE_URL }}/manifest.json
|
||||
files: |
|
||||
dist/${{ steps.version.outputs.version }}/*
|
||||
dist/manifest.json
|
||||
dist/manifest.json.sha256.txt
|
||||
|
||||
- name: Upload Release Asset
|
||||
uses: actions/upload-release-asset@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Write job summary
|
||||
run: |
|
||||
{
|
||||
echo "## Release v${{ steps.version.outputs.version }}"
|
||||
echo
|
||||
echo "- Manifest: ${PUBLIC_BASE_URL}/manifest.json"
|
||||
echo "- Commit: \`${{ github.sha }}\`"
|
||||
echo
|
||||
echo "| Variant | Size | SHA-256 |"
|
||||
echo "| --- | --- | --- |"
|
||||
jq -r '.artifacts[] | "| \(.variant) | \(.size) | `\(.sha256)` |"' dist/release-entry.json
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
verify:
|
||||
name: Verify public release
|
||||
needs: publish
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
upload_url: ${{ steps.create_release.outputs.upload_url }}
|
||||
asset_path: ./extension.zip
|
||||
asset_name: yakit-chrome-extension-v${{ steps.version.outputs.version }}.zip
|
||||
asset_content_type: application/zip
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Upload Extension To OSS
|
||||
uses: tvrcgo/upload-to-oss@master
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Download release entry
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
key-id: ${{ secrets.OSS_KEY_ID }}
|
||||
key-secret: ${{ secrets.OSS_KEY_SECRET }}
|
||||
region: oss-accelerate
|
||||
bucket: yaklang
|
||||
assets: |
|
||||
extension.zip:/chrome-extension/yakit-chrome-extension-v${{ steps.version.outputs.version }}.zip
|
||||
|
||||
- name: Update OSS latest version file
|
||||
run: echo ${{ steps.version.outputs.version }} > ./extension-version.txt
|
||||
|
||||
- name: Upload Version File to OSS
|
||||
uses: tvrcgo/upload-to-oss@master
|
||||
with:
|
||||
key-id: ${{ secrets.OSS_KEY_ID }}
|
||||
key-secret: ${{ secrets.OSS_KEY_SECRET }}
|
||||
region: oss-accelerate
|
||||
bucket: yaklang
|
||||
assets: |
|
||||
./extension-version.txt:/chrome-extension/latest-version.txt
|
||||
name: release-entry
|
||||
path: dist
|
||||
|
||||
- name: Verify from public endpoint
|
||||
run: node scripts/verify-public.mjs --public-base-url=${PUBLIC_BASE_URL} --release-entry=dist/release-entry.json
|
||||
|
||||
@@ -3,26 +3,39 @@ build.crx
|
||||
build.zip
|
||||
build.pem
|
||||
.idea/
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.js
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
.output
|
||||
stats.html
|
||||
stats-*.json
|
||||
.wxt
|
||||
web-ext.config.ts
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
|
||||
|
||||
ord/
|
||||
.artifacts/
|
||||
|
||||
# Tool-specific clients are developed and packaged outside this repository.
|
||||
/integrations/browser-transform/
|
||||
|
||||
# Product and research documents are maintained locally and are not versioned.
|
||||
/docs/
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
# Yakit Browser Agent Architecture
|
||||
|
||||
## Goals
|
||||
|
||||
- Reuse a user's real, authenticated browser session without exporting a complete browser profile.
|
||||
- Let an AI agent inspect a deliberately shared tab and request human takeover for QR codes, MFA, CAPTCHA, or device confirmation.
|
||||
- Keep proxy, Cookie, User-Agent, page-context, page-function, recording, Chromium debugger and browser transform capabilities behind one typed command boundary.
|
||||
- Make grants short lived, tab scoped, visible, and revocable.
|
||||
|
||||
## Layers
|
||||
|
||||
### Capability layer
|
||||
|
||||
The background service owns browser capabilities. Every remote command passes through one router before it reaches browser APIs.
|
||||
|
||||
| Method | Required scope | Effect |
|
||||
| --- | --- | --- |
|
||||
| `browser.tabs` | `browser.tabs.read` | Lists only tabs included in the active grant |
|
||||
| `browser.frames` | `browser.tabs.read` | Lists main, same-origin, and cross-origin frames for a granted tab |
|
||||
| `browser.context` | `browser.dom.read` | Captures a bounded structured snapshot and diff; Storage and Cookie require their own scopes |
|
||||
| `browser.node.inspect` | `browser.dom.read` | Inspects a document-bound node without returning the current input value |
|
||||
| `browser.node.action` | `browser.dom.write` | Clicks, focuses, scrolls, or writes a value through a current node reference |
|
||||
| `browser.cookies` | `browser.cookies.read` | Reads cookies for a granted tab |
|
||||
| `browser.takeover` | `browser.tab.activate` | Focuses a granted tab for a human step |
|
||||
| `browser.handoff.request` | `browser.human.takeover` | Starts a visible QR/MFA/CAPTCHA/device-confirmation handoff |
|
||||
| `browser.handoff.status` | `browser.human.takeover` | Reads the current task's handoff state |
|
||||
| `browser.network.status/list` | `browser.network.read` | Reads capture state and request metadata |
|
||||
| `browser.network.start/stop/clear` | `browser.network.capture` | Controls a bounded capture session for a granted document |
|
||||
| `browser.network.export` | `browser.network.sensitive.read` | Builds a replay packet from explicitly captured headers/body |
|
||||
| `browser.invoke` | `browser.page.invoke` | Calls an existing page-world function by path |
|
||||
| `browser.eval` expression | `browser.page.eval.expression` | Executes one parenthesized expression in a granted page world |
|
||||
| `browser.eval` program | `browser.page.eval.program` | Executes statements and side effects under an independent high-risk scope |
|
||||
| `browser.recording.status/get` | `browser.recording.read` | Reads bounded business Traces, Pipeline events and value links for a granted document |
|
||||
| `browser.recording.start/stop/clear` | `browser.recording.control` | Controls the document-bound MAIN-world recorder |
|
||||
| recording value previews | `browser.recording.sensitive.read` | Includes bounded short-lived input/output previews; off by default |
|
||||
| `browser.callable.list` | `browser.recording.read` | Lists callable metadata retained by the current granted document |
|
||||
| `browser.callable.create/execute/delete` | `browser.callable.execute` | Creates or invokes a recorded call or captured business closure without exporting keys; deep-capture creation also requires debugger control |
|
||||
| `browser.deep_capture.status` | `browser.debugger.read` | Reads bounded pause state, frames and scopes |
|
||||
| `browser.deep_capture.start/keepalive/resume/detach` | `browser.debugger.control` | Controls a one-shot Chromium function/request breakpoint and its pause lifecycle |
|
||||
| `browser.transform.profile.list` | `browser.transform.read` | Lists document-bound plaintext/wire transform profiles visible to the active grant |
|
||||
| `browser.transform.profile.save/delete` | `browser.transform.manage` | Creates, updates or removes a validated transform pipeline for a granted document |
|
||||
| `browser.transform.execute` | `browser.transform.execute` | Runs one request or response through the selected live-page function pipeline |
|
||||
| `proxy.list` | `browser.proxy.read` | Lists extension proxy profiles |
|
||||
| `proxy.switch` | `browser.proxy.write` | Switches the browser proxy profile |
|
||||
|
||||
The transport never calls browser APIs directly.
|
||||
|
||||
### Grant layer
|
||||
|
||||
A grant contains:
|
||||
|
||||
- an unpredictable session ID;
|
||||
- a task ID;
|
||||
- one or more explicit tab, frame, and document IDs with their origin and grant-time URL;
|
||||
- an explicit set of capability scopes;
|
||||
- creation and expiration timestamps.
|
||||
|
||||
Expired grants are rejected and removed. Reloading or navigating a document returns `stale_document`; navigation to a different origin returns `origin_changed`. Neither condition silently retargets an operation. The UI still offers read/control presets, but those presets only create concrete scope sets and are not stored as authorization levels. A remote caller cannot expand a grant. Only extension UI initiated by the user can create or replace one.
|
||||
|
||||
### Transport layer
|
||||
|
||||
Bridge v3 supports authenticated loopback WebSocket and optional Native Messaging:
|
||||
|
||||
```text
|
||||
Browser extension -> ws://127.0.0.1:<port>/extension -> Yak engine / AI session
|
||||
```
|
||||
|
||||
The Yak gRPC process owns this listener and starts it on `127.0.0.1:64333` by default. Yakit controls it through the existing `RequestYakURL` RPC with the `browser-extension://` schema, so pairing, approval, device rename and revocation do not add dedicated gRPC methods.
|
||||
|
||||
First-time pairing uses `/pairing`. The extension generates an origin-bound ECDSA P-256 installation identity and keeps its non-extractable private key in IndexedDB. Yak keeps a persistent engine identity under the Yakit home directory with owner-only file permissions. The plugin and Yakit derive the same six-digit code from both nonces, identities, origin and public keys; the user approves only after comparing that code. No bearer token is stored or copied.
|
||||
|
||||
The browser-profile `installationId` is stable across disconnects and local unpairing; clearing a pairing destroys the local signing key but does not manufacture a new browser installation. A later approved pairing with the same installation ID rotates the public credential in place while preserving the Yak `deviceId`, user-visible name and creation time. If browser storage was actually erased and a new installation ID is unavoidable, Yakit must explicitly choose whether to replace a matching offline identity or add a separate browser profile. Replacement is restricted to the same extension origin and client, so a shared Chrome extension ID is never used as an unsafe global deduplication key.
|
||||
|
||||
Every `/extension` connection starts with a signed engine challenge. The extension verifies the approved engine public key and replies with a signature from its paired installation key. Yak verifies both the installation ID and browser extension Origin before returning `hello_ack`. The connection is not reported ready until that acknowledgement confirms protocol, capabilities, engine identity, engine instance, connection and session identities. The authentication message also carries the current task/grant identity. A disconnected installation can resume its logical session while each physical connection receives a new ID. Revoking a device immediately closes its active connection. Heartbeats carry sequence/timestamps and expose round-trip latency.
|
||||
|
||||
Request IDs allow concurrent calls in both directions. The extension accepts at most eight engine-initiated in-flight requests, rejects duplicate IDs, supports cancellation, and applies a 16 MiB aggregate limit. Messages above 512 KiB are split into bounded 256 KiB chunks with transfer count/timeout limits. Yak forwards context cancellation and buffers extension events in a bounded queue exposed as `browser.ExtensionWaitEvent`.
|
||||
|
||||
### Yakit device tasks
|
||||
|
||||
Pairing and device CRUD remain on `RequestYakURL`. Executable work uses one server-streaming RPC, `ExecuteBrowserExtensionTask`, with stable routing fields (`task_id`, `device_id`, `schema`, JSON payload and timeout). The stable schemas are:
|
||||
|
||||
- `capability.call`: invokes one extension capability with `{method, params}` and returns its JSON result;
|
||||
- `yak.script`: executes Yak in the owning gRPC process and injects a request-bound `browser.ExtensionCall` and `browser.ExtensionStatus` for the selected device.
|
||||
|
||||
Yakit treats `capability.call` as a schema-controlled command channel rather than adding one gRPC method per browser feature. Its selected-device workspace defaults to a browser-workflow view with Plaintext Gateway, Recorder and Deep Capture modes; raw capability JSON and Yak scripts remain advanced modes. Recording, `browser.callable.*`, `browser.deep_capture.*` and `browser.transform.*` calls therefore use the same streamed task lifecycle, cancellation, device routing and output limits as every other extension capability.
|
||||
|
||||
The engine supports multiple simultaneous browser connections. Calls are routed by paired device ID, pending responses are bound to the target WebSocket, and a disconnect immediately fails that device's outstanding calls. A schema handler cannot silently fall back to another online browser.
|
||||
|
||||
Task events use a small common vocabulary (`queued`, `running`, `log`, `result`, `warning`, `error`, `cancelled`, `completed`) with monotonic sequence and timestamp fields. The RPC bounds payload size, timeout, concurrent scripts, per-event data and aggregate output; cancelling the stream propagates through the Yak context to the extension request.
|
||||
|
||||
The Yak runner is a controlled in-process context, not an operating-system sandbox. It prevents process exit, recovers VM panics and enforces resource bounds, but only trusted operator-authored code should use it. Untrusted or remotely supplied scripts require a future isolated worker. The generic `ExecYakScript` path is intentionally not reused because its child process does not own the parent process's live Bridge manager.
|
||||
|
||||
Native Messaging uses the same Bridge v3 challenge/auth envelope and paired identity contract:
|
||||
|
||||
```text
|
||||
Browser extension -> registered Yakit Native Host -> loopback Yak Bridge -> running Yak engine
|
||||
```
|
||||
|
||||
The Yak repository contains `common/browser/nativehostcmd`, a stdio framing proxy with loopback/origin validation. `native-host/install.sh` and `install.ps1` register per-user Chrome/Chromium/Edge/Brave/Firefox manifests. `nativeMessaging` is optional and requested only when the user explicitly saves Native mode.
|
||||
|
||||
## Human takeover
|
||||
|
||||
Agent workflows treat human participation as an explicit, persisted state transition:
|
||||
|
||||
1. The agent detects a QR code, MFA prompt, CAPTCHA, or device confirmation.
|
||||
2. It calls `browser.handoff.request` for a document in the active control grant.
|
||||
3. The extension focuses the tab, shows a badge, expands the target page panel, and displays the same request in Popup and Options.
|
||||
4. The Agent pauses without polling sensitive content.
|
||||
5. The user chooses **操作已完成** or **取消任务**.
|
||||
6. The extension emits `browser.handoff.changed`; Yak receives it through `ExtensionWaitEvent`.
|
||||
7. The Agent matches the handoff ID, captures a fresh context, and continues only after `completed`.
|
||||
|
||||
`browser.takeover` remains a short-lived focus action without a completion lifecycle.
|
||||
|
||||
## Network capture
|
||||
|
||||
Network capture uses the browser `webRequest` API rather than page-world Fetch/XHR monkey patches. This preserves the actual outgoing request headers, browser-added Cookie header, request body, redirect status, cache state, and timing. The listener is filtered to Fetch/XHR, ping, and related programmatic requests; images, stylesheets, scripts, fonts, and media are not collected.
|
||||
|
||||
Each capture session is bound to one tab, frame, and document. Chrome MV3 stores the bounded session in `storage.session`, so Service Worker suspension does not move sensitive records into persistent settings. Firefox MV2 keeps the same data in background memory. Defaults are metadata-only, 100 entries, and no request headers or body. Explicit sensitive capture is capped at 200 entries and 64 KiB per request body; the UI currently uses 100 entries and 32 KiB.
|
||||
|
||||
Generating a replay packet requires captured request headers. The packet is reconstructed as HTTP/1.1 with the observed header values and bounded body bytes. Truncated or omitted bodies produce an explicit limitation warning. Sending to Yakit is a confirmed Bridge request: Yak validates a maximum 2 MiB packet, saves a Web Fuzzer page configuration in the current project database, broadcasts the new tab to Yakit, and returns its `pageId` before the extension reports success.
|
||||
|
||||
## Browser recording and page callables
|
||||
|
||||
The independent `page-recorder-main-world.js` entrypoint temporarily wraps user-visible interactions, Fetch, XHR, form submission, Beacon, WebSocket, Worker/SharedWorker/MessagePort boundaries, a crypto-adapter registry, `btoa`, and `atob`. WebCrypto, CryptoJS, JSEncrypt, sm-crypto, and node-forge feed one open-but-bounded `crypto` event contract rather than library-specific event kinds. Worker and MessagePort round trips inherit their originating Trace through a bounded channel context, but are explicitly labeled `correlated` rather than being misrepresented as exact value equality. It does not replace `webRequest`: recording explains page-side data flow, while network capture preserves the browser's actual outbound request.
|
||||
|
||||
Each click or submit begins a five-second business Trace. Nested and subsequent events share that Trace. Inputs and outputs are reduced to bounded evidence paths, byte lengths, encodings, and a randomly seeded 64-bit correlation fingerprint. The seed remains inside one page document and is regenerated for every document observer, so fingerprints cannot be compared across document boundaries. Matching an earlier output fingerprint to a later input fingerprint creates an exact Pipeline link. This is evidence of value equality inside one document segment, not proof of semantic causality.
|
||||
|
||||
Raw previews are disabled by default. Enabling them requires `browser.recording.sensitive.read` and caps each preview at 8 KiB. A user-started recording is a tab/frame-scoped Session: the current document keeps live hooks and handles, while the background merges bounded document segments into extension-only `storage.session`. A full navigation is recorded as a first-class Trace event; the previous segment is sealed, the destination document receives a new observer with the same Session identity and a synchronized global sequence, and recording continues until explicit stop, expiry, clear, or tab close. The single per-target Session is removed by a new recording, explicit clear, tab close, or browser-session end. Previews are never written to persistent storage or included in audit or AI request-analysis payloads. Recording is bounded to 500 aggregate events, 48 evidence items per side, 1,000 links, and 64 live callable handles per document.
|
||||
|
||||
Navigation is both a business event and a strict execution-context boundary. Full document navigation, reload, browser Back/Forward, same-document History changes and fragment changes are distinguished. If Back/Forward restores the original document from BFCache, its recorder, handles and callables are resumed without clearing earlier evidence; if the browser performs a hard reload, the historical evidence remains but the destroyed closure heap is truthfully unavailable. MAIN-world lifecycle and the tab-scoped Session are separate states, so a temporary document transition no longer appears as a completed recording. A grant-owned recording remains document-bound and stops at navigation instead of silently extending an Agent's authority into a new document.
|
||||
|
||||
When an observed stateless or receiver-bound operation can be replayed, the recorder retains an opaque reference to the original function, actual receiver, argument template, and non-extractable `CryptoKey` or library key object. Stateful and streaming node-forge sessions instead expose correlated create/init/update/final evidence and direct the user to retain their one-shot business wrapper. Creating a `BrowserPageCallable` places only metadata and a named data slot in the shared current-document registry; key material remains in the retained call template. Library adapters expose only key kind, modulus size, and a document-salted fingerprint—never PEM/private-key material, modulus, exponent, or an instance. Retained call handles are bounded by count, a 2 MiB per-handle limit, and an 8 MiB aggregate limit; oversized calls remain visible as metadata but cannot pin their arguments as replay handles. A manual stop restores wrapped APIs but keeps callables usable in the same live document. Navigation or refresh destroys the page heap and intentionally invalidates every handle. Clear, grant expiry, and grant revocation restore APIs and destroy events, retained handles, and recorded-call entries.
|
||||
|
||||
Inference is request-centered. One exact crypto-output-to-request-field edge plus a live handle can produce a ready profile directly, including JSEncrypt RSA into form, JSON, header, query, or raw body destinations. Multiple crypto outputs in one request become one request-level candidate. Even when every edge is exact, those primitives are not replayed separately because AES keys, RSA-wrapped keys, IVs, nonces, signatures, and timestamps may share one dynamic business context; Deep Capture is required to retain that higher-level callable. Known-library adapters are semantic accelerators rather than the generality boundary: ESM/bundler closures, Worker/WASM paths and unknown business wrappers must remain usable through request/message boundary evidence and business-callable capture even when the algorithm cannot yet be named. The adapter refactor, high-value provider order and anti-fixture acceptance matrix are defined in [`docs/FRONTEND_CRYPTO_GENERALIZATION_ROADMAP.md`](docs/FRONTEND_CRYPTO_GENERALIZATION_ROADMAP.md).
|
||||
|
||||
Options and Yakit expose the same Session -> Trace -> event/evidence/callable model. The UI uses one oldest-to-newest recording timeline, numbered execution cards and relative timestamps. A neutral vertical rail communicates execution order; exact value links use a separate success treatment so temporal order is never mistaken for data-flow proof. Navigation cards show source, destination, lifecycle phase and document availability. The workspace validates a callable with new arguments before it is used by a Yak or AI workflow.
|
||||
|
||||
## Chromium Deep Capture and business callables
|
||||
|
||||
The Recorder remains the low-overhead discovery layer. When a Trace identifies the relevant unified crypto call or request, Chromium Deep Capture attaches through `chrome.debugger`, enables the Runtime/Debugger/DOMDebugger domains and installs one one-shot breakpoint. Crypto matching uses `Debugger.setBreakpointOnFunctionCall` on the real installed adapter wrapper function, so production minification and page CSP cannot remove or block the breakpoint. Request matching uses a bounded XHR/fetch URL substring.
|
||||
|
||||
Pause processing is two-stage. The background publishes at most 14 call-frame skeletons immediately, schedules a 45-second alarm watchdog, then reads up to six local/closure/module scopes for the first eight frames in parallel. UI keepalive extends the deadline; loss of all control surfaces resumes the page. Status, keepalive, resume, detach and adapter creation use only grant identity, `webNavigation`, session state and CDP while paused. They never inject a script into the paused document, avoiding a control-plane deadlock.
|
||||
|
||||
`browser.callable.create` with `source: deep-capture` defaults to a backend-trusted `selected-frame` strategy. Multi-source stack hints and deterministic CDP inspection select a unique page business frame, resolve its real function object from the frame name, receiver descriptor or scope binding, verify its function location and block network/DOM/navigation/storage side effects. A user expression is an advanced fallback and passes the same gate. The resulting function and receiver enter the same page-owned callable registry used by recorded calls; metadata alone crosses the extension boundary. Formal parameters, including those after default values, become ordered input slots. Options can use exact same-name values already present in the authorized paused scope to initialize a non-persistent local replay sample and `body.<parameter>` guide. After resume, `browser.callable.execute` invokes that closure with at most 64 JSON arguments and returns a bounded structured result. Non-extractable keys, key promises and other closure objects remain in the page. Navigation destroys every callable.
|
||||
|
||||
Debugger read, debugger control and callable execution are separate scopes. A grant cannot control a local or different grant's debugger session. Replacement, expiry, revocation and tab closure release owned sessions. Firefox does not request `debugger` or advertise Deep Capture, but it can retain recorder-created page callables. Detailed invariants and real AES-GCM/HMAC acceptance criteria are in [`docs/DEEP_CAPTURE_ARCHITECTURE.md`](docs/DEEP_CAPTURE_ARCHITECTURE.md).
|
||||
|
||||
## Browser Transform Gateway
|
||||
|
||||
The Transform Gateway turns retained page callables into a native Web Fuzzer data plane. Yakit keeps the request and response editor in plaintext. The owning Yak gRPC process calls the selected paired browser after the user's `beforeRequest` hot patch and before network transmission, then calls it again immediately after receiving a response and before the user's `afterRequest` hot patch. `RequestRaw`/`ResponseRaw` remain logical plaintext; `WireRequestRaw`/`WireResponseRaw` preserve the actual transmitted packets for side-by-side inspection and history.
|
||||
|
||||
Profiles are bound to one current `tabId + frameId + documentId + origin`, route-filtered by HTTP method and wildcard URL, and composed as a Pipeline v2 ordered DAG of `context.read`, whitelisted `builtin`, `page.call` and `output.write` nodes. Nodes may reference only earlier results. After the background validates route, origin and document identity, the complete bounded DAG executes in the target MAIN world with one extension-to-page round trip rather than one round trip per node. Outputs support complete/field-level bodies, headers and query parameters. Paths reject prototype traversal, header mappings reject CR/LF injection, and Yak independently rejects any returned URL that changes scheme, host, port or path. Execution values are lossless within an 8 MiB body limit and fail explicitly outside their structural bounds. A bounded per-profile gate protects page functions that are not safely re-entrant.
|
||||
|
||||
Request conversion is fail-closed: no error path sends the plaintext packet. Response conversion failure returns an explicit synthetic failure while retaining the wire response for diagnosis. Navigation, refresh, grant expiry, callable loss, route mismatch and browser disconnect never silently retarget or fall back. Chromium exposes the workspace because Deep Capture can retain business closures; Firefox hides the unavailable Gateway/Deep Capture modes.
|
||||
|
||||
The complete product contract, schema, ordering and acceptance fixture are documented in [`docs/BROWSER_TRANSFORM_GATEWAY.md`](docs/BROWSER_TRANSFORM_GATEWAY.md).
|
||||
|
||||
## Page-world code
|
||||
|
||||
### Structured context and node references
|
||||
|
||||
`browser.context` no longer returns a full HTML document. A snapshot contains a 20 KiB body-text excerpt, bounded headings/forms, up to 400 actionable nodes discovered while scanning at most 10,000 elements, a full frame inventory, optional bounded Web Storage values, optional IndexedDB database/store/key metadata, optional CacheStorage names, bounded document/SPA lifecycle events, optional Cookie values, authentication signals, and a diff against the preceding snapshot for the same tab/frame. IndexedDB and Cache values are never collected. Open Shadow Roots are traversed recursively; the extension's own edge-panel Shadow Root is excluded.
|
||||
|
||||
Each actionable element is registered in the page's MAIN world and identified by `captureId + tabId + frameId + documentId + nodeId`. `browser.node.inspect` and `browser.node.action` resolve the registered `Element` directly instead of re-running a CSS selector. A new capture replaces the registry, a detached element is rejected, and a changed document fails target resolution. These paths return `stale_node` or `stale_document`; they never silently retarget a similar element.
|
||||
|
||||
Frame inventory combines `webNavigation.getAllFrames` with a bounded packaged probe in every accessible frame. Grants store an explicit target for each selected `tabId + frameId + documentId + origin`; selecting a tab authorizes only its main frame until the user separately selects child frames. `webNavigation.getFrame` verifies each remote operation against the current frame URL and document. Cross-origin navigation returns `origin_changed`, while same-origin document replacement returns `stale_document`.
|
||||
|
||||
Node inspection returns bounded identity, safe attributes, visibility, state, and viewport bounds. It deliberately excludes the current input value. Node actions support `click`, `focus`, `scroll`, and `setValue`; `setValue` uses native value setters plus input/change events, rejects file inputs, requires `browser.dom.write`, and never sends the supplied value to the audit writer. Programmatic click is a page-world click and is not represented as a trusted physical mouse event.
|
||||
|
||||
The authentication classification is a heuristic based on bounded DOM controls plus explicitly requested Cookie names and Storage keys. It is useful for workflow routing, but it is not proof that the server accepts the current session.
|
||||
|
||||
`PageExecutionAdapter` selects an execution mechanism at build time. Production/store Chrome builds use the Web Store-permitted User Scripts API:
|
||||
|
||||
```text
|
||||
Background capability router
|
||||
-> userScripts.execute({ world: "MAIN" })
|
||||
-> structured { ok, result | error }
|
||||
```
|
||||
|
||||
The default production build declares Chrome 138+, requires the user to enable Allow User Scripts, and physically omits `page-main-world.js`. It never silently falls back to direct Eval.
|
||||
|
||||
User Scripts receive the selected expression or program as direct script source; the Store path never calls `eval` on Bridge-provided text. Expression mode automatically returns its expression. Program mode is an async function body and requires an explicit `return` to produce a value; without one it returns `undefined`.
|
||||
|
||||
Development and local Firefox MV2 builds use WXT's packaged injection pattern. Enterprise Chrome prefers User Scripts and retains this pattern only as a managed fallback:
|
||||
|
||||
```text
|
||||
Background capability router
|
||||
| tabs.sendMessage (extension-only)
|
||||
Isolated content script
|
||||
| correlated CustomEvent on the injected script element
|
||||
Unlisted page-main-world script
|
||||
| indirect eval / function invocation
|
||||
The page's real window context
|
||||
```
|
||||
|
||||
The old extension established the essential behavior by injecting `inject.js` and forwarding `CONTENT_EVAL_CODE` through `window.postMessage`. The current bridge preserves that capability while adding request IDs, Promise resolution, response timeouts, error propagation, cycle-safe result serialization, output limits, and content-script lifecycle cleanup. A timeout stops the extension from waiting for an asynchronous result; JavaScript cannot safely interrupt synchronous code, so an infinite loop can still block the target page.
|
||||
|
||||
Both adapters share the same expression/program return rules, result serializer, Promise behavior, timeout bounds, and error envelope. Local Eval is initiated by an explicit user action. Remote expression and program modes require separate scopes and a target whose tab, frame, document and origin still match. Because the page controls its JavaScript environment, all results remain untrusted input.
|
||||
|
||||
The public Firefox MV3 AMO channel is invoke-only at the extension boundary: it requests neither `userScripts` nor general page invocation/Eval, does not package `page-main-world.js`, and advertises neither Bridge capability. This follows Mozilla's current restriction of `userScripts` to user-script managers. Structured context, stable node commands, network capture, browser recording and human handoff remain available.
|
||||
|
||||
The same page bridge supports `browser.invoke` for the narrower case where the Agent already knows a concrete global function path. Browser recording uses the same target/grant boundary through a separately packaged, bounded MAIN-world recorder and does not depend on general Eval.
|
||||
|
||||
## Proxy routing
|
||||
|
||||
Proxy routing is a compile-and-apply subsystem, not an extension-side per-request rules engine. Durable endpoint/rule/source summaries remain in `settings.proxy.v1`; downloaded source revisions, normalized 512-rule chunks, and the eight newest compiled artifacts live in `yakit-proxy-rules` IndexedDB. Large exact/suffix host sets compile to PAC tries, while wildcard and regex conditions are instantiated once outside `FindProxyForURL`.
|
||||
|
||||
Automatic order is manual rules, ordered sources, then the default endpoint. Source exclusions run before positive rules unless a SwitchyOmega `@with result` list explicitly owns file order. Rule-source updates stage a new revision and only replace the state reference after parse, compilation, `browser.proxy.settings`, and serialized state commit succeed. The last live PAC and source revision remain active on failure.
|
||||
|
||||
Yakit MITM is a built-in fixed endpoint, not a remotely managed MITM process. Popup keeps two operations visually and behaviorally separate: a current-hostname assignment can target any Direct or fixed HTTP(S)/SOCKS endpoint and atomically enables automatic routing, while the global mode list changes the entire browser without creating a rule. “Automatic” clears the exact-host override so subscriptions and the default endpoint resume control. The extension does not control Yak MITM lifecycle or downstream interception policy. Full formats, budgets, failure behavior, and verification requirements are documented in `docs/PROXY_ARCHITECTURE.md`.
|
||||
|
||||
## Popup and Options tool boundary
|
||||
|
||||
The popup is the current-tab command surface. It uses a fixed 48px icon rail with four modules: overview, proxy, Cookie Editor and User-Agent. The Yak SVG mark remains visible in the header without repeating the full product name. Bridge state is represented by a focusable status dot with a tooltip and explicit accessible label; green means connected, amber means connecting/negotiating, gray means unpaired or offline, and red means an error.
|
||||
|
||||
Cookie Editor and User-Agent are exposed as rail modules for actions that should complete in one or two steps:
|
||||
|
||||
- Cookie values are masked by default and only revealed by an explicit click; the quick editor supports the common name/value/path/SameSite/flag fields and preserves existing partition metadata.
|
||||
- User-Agent quick switching offers browser default, built-in device templates and saved custom profiles, then applies the selected header to the current hostname and reloads the target tab.
|
||||
- Both quick views report the current target hostname and link to the full Options tool. They never implement a second browser API path; all reads and mutations use the typed runtime request map.
|
||||
|
||||
Options is the durable management surface. Its `常用工具` navigation group contains the full Cookie Editor and User-Agent manager, including filtering, import/export, CHIPS fields, per-host assignments, custom profile editing and deletion. This split keeps the popup small enough for repeated use while retaining the security controls and information density required for deep workflows.
|
||||
|
||||
## Page UI loading
|
||||
|
||||
The content script is a roughly 10-12.2 KiB native DOM shell. It owns the Yak launcher, bridge indicator, drag position, left/right snapping, and handoff-triggered expansion. React, Radix, and the floating workbench are loaded in `floating.html` only after the user expands the launcher or a handoff targets that tab; the iframe is released after 60 seconds collapsed. Build auditing reports the content-script size as an advisory trend; lazy loading and the 60-second release policy are verified from runtime behavior rather than enforced through a fixed bundle-size gate.
|
||||
|
||||
Popup, Options, and the floating workbench share one token-based design system in `src/styles/`: `tokens.css` defines the palette, type scale (11-20px), radii, and shadows, including a full dark set under `[data-theme='dark']`; `ui.css` styles the shared Radix-backed components. The vivid brand orange is reserved for non-text accents; filled primary buttons and text links use a deeper AA-contrast orange. All surfaces are light-first — the orange yak mark is shown bare without a backing tile. The theme preference (`system`/`light`/`dark`) lives in its own `settings.appearance.v1` local-storage key, is written only from extension UI, and is applied to `<html data-theme>` by each entrypoint through `src/platform/storage/appearance.ts`; the content-script launcher reads the same key in-page (falling back to the OS scheme) to theme its shadow-DOM shell.
|
||||
|
||||
## Audit boundary
|
||||
|
||||
Audit events live under a separate storage key and are serialized independently from settings and active session state. The bounded log retains the latest 500 events. It records category, method/action, outcome, task ID, tab ID, duration, error code, and a fixed safe summary where applicable. Capability parameters and results are never passed to the audit writer. The Options activity view reads the latest 200 entries and lets the user clear them locally.
|
||||
|
||||
## Production operations
|
||||
|
||||
- State v7 uses separate durable proxy/UA/Bridge/panel keys and separate session grant/Bridge/action keys; mutation is serialized across domains and no legacy migration path exists.
|
||||
- Agent actions have a session timeline and user pause/resume/revoke controls. Persistent audit remains metadata-only.
|
||||
- Managed storage can lock transport, endpoint/host, grant duration/origins, program Eval and panel availability. Enforcement is in background handlers.
|
||||
- Aggregate Service Worker, Bridge, heartbeat and capability metrics stay local. Explicit diagnostics export omits URLs, values, payloads, Eval code and task/grant identifiers.
|
||||
- Public review artifacts live under `docs/store-review`; privacy, permission and enterprise deployment contracts live under `docs/`.
|
||||
- Store/Enterprise Chromium E2E covers 320/390/desktop UI, service-worker restart, frame/document/origin boundaries, request/recording workflows, exact value and correlated channel links, document callable replay, all five crypto adapters, node-forge stateful sessions, independent SM2/SM4/RSA/AES/digest/HMAC/signature validation, randomized non-global ESM + WebAssembly closure recovery, Worker holdout, recorder load/memory budgets, JSEncrypt RSA receiver retention and guided form-field profiles, distinct WebCrypto operation breakpoints, real closure-held AES-GCM/HMAC request encryption, encrypted-response restoration and server validation, handoff, audit/diagnostic redaction and state concurrency. Go tests cover Bridge v3 pairing, code derivation, signed challenge/auth, revocation, YakURL control, chunking/session recovery, transform URL confinement and Native Messaging proxy framing.
|
||||
@@ -0,0 +1,69 @@
|
||||
# Design System: Yakit Browser Agent
|
||||
**Project ID:** yakit-chrome-client (derived from codebase design tokens, `src/styles/tokens.css` — no Stitch project)
|
||||
|
||||
## 1. Visual Theme & Atmosphere
|
||||
|
||||
A **focused security instrument panel**: utilitarian, information-dense, and calm. The aesthetic philosophy is "console first, chrome second" — content surfaces stay quiet and neutral so that state (connection, capture, risk) can carry all the visual signal. The mood is airy-but-dense: compact 13px typography and tight 8px-rhythm spacing, balanced by generous card padding and breathing room between functional groups.
|
||||
|
||||
The brand presence is deliberately restrained: a light, continuous surface carries every view, signed by the bare orange yak mark and a single ember-orange accent reserved for moments of genuine emphasis. Nothing glows, nothing gradients, no black slabs; depth comes from whisper-soft shadows and hairline separators, not borders. The system ships in twin themes — a cool light canvas and a true-dark console — with identical geometry and hierarchy, switched by a user preference (`system` / `light` / `dark`).
|
||||
|
||||
## 2. Color Palette & Roles
|
||||
|
||||
### Light theme (default)
|
||||
|
||||
- **Canvas Mist (#f3f4f6)** — application background; lets white cards float without borders.
|
||||
- **Card White (#ffffff)** — primary content surfaces: cards, tables, panels, inputs.
|
||||
- **Inset Pebble (#eceef1)** — recessed fills: stat tiles, code-free inset areas, toggle-off track.
|
||||
- **Ink (#1d232a)** — primary text and strong values.
|
||||
- **Slate Note (#68727d)** — secondary text, descriptions, timestamps.
|
||||
- **Label Slate (#474f59)** — field labels, section labels, ghost-button text.
|
||||
- **Hairline (#e1e4e8)** — non-structural separators (table rows, list dividers); used sparingly.
|
||||
- **Frame Line (#c8cfd6)** — input strokes and secondary-button outlines.
|
||||
- **Yak Orange (#ee7815)** — brand accent for *non-text* signal only: toggle-on tracks, active nav indicator, icon highlights, focus halo. Never carries text.
|
||||
- **Ember (#b54f08)** — the accessible action orange: filled primary buttons (white text, 5.1:1 AA) and text links on light surfaces.
|
||||
- **Ember Deep (#9e4607)** — hover state for filled primary buttons.
|
||||
- **Ember Wash (#fdf0e1)** — soft selection tint: active list rows, selected table lines.
|
||||
- **Pine (#1e7f52)** on **Mint Mist (#e4f3eb)** — connected, captured, success states.
|
||||
- **Umber (#94650d)** on **Parchment (#fcf2d9)** — warning states and the human-handoff surface.
|
||||
- **Brick (#bf3d3d)** on **Blush (#fbeaea)** — destructive actions, errors, failed states.
|
||||
- **Bare Yak (the orange brand mark, #f97a04 family)** — shown directly on the surface with no backing tile; it is the only persistent brand signature.
|
||||
|
||||
### Dark theme (`[data-theme='dark']`)
|
||||
|
||||
- **Deep Space (#0e1116)** — application background; true console dark, not navy.
|
||||
- **Panel Slate (#161b21)** — cards and surfaces.
|
||||
- **Raised Slate (#1e242c)** — inset fills and hover states.
|
||||
- **Fog Text (#e2e7ec)** — primary text; **Ash (#8a949f)** secondary; **Mist Strong (#b2bcc5)** labels.
|
||||
- **Ember Glow (#f5832a)** — filled primary buttons with **Roasted Ink (#201205)** text (7.5:1 AA); brighter than light theme to hold contrast on dark.
|
||||
- **Ember Light (#f7a15c)** — text links and code accents on dark surfaces.
|
||||
- Semantic tints deepen to translucent darkness: **Pine Glow (#45b981 / #122a1f)**, **Amber Glow (#d9a441 / #2c2311)**, **Coral Glow (#e06e6e / #2f1b1b)**.
|
||||
|
||||
## 3. Typography Rules
|
||||
|
||||
- **Family:** A system-native sans stack (Inter falling back to ui-sans-serif, system-ui, PingFang SC, Hiragino Sans GB, Microsoft YaHei, Noto Sans CJK SC) — chosen for crisp CJK rendering at small sizes without bundling font files. Code and packets use a mono stack (ui-monospace, SF Mono, Consolas).
|
||||
- **Scale (six steps, no more):** 11px for uppercase micro-labels only, 12px secondary/description, **13px as the reading base**, 14px emphasized values, 16px section titles, 20px page titles.
|
||||
- **Weight hierarchy:** 500 for navigation, 600 for interactive text and labels, 650 for card titles and strong values, 700 reserved for page titles and hero numerals.
|
||||
- **Micro-labels:** 11px, weight 650, letter-spacing .04em, uppercase, Slate Note color — the "eyebrow" voice used above data.
|
||||
- **Rhythm:** line-heights stay tight (16–18px for body); Chinese text is never set below 12px except uppercase micro-labels.
|
||||
|
||||
## 4. Component Stylings
|
||||
|
||||
* **Buttons:** 36px tall with gently squared corners (6px radius) and 13px semibold labels. The *filled primary* is Ember (light) / Ember Glow (dark) with contrasting text — strictly one per view. *Secondary* buttons are Card White with a Frame Line stroke. *Ghost* buttons are transparent until hovered. *Danger* is a Brick outline that fills with Blush on hover. Small (30px) and icon (34px square) variants share the same geometry.
|
||||
* **Cards/Containers:** Generously rounded corners (12px radius), Card White fill, and a whisper-soft two-layer shadow (a 1px key line of shade plus a faint 4px lift) — no borders. Recessed stat tiles inside cards use Inset Pebble with softly rounded corners (8px). Nothing nests a shadowed card inside another.
|
||||
* **Inputs/Forms:** 36px tall, 6px corner radius, 1px Frame Line stroke on Card White; textareas keep the same stroke. Focus never shows a hard outline — instead a soft ember halo (3px of translucent Yak Orange). Field labels are 12px semibold Label Slate; hints in 12px Slate Note.
|
||||
* **Toggles:** Pill-shaped switches (40×22px), Pebble track when off, Yak Orange track when on, white 16px thumb gliding on a short ease.
|
||||
* **Navigation rail:** A 238px rail in the same surface as the workspace, separated by a single hairline. Items are 40px rows with softly rounded corners (8px); the active item shows a subtle raised fill plus a 3px inset Yak Orange indicator bar on its leading edge, with its icon tinted orange.
|
||||
* **Status pills:** Fully rounded (pill-shaped, 999px) badges pairing each semantic color with its soft wash — connected/capturing in Pine-on-Mint, waiting/warning in Umber-on-Parchment, error in Brick-on-Blush.
|
||||
* **Code & packets:** Deep slate panels (#171b20, light mono text) with 8px rounded corners; they remain dark in both themes as "terminal territory."
|
||||
* **Handoff surface:** A Parchment card with a 3px Umber leading edge and the warning icon — the single interruptive pattern in the system, reserved for QR/MFA/CAPTCHA human takeover.
|
||||
|
||||
## 5. Layout Principles
|
||||
|
||||
- **Shell:** A fixed 238px dark rail plus a fluid workspace. The workspace column is capped at a comfortable 1440px reading width and **horizontally centered**, so ultra-wide monitors frame the console instead of stretching tables into unreadability.
|
||||
- **Grid alignment:** The 60px sticky topbar shares the exact content grid — its padding is computed from the same 1440px cap (`max(28px, (100% − 1440px)/2 + 28px)`), keeping the target-tab chip and the page content on one vertical line.
|
||||
- **Spacing rhythm:** An 8px base unit; 16px gaps between cards, 16–20px inner card padding, 22–28px page padding. Groups are separated by space and shadow, not rules.
|
||||
- **Two-column workbenches:** Data pages (network, cookies, context, engine) use a fluid primary column with a 320–440px inspector column that sticks below the topbar; below 1080px they stack to a single column.
|
||||
- **Grid discipline:** Every single-column vertical grid declares an explicit `minmax(0, 1fr)` track, so long URLs and code strings truncate with ellipses instead of overflowing narrow (320–390px) viewports.
|
||||
- **Popup:** A fixed 390px single-sheet column — sections divided by hairlines, not floating cards — designed to a strict 600px height budget, keeping every action including the bottom primary capture button visible without scrolling.
|
||||
- **Floating panel:** A 46px edge launcher — a white stadium orb with the bare yak mark (dark in dark theme, theme-aware in-page) — that expands to a 326px rounded workbench over the page; its header shares the panel surface with a single hairline seam.
|
||||
- **Motion:** Short (140–180ms) ease transitions on color and slide only; `prefers-reduced-motion` collapses all animation.
|
||||
@@ -1,90 +1,414 @@
|
||||
# Yet Another Chrome Extension for Yakit CyberSecurity
|
||||
<p align="center">
|
||||
<img src="./public/yak.svg" width="96" alt="Yak Logo" />
|
||||
</p>
|
||||
|
||||
This is a Chrome Extension for Yakit CyberSecurity. U can use it to...
|
||||
<h1 align="center">Yakit Browser Agent</h1>
|
||||
|
||||
1. Change your proxy between Yakit and other proxy or your system.
|
||||
2. As a sandbox for your Yakit Client
|
||||
<p align="center">
|
||||
面向真实浏览器上下文的安全测试与 AI Agent 协作扩展
|
||||
</p>
|
||||
|
||||
# CRA: Getting Started with Create React App
|
||||
<p align="center">
|
||||
连接浏览器、Yak 引擎与 Yakit,让登录态、页面函数、前端加解密、网络请求和人工操作成为可授权、可复用、可审计的测试能力。
|
||||
</p>
|
||||
|
||||
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
|
||||
> [!IMPORTANT]
|
||||
> Yakit Browser Agent 面向已获授权的安全测试、企业自测和教学环境。扩展具备读取登录态、捕获网络请求、调用页面函数和调试页面执行现场等高权限能力;请只对你拥有或明确获准测试的目标使用。
|
||||
|
||||
## Available Scripts
|
||||
## 项目定位
|
||||
|
||||
In the project directory, you can run:
|
||||
Yakit Browser Agent 是 Yak / Yakit 生态中的浏览器执行端。它运行在用户真实使用的浏览器里,在用户明确授权后,将特定标签页的页面上下文、安全测试能力和人工交互能力提供给 Yak 引擎、Yakit 工作区以及 AI Agent。
|
||||
|
||||
### `npm start`
|
||||
它重点解决传统安全测试工具难以自然处理的几类问题:
|
||||
|
||||
Runs the app in the development mode.\
|
||||
Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
|
||||
- 目标功能依赖已经登录的浏览器环境,无法仅靠离线 HTTP 请求复现;
|
||||
- 请求参数由混淆后的前端代码、闭包状态、动态密钥、`CryptoKey`、Worker 或 WebAssembly 现场生成;
|
||||
- 测试者希望编辑明文,但目标服务器只接受页面产生的密文、签名或动态请求封装;
|
||||
- 流程包含扫码、MFA、CAPTCHA、设备确认等必须由用户参与的步骤;
|
||||
- 双身份授权测试需要可靠隔离登录态、复用真实请求并保留可复核证据;
|
||||
- AI Agent 需要浏览器提供真实、结构化、受控的上下文,而不是依赖截图猜测或导出完整浏览器配置。
|
||||
|
||||
The page will reload when you make changes.\
|
||||
You may also see any lint errors in the console.
|
||||
本项目并不是只针对某个靶场编写的加解密脚本,也不是一个简单的 JS-RPC 转发器。它以通用的调用证据、业务 Trace、请求边界、页面 Callable 和类型化 Pipeline 为基础:能由确定性证据完成的步骤交给代码验证,证据不足或语义复杂的部分再交给用户与 AI 辅助分析。
|
||||
|
||||
### `npm test`
|
||||
## 设计原则
|
||||
|
||||
Launches the test runner in the interactive watch mode.\
|
||||
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more
|
||||
information.
|
||||
| 原则 | 说明 |
|
||||
| --- | --- |
|
||||
| 真实现场优先 | 复用页面正在运行的函数、receiver、闭包和浏览器状态,不要求先把密钥或完整算法导出到外部。 |
|
||||
| 证据驱动 | 通过值指纹、调用顺序、业务 Trace、请求字段关联和响应归属建立结论,不因“发现某个加密库”就直接猜测转换逻辑。 |
|
||||
| 用户明确授权 | 所有远程能力绑定具体标签页、Frame、文档、来源、任务、权限范围和有效期,授权可见、可暂停、可撤销。 |
|
||||
| 确定性验证与 AI 协作 | AI 用于解释、归纳和提出方案;协议校验、Profile 编译、真实回放和结果比较由确定性代码完成。 |
|
||||
| 通用能力优先 | 对库、算法和业务形态建立适配层,不以固定字段名、固定接口或单一靶场流程作为产品逻辑。 |
|
||||
| 本地与性能优先 | 大型代理规则使用 IndexedDB 分块存储和编译缓存;敏感页面数据默认短时保留,诊断与审计只记录必要元数据。 |
|
||||
|
||||
### `npm run build`
|
||||
## 系统组成
|
||||
|
||||
Builds the app for production to the `build` folder.\
|
||||
It correctly bundles React in production mode and optimizes the build for the best performance.
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph Browser[用户浏览器]
|
||||
Page[目标页面\n登录态 · DOM · JS · Worker]
|
||||
Extension[Yakit Browser Agent\n录制 · 调试 · 代理 · 授权]
|
||||
Page <--> Extension
|
||||
end
|
||||
|
||||
The build is minified and the filenames include the hashes.\
|
||||
Your app is ready to be deployed!
|
||||
subgraph Local[本地安全测试环境]
|
||||
Yak[Yak Engine\nBridge v3 · Capability Router]
|
||||
Yakit[Yakit\n浏览器工作区 · Web Fuzzer]
|
||||
Agent[AI Agent\n证据分析 · 流程编排]
|
||||
Yak <--> Yakit
|
||||
Yak <--> Agent
|
||||
end
|
||||
|
||||
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
|
||||
User[测试人员] <--> Extension
|
||||
Extension <-- 配对身份 / 签名挑战 / 流式任务 --> Yak
|
||||
```
|
||||
|
||||
### `npm run eject`
|
||||
扩展不允许远程调用方直接访问浏览器 API。所有命令统一经过 Capability Router、参数 Schema、授权 Scope 和文档生命周期检查,再由对应功能模块执行。
|
||||
|
||||
**Note: this is a one-way operation. Once you `eject`, you can't go back!**
|
||||
## 核心能力
|
||||
|
||||
If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will
|
||||
remove the single build dependency from your project.
|
||||
### 1. 前端加解密录制与明文网关
|
||||
|
||||
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right
|
||||
into your project so you have full control over them. All of the commands except `eject` will still work, but they will
|
||||
point to the copied scripts so you can tweak them. At this point you're on your own.
|
||||
这是 Yakit Browser Agent 的核心工作流。测试者只需要在真实页面完成一次尽可能短的业务操作,扩展会从页面输入、密码调用、编码转换、通信边界和最终请求中还原数据流。
|
||||
|
||||
You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you
|
||||
shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't
|
||||
customize it when you are ready for it.
|
||||
主要能力包括:
|
||||
|
||||
## Learn More
|
||||
- 录制 Fetch、XHR、表单导航、Beacon、WebSocket、Worker、SharedWorker 和 MessagePort 等业务边界;
|
||||
- 记录加解密调用的输入、输出指纹、调用栈、receiver、固定参数模板与请求先后关系;
|
||||
- 将同一业务动作组织为按时间排序的 Trace,区分页面原始函数与扩展注入的观测 Hook;
|
||||
- 自动推断明文来源、密码调用和线上请求字段之间的关联;
|
||||
- 在证据充分时直接生成请求或响应方向的明文网关;
|
||||
- 在普通录制无法保留状态时,使用 Chromium Deep Capture 捕获闭包、模块脚本、`CryptoKey`、WebAssembly 实例或多调用请求事务;
|
||||
- 将捕获到的业务调用保存为文档绑定的页面 Callable,无需向外导出页面密钥;
|
||||
- 使用类型化 Pipeline 组合上下文读取、页面调用、白名单转换、字段装配和输出写入;
|
||||
- 在本地回放中使用录制的短时样本验证转换关系;
|
||||
- 与 Yakit Web Fuzzer 联动:编辑逻辑明文,由真实页面生成线上密文或签名,同时并排查看“明文 / 线上”报文。
|
||||
|
||||
You can learn more in
|
||||
the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
|
||||
当前观测与推断适配层覆盖:
|
||||
|
||||
To learn React, check out the [React documentation](https://reactjs.org/).
|
||||
- Web Crypto API;
|
||||
- CryptoJS;
|
||||
- JSEncrypt;
|
||||
- jsrsasign;
|
||||
- node-forge;
|
||||
- sm-crypto;
|
||||
- JOSE;
|
||||
- libsodium;
|
||||
- TweetNaCl;
|
||||
- Noble;
|
||||
- OpenPGP。
|
||||
|
||||
### Code Splitting
|
||||
适配器用于识别通用调用语义,并不意味着所有混淆代码都可以无条件自动还原。自动化程度取决于录制证据是否能够证明“明文输入 → 页面调用 → 请求字段”或“线上响应字段 → 页面调用 → 明文输出”的完整链路;证据不足时,界面会明确展示缺失环节,并引导进入深度捕获或 AI 辅助分析。
|
||||
|
||||
This section has moved
|
||||
here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
|
||||
### 2. 登录态上下文与 AI Agent 协作
|
||||
|
||||
### Analyzing the Bundle Size
|
||||
扩展可以把用户明确共享的浏览器页面转换为适合 Agent 使用的结构化上下文,而不是直接导出完整 HTML 或浏览器 Profile。
|
||||
|
||||
This section has moved
|
||||
here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
|
||||
- 采集页面文档信息、认证信号、表单、交互元素、开放 Shadow DOM、Storage 与 Cookie 清单;
|
||||
- 使用文档绑定的节点引用执行检查、点击、聚焦、滚动和输入等操作;
|
||||
- 追踪上下文差异,帮助 Agent 判断登录、跳转和业务状态变化;
|
||||
- 在独立权限下调用页面已有函数,或执行表达式与程序级 Eval;
|
||||
- 捕获已授权文档的真实网络请求,并生成可在 Yakit 中重放的报文;
|
||||
- 将录制 Trace、Callable、Transform Profile、请求事务和验证结果作为 Agent 工具能力;
|
||||
- 在 Agent 遇到扫码、MFA、CAPTCHA 或设备确认时创建“人工接管”任务,聚焦目标标签页并等待用户完成后继续。
|
||||
|
||||
### Making a Progressive Web App
|
||||
程序级 Eval、敏感网络字段、深度捕获和页面控制均属于高风险 Scope,不会被只读共享会话隐式包含。
|
||||
|
||||
This section has moved
|
||||
here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
|
||||
### 3. 双身份水平与垂直授权测试
|
||||
|
||||
### Advanced Configuration
|
||||
授权测试工作区用于组织两个真实登录身份,并以可复核的方式验证资源访问或权限动作。
|
||||
|
||||
This section has moved
|
||||
here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
|
||||
- 在普通窗口、无痕窗口或其他受支持的隔离上下文中选择身份 A / B;
|
||||
- 校验 Cookie Store、认证材料和页面上下文是否真正隔离;
|
||||
- 自动读取双方最近的同类业务请求,建立 A/B 正常基线;
|
||||
- 从 Query、Path、Header、表单或结构化 Body 中提取资源候选;
|
||||
- 水平授权测试使用固定请求预算构造 A-own、B-own、A-to-B、B-to-A 四项矩阵;
|
||||
- 垂直授权测试对比低权限控制请求与高权限目标动作,并明确提示潜在副作用;
|
||||
- 对状态码、响应结构、业务字段和目标身份正常响应进行差异比较;
|
||||
- 对时间戳、请求 ID 等易变噪声进行归一化,保留可解释的业务差异;
|
||||
- 将短时证据包交给 Yakit 与 AI Agent 深入分析,同时避免用插件预判结论暗示 AI;
|
||||
- 由确定性证据给出“观察到什么”,由用户、业务规则和独立 AI 复核决定是否构成真实授权缺陷。
|
||||
|
||||
### Deployment
|
||||
扩展不会因为交叉请求返回 `200` 就直接判定越权,也不会绕过真实身份隔离要求。
|
||||
|
||||
This section has moved
|
||||
here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
|
||||
### 4. 自动代理与规则系统
|
||||
|
||||
### `npm run build` fails to minify
|
||||
代理模块面向日常安全测试和多出口切换,交互方式接近现代化的 SwitchyOmega / ZeroOmega 工作流,但针对大规则集和扩展运行时做了重新设计。
|
||||
|
||||
This section has moved
|
||||
here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
|
||||
- 创建并管理多个代理出口;
|
||||
- 为不同域名、URL 模式或规则条件选择指定出口;
|
||||
- 支持直连、代理和自动切换情景;
|
||||
- 在 Popup 中快速切换当前出口,或为当前站点建立规则;
|
||||
- 导入和更新远程规则订阅;
|
||||
- 将规则编译为 PAC,并在应用前完成规范化和错误检查;
|
||||
- 使用 IndexedDB 按块保存大型规则源,避免把完整订阅反复塞入同步状态;
|
||||
- 缓存有限数量的编译产物,并清理过期 Revision;
|
||||
- 通过分页与搜索读取规则,不要求一次渲染全部内容。
|
||||
|
||||
该模块只决定浏览器请求应当走哪个代理出口。Yak MITM 可以作为其中一个代理出口使用,但扩展不会替用户控制或改变 MITM 内部规则。
|
||||
|
||||
### 5. Cookie Editor 与 User-Agent 快速切换
|
||||
|
||||
Popup 提供针对当前站点的高频操作,Options 提供完整管理界面。
|
||||
|
||||
- 查看、添加、编辑和删除当前站点 Cookie;
|
||||
- 支持 Domain、Path、SameSite、安全标记与分区 Cookie 元数据;
|
||||
- 支持 Cookie 过滤、导入与导出;
|
||||
- 提供常用设备 User-Agent 模板;
|
||||
- 创建、保存和删除自定义 User-Agent;
|
||||
- 将 User-Agent 分配给指定 Hostname,并立即作用于真实网络请求头。
|
||||
|
||||
User-Agent 工具只修改网络请求头,不伪装 `navigator`、Client Hints、屏幕信息、Canvas、TLS 或其他浏览器指纹。界面会明确提示这一边界。
|
||||
|
||||
### 6. 安全配对与浏览器共享会话
|
||||
|
||||
Yak gRPC 进程内置 Browser Bridge v3,扩展无需额外启动桥接脚本,也不依赖手工复制的长期 Token。
|
||||
|
||||
- 首次配对显示六位校验码,由用户同时在扩展与 Yakit 中确认;
|
||||
- 扩展生成不可导出的 ECDSA P-256 安装身份,Yak 保存独立引擎身份;
|
||||
- 后续连接通过双向身份、签名挑战、扩展 Origin 和安装 ID 完成认证;
|
||||
- 支持多个浏览器设备同时在线,并按设备 ID 精确路由任务;
|
||||
- 共享会话绑定标签页、Frame、文档、Origin、Task、Scope 和过期时间;
|
||||
- 页面刷新、文档替换或跨来源导航不会静默继承原授权;
|
||||
- 用户可以随时暂停 Agent、撤销共享会话或在 Yakit 中撤销整个浏览器设备;
|
||||
- 审计日志只记录方法、目标类型、耗时、结果和错误码等元数据,不保存 Cookie 值、页面正文、Eval 源码、请求载荷或执行结果。
|
||||
|
||||
## 产品界面
|
||||
|
||||
| 界面 | 主要用途 |
|
||||
| --- | --- |
|
||||
| Popup | 查看当前页面与引擎状态;快速切换代理、Cookie 和 User-Agent;进入完整工作区。 |
|
||||
| Options | 运行概览、授权测试、代理出口、自动切换、规则订阅、网络活动、Cookie Editor、UA 管理、登录态工作区、引擎连接与操作记录。 |
|
||||
| 页面悬浮面板 | 贴近当前页面的轻量操作入口,可吸附屏幕边缘,并在需要时展开代理、接管和任务状态。 |
|
||||
| Yakit 浏览器集成 | 管理已配对设备、执行浏览器任务、查看录制与明文网关,并与 Web Fuzzer 联动。 |
|
||||
| Yak AI Agent | 调用经过授权的浏览器能力,分析证据、编排流程,并在必须人工参与时等待用户接管。 |
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 环境准备
|
||||
|
||||
完整能力需要以下组件:
|
||||
|
||||
- Chrome / Chromium / Edge,或受支持的 Firefox;
|
||||
- Node.js 与 pnpm;
|
||||
- 包含 Browser Bridge v3 的 Yak 引擎;
|
||||
- 包含“浏览器集成”工作区的 Yakit。
|
||||
|
||||
仅使用代理、Cookie、User-Agent 等本地工具时,不要求连接 Yak 引擎。
|
||||
|
||||
### 安装依赖并启动开发模式
|
||||
|
||||
```bash
|
||||
git clone https://github.com/yaklang/yaklang-chrome-extension.git
|
||||
cd yaklang-chrome-extension
|
||||
pnpm install
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
如果浏览器没有自动加载扩展:
|
||||
|
||||
1. 打开 `chrome://extensions`;
|
||||
2. 开启“开发者模式”;
|
||||
3. 选择“加载已解压的扩展程序”;
|
||||
4. 加载 `.output/chrome-mv3-dev`。
|
||||
|
||||
### WSL 开发
|
||||
|
||||
WXT 在 WSL 环境中不会自动打开浏览器。项目提供了单独的启动器:
|
||||
|
||||
```bash
|
||||
pnpm dev:wsl
|
||||
```
|
||||
|
||||
开发 Profile 位于 `.wxt/chrome-wsl-profile`。当前稳定版 Chrome 不接受无人值守的 `--load-extension` 参数时,首次仍需在 `chrome://extensions` 手动加载 `.output/chrome-mv3-dev`;之后该 Profile 会记住扩展。
|
||||
|
||||
如需指定 Chromium 或 Chrome for Testing:
|
||||
|
||||
```bash
|
||||
CHROME_PATH=/path/to/chromium pnpm dev:wsl
|
||||
```
|
||||
|
||||
## 连接 Yak 与 Yakit
|
||||
|
||||
在 Yak 仓库中启动 gRPC 引擎:
|
||||
|
||||
```bash
|
||||
go run common/yak/cmd/yak.go grpc --host 0.0.0.0
|
||||
```
|
||||
|
||||
标准启动会在 `127.0.0.1:64333` 自动启动 Browser Bridge,无需额外参数。
|
||||
|
||||
首次配对:
|
||||
|
||||
1. 在 Yakit 打开“系统设置 → 浏览器集成”;
|
||||
2. 在扩展 Options 打开“引擎连接”;
|
||||
3. 点击“查找本机 Yakit”;
|
||||
4. 对比扩展与 Yakit 显示的六位校验码;
|
||||
5. 确认一致后,在 Yakit 批准待配对浏览器。
|
||||
|
||||
配对完成后,设备身份会持久保存,后续通过签名挑战自动认证。若在 Yakit 中撤销设备,当前连接会立即关闭,浏览器必须重新配对。
|
||||
|
||||
非默认部署可以使用:
|
||||
|
||||
- `--browser-extension-bridge-port`:修改 Bridge 监听端口;
|
||||
- `--disable-browser-extension-bridge`:显式关闭 Browser Bridge;
|
||||
- Native Messaging:在浏览器无法直接访问回环 Bridge,或需要受管部署时使用。
|
||||
|
||||
Native Host 的构建与注册方式见 [native-host/README.md](./native-host/README.md)。
|
||||
|
||||
## 典型工作流
|
||||
|
||||
### 从真实页面生成明文网关
|
||||
|
||||
1. 打开目标页面,在扩展中选择对应标签页;
|
||||
2. 进入“网络活动”,在“录制”中开始一次操作;
|
||||
3. 回到目标页面,完成一次登录、查询、提交或解密操作;
|
||||
4. 停止录制,查看按时间排序的业务 Trace 与自动推断 Profile;
|
||||
5. 证据充分时直接生成明文网关;证据不足时按提示进入“深度捕获”,再执行一次最小业务动作;
|
||||
6. 在“明文网关”查看数据流、页面函数、字段映射和本地回放结果;
|
||||
7. 保存后创建或复用浏览器共享会话;
|
||||
8. 在 Yakit Web Fuzzer 选择对应的浏览器明文网关,编辑明文并发送。
|
||||
|
||||
页面刷新或跨文档导航后,依赖旧页面闭包的 Callable 可能失效。扩展会保留录制证据,但不会把旧函数静默绑定到新文档。
|
||||
|
||||
### 进行双身份授权测试
|
||||
|
||||
1. 准备两个已经登录不同账号、且认证上下文真正隔离的页面;
|
||||
2. 在“授权测试”中分别选择身份 A 与身份 B;
|
||||
3. 执行身份校验并开始双方请求捕获;
|
||||
4. 在两个页面分别完成同类业务动作;
|
||||
5. 让扩展自动选择正常基线,或手动确认请求;
|
||||
6. 选择资源字段或权限动作,审阅确定性测试计划;
|
||||
7. 确认请求预算与潜在副作用后执行;
|
||||
8. 查看四项矩阵、报文、结构化差异和业务归属证据;
|
||||
9. 将短时证据包交给 Yakit / AI Agent 做独立复核。
|
||||
|
||||
同一浏览器普通窗口中的两个标签页通常共享 Cookie,不能仅凭“两个 Tab”证明身份隔离。Chromium 推荐使用普通窗口与无痕窗口,Firefox 可使用受支持的隔离上下文。
|
||||
|
||||
### 让 Agent 使用登录后的页面
|
||||
|
||||
1. 在“引擎连接”中勾选需要共享的 Tab 与 Frame;
|
||||
2. 选择只读或控制权限预设,并设置 15 分钟至 4 小时的有效期;
|
||||
3. 如确有必要,单独开启程序级 Eval;
|
||||
4. 创建浏览器共享会话;
|
||||
5. 在 Yakit 或 Yak AI Agent 中选择对应设备执行任务;
|
||||
6. 随时在扩展中暂停、恢复或撤销会话。
|
||||
|
||||
## 构建与验证
|
||||
|
||||
### 常用命令
|
||||
|
||||
| 命令 | 用途 |
|
||||
| --- | --- |
|
||||
| `pnpm dev` | 启动 Chromium 开发模式。 |
|
||||
| `pnpm dev:wsl` | 使用持久 Profile 启动 WSL 开发环境。 |
|
||||
| `pnpm dev:firefox` | 启动 Firefox 开发模式。 |
|
||||
| `pnpm compile` | 运行 TypeScript 类型检查,不生成文件。 |
|
||||
| `pnpm test` | 运行 Vitest 测试。 |
|
||||
| `pnpm build:store` | 构建 Chrome Store 包。 |
|
||||
| `pnpm build:enterprise` | 构建本地或企业受管部署包。 |
|
||||
| `pnpm build:firefox` | 构建 Firefox MV2 包。 |
|
||||
| `pnpm build:firefox:amo` | 构建 Firefox MV3 AMO 包。 |
|
||||
| `pnpm verify:production` | 运行测试、类型检查、多目标构建和生产策略审计。 |
|
||||
| `pnpm verify:ui:store` | 验证 Chrome Store 运行路径。 |
|
||||
| `pnpm verify:ui:enterprise` | 验证 Enterprise User Scripts 路径。 |
|
||||
| `pnpm verify:ui:enterprise:fallback` | 验证 Enterprise 注入回退路径。 |
|
||||
| `pnpm verify:native` | 验证 Native Messaging Host 与 Bridge 链路。 |
|
||||
|
||||
`verify:production` 会连续执行测试、类型检查和多个浏览器目标构建,资源占用明显高于单项命令。日常开发建议先运行与改动相关的测试和 `pnpm compile`,发布前再执行完整验证。
|
||||
|
||||
### 构建差异
|
||||
|
||||
| 构建 | 页面执行通道 | 适用场景 |
|
||||
| --- | --- | --- |
|
||||
| Chrome Store | User Scripts MAIN,不包含直接 Eval 注入回退 | 商店策略兼容分发。 |
|
||||
| Chrome Enterprise | User Scripts MAIN,并提供受控的打包回退通道 | 本地安装、企业受管与高级测试。 |
|
||||
| Firefox MV2 | Firefox 页面注入通道 | 本地与企业 Firefox 环境。 |
|
||||
| Firefox MV3 AMO | Invoke-only 公共分发包 | Firefox AMO 策略兼容分发。 |
|
||||
|
||||
Chrome Store 构建声明 Chrome 138+。用户需要在扩展详情页开启“允许用户脚本”,页面主世界能力才能正常工作;未开启时扩展会明确报告原因,不会静默降级为直接 Eval。
|
||||
|
||||
### 发布与下载
|
||||
|
||||
发布由 GitHub Actions 的 **Build and Release** workflow(手动触发)完成:执行 `verify:production` 全量校验后,将四个变体打包为不可变的版本化产物上传到 OSS,再发布机器可读的 manifest,并从公网侧回读验证。CI 在每次 push / PR 时运行同一套构建与审计。
|
||||
|
||||
**下载入口**(不要硬编码版本号):
|
||||
|
||||
```
|
||||
https://aliyun-oss.yaklang.com/chrome-extension/manifest.json
|
||||
```
|
||||
|
||||
manifest 的 `latest` 指向最新版本,`versions[0]` 为完整记录,最多保留 10 个历史版本。每个版本按 `variant`(`chrome-store` / `chrome-enterprise` / `firefox` / `firefox-amo`)匹配 artifact,字段包括 `url`、`filename`、`sha256`、`size` 与 `checksum_url`;manifest 自身的 SHA-256 在同目录的 `manifest.json.sha256.txt`。
|
||||
|
||||
推荐的消费流程:
|
||||
|
||||
1. 拉取 `manifest.json`(缓存 5 分钟),按需选择版本与变体;
|
||||
2. 下载 artifact(版本化 URL 永不变更,缓存一年)到临时文件;
|
||||
3. 校验 `size` 与 `sha256`(或对比 `checksum_url` 内容)后,解压并安装;
|
||||
4. 变体用途见上表“构建差异”。
|
||||
|
||||
**发布契约**:
|
||||
|
||||
- 版本化产物不可变:URL 形如 `…/chrome-extension/<version>/<variant>-<version>.zip`,重复发布同版本时内容一致则跳过、不一致则流水线报错拒绝覆盖;
|
||||
- `manifest.json` 可变、缓存 5 分钟,先发布 manifest 再发布其校验文件,消费方可用校验文件识别中间态;
|
||||
- 发布 job 结束前有独立的 verify job 从公网下载全部产物,复核 sha256、缓存头与 zip 内 `manifest.json` 版本。
|
||||
|
||||
## 权限与数据边界
|
||||
|
||||
扩展声明 `tabs`、`scripting`、`cookies`、`proxy`、`webRequest`、`webNavigation`、`debugger` 等权限,是为了在用户主动选择的目标页面上提供对应安全测试能力。`nativeMessaging` 是可选权限,仅在用户选择 Native 模式时请求。
|
||||
|
||||
默认数据策略:
|
||||
|
||||
- Cookie、Storage、表单值、请求 Header / Body 和录制值预览分别受独立 Scope 控制;
|
||||
- 敏感网络字段与录制短时样本默认关闭或仅在当前会话保留;
|
||||
- 页面上下文采用有界结构化快照,不导出完整页面 HTML;
|
||||
- Deep Capture 可以保留页面内对象引用,但不会主动导出不可提取密钥;
|
||||
- 操作审计与诊断导出不包含 URL 参数值、Cookie、载荷、Eval 代码、调用参数或结果;
|
||||
- 远程订阅、代理配置和浏览器状态保存在扩展本地存储或 IndexedDB;
|
||||
- 撤销 Grant、关闭目标文档或断开设备会终止相关远程能力。
|
||||
|
||||
更完整的 Capability、Grant、Bridge、Native Messaging、网络捕获、Recorder、Deep Capture 和 Transform Gateway 设计见 [ARCHITECTURE.md](./ARCHITECTURE.md)。视觉与交互规范见 [DESIGN.md](./DESIGN.md)。
|
||||
|
||||
## 浏览器支持与已知边界
|
||||
|
||||
- Chromium 系浏览器提供完整 Deep Capture 调试能力;Firefox 不提供完全相同的 Debugger 协议能力;
|
||||
- Store、Enterprise、Firefox MV2 与 Firefox AMO 构建的页面执行通道和权限不同;
|
||||
- 页面导航可能使文档绑定节点、Grant、Callable 和 Transform Profile 失效,扩展不会跨文档静默复用高权限引用;
|
||||
- 前端代码严重混淆、动态加载、原生模块、远程证明或服务端参与的算法不保证全自动还原;
|
||||
- 自动推断只在证据满足约束时生成 Profile,必要时仍需要测试者选择业务函数、确认字段语义或使用 AI 分析;
|
||||
- User-Agent 修改不等于完整设备指纹伪装;
|
||||
- 浏览器会话能够复用登录态,但不能替代目标授权、业务理解和测试人员的最终判断。
|
||||
|
||||
## 目录结构
|
||||
|
||||
```text
|
||||
src/
|
||||
├── app/background/ # Background 路由与功能 Handler
|
||||
├── components/ # 品牌与共享 UI 组件
|
||||
├── entrypoints/ # Popup、Options、Content、Floating、MAIN-world 入口
|
||||
├── features/ # 代理、录制、加解密、授权测试、Bridge 等领域模块
|
||||
├── platform/ # 浏览器、策略、消息与存储适配层
|
||||
├── protocol/ # Bridge、Capability、Storage 与 Transform Schema
|
||||
├── shared/ # 无状态公共工具
|
||||
├── styles/ # 设计 Token、主题与基础 UI 样式
|
||||
└── types/ # 跨模块领域模型
|
||||
|
||||
native-host/ # Native Messaging 安装脚本与说明
|
||||
public/ # 图标、品牌资源与 Managed Storage Schema
|
||||
scripts/ # 构建审计、浏览器验证与契约测试
|
||||
ARCHITECTURE.md # 系统架构与安全边界
|
||||
DESIGN.md # UI 设计系统
|
||||
wxt.config.ts # WXT 与浏览器 Manifest 配置
|
||||
```
|
||||
|
||||
## 相关项目
|
||||
|
||||
- [Yaklang](https://github.com/yaklang/yaklang):Yak 语言、安全引擎、Browser Bridge 与 AI Agent 能力;
|
||||
- [Yakit](https://github.com/yaklang/yakit):安全测试桌面端、浏览器集成工作区与 Web Fuzzer;
|
||||
- [WXT](https://wxt.dev/):本扩展使用的跨浏览器扩展开发框架。
|
||||
|
||||
## 负责任地使用
|
||||
|
||||
浏览器真实上下文能够显著降低复杂登录态、前端加密和授权测试的操作成本,也意味着错误操作可能读取敏感数据、发送真实请求或改变业务状态。请在执行前确认目标范围、账号权限、请求预算和副作用,并保留必要的人工复核。
|
||||
|
||||
Yakit Browser Agent 的目标不是替用户隐藏风险,而是把风险、证据、权限和执行现场放在同一个可理解、可控制的工作流中。
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const paths = require('./paths');
|
||||
|
||||
// Make sure that including paths.js after env.js will read .env variables.
|
||||
delete require.cache[require.resolve('./paths')];
|
||||
|
||||
const NODE_ENV = process.env.NODE_ENV;
|
||||
if (!NODE_ENV) {
|
||||
throw new Error(
|
||||
'The NODE_ENV environment variable is required but was not specified.'
|
||||
);
|
||||
}
|
||||
|
||||
// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
|
||||
const dotenvFiles = [
|
||||
`${paths.dotenv}.${NODE_ENV}.local`,
|
||||
// Don't include `.env.local` for `test` environment
|
||||
// since normally you expect tests to produce the same
|
||||
// results for everyone
|
||||
NODE_ENV !== 'test' && `${paths.dotenv}.local`,
|
||||
`${paths.dotenv}.${NODE_ENV}`,
|
||||
paths.dotenv,
|
||||
].filter(Boolean);
|
||||
|
||||
// Load environment variables from .env* files. Suppress warnings using silent
|
||||
// if this file is missing. dotenv will never modify any environment variables
|
||||
// that have already been set. Variable expansion is supported in .env files.
|
||||
// https://github.com/motdotla/dotenv
|
||||
// https://github.com/motdotla/dotenv-expand
|
||||
dotenvFiles.forEach(dotenvFile => {
|
||||
if (fs.existsSync(dotenvFile)) {
|
||||
require('dotenv-expand')(
|
||||
require('dotenv').config({
|
||||
path: dotenvFile,
|
||||
})
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// We support resolving modules according to `NODE_PATH`.
|
||||
// This lets you use absolute paths in imports inside large monorepos:
|
||||
// https://github.com/facebook/create-react-app/issues/253.
|
||||
// It works similar to `NODE_PATH` in Node itself:
|
||||
// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders
|
||||
// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored.
|
||||
// Otherwise, we risk importing Node.js core modules into an app instead of webpack shims.
|
||||
// https://github.com/facebook/create-react-app/issues/1023#issuecomment-265344421
|
||||
// We also resolve them to make sure all tools using them work consistently.
|
||||
const appDirectory = fs.realpathSync(process.cwd());
|
||||
process.env.NODE_PATH = (process.env.NODE_PATH || '')
|
||||
.split(path.delimiter)
|
||||
.filter(folder => folder && !path.isAbsolute(folder))
|
||||
.map(folder => path.resolve(appDirectory, folder))
|
||||
.join(path.delimiter);
|
||||
|
||||
// Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be
|
||||
// injected into the application via DefinePlugin in webpack configuration.
|
||||
const REACT_APP = /^REACT_APP_/i;
|
||||
|
||||
function getClientEnvironment(publicUrl) {
|
||||
const raw = Object.keys(process.env)
|
||||
.filter(key => REACT_APP.test(key))
|
||||
.reduce(
|
||||
(env, key) => {
|
||||
env[key] = process.env[key];
|
||||
return env;
|
||||
},
|
||||
{
|
||||
// Useful for determining whether we’re running in production mode.
|
||||
// Most importantly, it switches React into the correct mode.
|
||||
NODE_ENV: process.env.NODE_ENV || 'development',
|
||||
// Useful for resolving the correct path to static assets in `public`.
|
||||
// For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.
|
||||
// This should only be used as an escape hatch. Normally you would put
|
||||
// images into the `src` and `import` them in code to get their paths.
|
||||
PUBLIC_URL: publicUrl,
|
||||
// We support configuring the sockjs pathname during development.
|
||||
// These settings let a developer run multiple simultaneous projects.
|
||||
// They are used as the connection `hostname`, `pathname` and `port`
|
||||
// in webpackHotDevClient. They are used as the `sockHost`, `sockPath`
|
||||
// and `sockPort` options in webpack-dev-server.
|
||||
WDS_SOCKET_HOST: process.env.WDS_SOCKET_HOST,
|
||||
WDS_SOCKET_PATH: process.env.WDS_SOCKET_PATH,
|
||||
WDS_SOCKET_PORT: process.env.WDS_SOCKET_PORT,
|
||||
// Whether or not react-refresh is enabled.
|
||||
// It is defined here so it is available in the webpackHotDevClient.
|
||||
FAST_REFRESH: process.env.FAST_REFRESH !== 'false',
|
||||
}
|
||||
);
|
||||
// Stringify all values so we can feed into webpack DefinePlugin
|
||||
const stringified = {
|
||||
'process.env': Object.keys(raw).reduce((env, key) => {
|
||||
env[key] = JSON.stringify(raw[key]);
|
||||
return env;
|
||||
}, {}),
|
||||
};
|
||||
|
||||
return { raw, stringified };
|
||||
}
|
||||
|
||||
module.exports = getClientEnvironment;
|
||||
@@ -1,66 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
const chalk = require('react-dev-utils/chalk');
|
||||
const paths = require('./paths');
|
||||
|
||||
// Ensure the certificate and key provided are valid and if not
|
||||
// throw an easy to debug error
|
||||
function validateKeyAndCerts({ cert, key, keyFile, crtFile }) {
|
||||
let encrypted;
|
||||
try {
|
||||
// publicEncrypt will throw an error with an invalid cert
|
||||
encrypted = crypto.publicEncrypt(cert, Buffer.from('test'));
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
`The certificate "${chalk.yellow(crtFile)}" is invalid.\n${err.message}`
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
// privateDecrypt will throw an error with an invalid key
|
||||
crypto.privateDecrypt(key, encrypted);
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
`The certificate key "${chalk.yellow(keyFile)}" is invalid.\n${
|
||||
err.message
|
||||
}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Read file and throw an error if it doesn't exist
|
||||
function readEnvFile(file, type) {
|
||||
if (!fs.existsSync(file)) {
|
||||
throw new Error(
|
||||
`You specified ${chalk.cyan(
|
||||
type
|
||||
)} in your env, but the file "${chalk.yellow(file)}" can't be found.`
|
||||
);
|
||||
}
|
||||
return fs.readFileSync(file);
|
||||
}
|
||||
|
||||
// Get the https config
|
||||
// Return cert files if provided in env, otherwise just true or false
|
||||
function getHttpsConfig() {
|
||||
const { SSL_CRT_FILE, SSL_KEY_FILE, HTTPS } = process.env;
|
||||
const isHttps = HTTPS === 'true';
|
||||
|
||||
if (isHttps && SSL_CRT_FILE && SSL_KEY_FILE) {
|
||||
const crtFile = path.resolve(paths.appPath, SSL_CRT_FILE);
|
||||
const keyFile = path.resolve(paths.appPath, SSL_KEY_FILE);
|
||||
const config = {
|
||||
cert: readEnvFile(crtFile, 'SSL_CRT_FILE'),
|
||||
key: readEnvFile(keyFile, 'SSL_KEY_FILE'),
|
||||
};
|
||||
|
||||
validateKeyAndCerts({ ...config, keyFile, crtFile });
|
||||
return config;
|
||||
}
|
||||
return isHttps;
|
||||
}
|
||||
|
||||
module.exports = getHttpsConfig;
|
||||
@@ -1,29 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const babelJest = require('babel-jest').default;
|
||||
|
||||
const hasJsxRuntime = (() => {
|
||||
if (process.env.DISABLE_NEW_JSX_TRANSFORM === 'true') {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
require.resolve('react/jsx-runtime');
|
||||
return true;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
})();
|
||||
|
||||
module.exports = babelJest.createTransformer({
|
||||
presets: [
|
||||
[
|
||||
require.resolve('babel-preset-react-app'),
|
||||
{
|
||||
runtime: hasJsxRuntime ? 'automatic' : 'classic',
|
||||
},
|
||||
],
|
||||
],
|
||||
babelrc: false,
|
||||
configFile: false,
|
||||
});
|
||||
@@ -1,14 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
// This is a custom Jest transformer turning style imports into empty objects.
|
||||
// http://facebook.github.io/jest/docs/en/webpack.html
|
||||
|
||||
module.exports = {
|
||||
process() {
|
||||
return 'module.exports = {};';
|
||||
},
|
||||
getCacheKey() {
|
||||
// The output is always the same.
|
||||
return 'cssTransform';
|
||||
},
|
||||
};
|
||||
@@ -1,40 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const path = require('path');
|
||||
const camelcase = require('camelcase');
|
||||
|
||||
// This is a custom Jest transformer turning file imports into filenames.
|
||||
// http://facebook.github.io/jest/docs/en/webpack.html
|
||||
|
||||
module.exports = {
|
||||
process(src, filename) {
|
||||
const assetFilename = JSON.stringify(path.basename(filename));
|
||||
|
||||
if (filename.match(/\.svg$/)) {
|
||||
// Based on how SVGR generates a component name:
|
||||
// https://github.com/smooth-code/svgr/blob/01b194cf967347d43d4cbe6b434404731b87cf27/packages/core/src/state.js#L6
|
||||
const pascalCaseFilename = camelcase(path.parse(filename).name, {
|
||||
pascalCase: true,
|
||||
});
|
||||
const componentName = `Svg${pascalCaseFilename}`;
|
||||
return `const React = require('react');
|
||||
module.exports = {
|
||||
__esModule: true,
|
||||
default: ${assetFilename},
|
||||
ReactComponent: React.forwardRef(function ${componentName}(props, ref) {
|
||||
return {
|
||||
$$typeof: Symbol.for('react.element'),
|
||||
type: 'svg',
|
||||
ref: ref,
|
||||
key: null,
|
||||
props: Object.assign({}, props, {
|
||||
children: ${assetFilename}
|
||||
})
|
||||
};
|
||||
}),
|
||||
};`;
|
||||
}
|
||||
|
||||
return `module.exports = ${assetFilename};`;
|
||||
},
|
||||
};
|
||||
@@ -1,134 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const paths = require('./paths');
|
||||
const chalk = require('react-dev-utils/chalk');
|
||||
const resolve = require('resolve');
|
||||
|
||||
/**
|
||||
* Get additional module paths based on the baseUrl of a compilerOptions object.
|
||||
*
|
||||
* @param {Object} options
|
||||
*/
|
||||
function getAdditionalModulePaths(options = {}) {
|
||||
const baseUrl = options.baseUrl;
|
||||
|
||||
if (!baseUrl) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const baseUrlResolved = path.resolve(paths.appPath, baseUrl);
|
||||
|
||||
// We don't need to do anything if `baseUrl` is set to `node_modules`. This is
|
||||
// the default behavior.
|
||||
if (path.relative(paths.appNodeModules, baseUrlResolved) === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Allow the user set the `baseUrl` to `appSrc`.
|
||||
if (path.relative(paths.appSrc, baseUrlResolved) === '') {
|
||||
return [paths.appSrc];
|
||||
}
|
||||
|
||||
// If the path is equal to the root directory we ignore it here.
|
||||
// We don't want to allow importing from the root directly as source files are
|
||||
// not transpiled outside of `src`. We do allow importing them with the
|
||||
// absolute path (e.g. `src/Components/Button.js`) but we set that up with
|
||||
// an alias.
|
||||
if (path.relative(paths.appPath, baseUrlResolved) === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Otherwise, throw an error.
|
||||
throw new Error(
|
||||
chalk.red.bold(
|
||||
"Your project's `baseUrl` can only be set to `src` or `node_modules`." +
|
||||
' Create React App does not support other values at this time.'
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get webpack aliases based on the baseUrl of a compilerOptions object.
|
||||
*
|
||||
* @param {*} options
|
||||
*/
|
||||
function getWebpackAliases(options = {}) {
|
||||
const baseUrl = options.baseUrl;
|
||||
|
||||
if (!baseUrl) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const baseUrlResolved = path.resolve(paths.appPath, baseUrl);
|
||||
|
||||
if (path.relative(paths.appPath, baseUrlResolved) === '') {
|
||||
return {
|
||||
src: paths.appSrc,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get jest aliases based on the baseUrl of a compilerOptions object.
|
||||
*
|
||||
* @param {*} options
|
||||
*/
|
||||
function getJestAliases(options = {}) {
|
||||
const baseUrl = options.baseUrl;
|
||||
|
||||
if (!baseUrl) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const baseUrlResolved = path.resolve(paths.appPath, baseUrl);
|
||||
|
||||
if (path.relative(paths.appPath, baseUrlResolved) === '') {
|
||||
return {
|
||||
'^src/(.*)$': '<rootDir>/src/$1',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function getModules() {
|
||||
// Check if TypeScript is setup
|
||||
const hasTsConfig = fs.existsSync(paths.appTsConfig);
|
||||
const hasJsConfig = fs.existsSync(paths.appJsConfig);
|
||||
|
||||
if (hasTsConfig && hasJsConfig) {
|
||||
throw new Error(
|
||||
'You have both a tsconfig.json and a jsconfig.json. If you are using TypeScript please remove your jsconfig.json file.'
|
||||
);
|
||||
}
|
||||
|
||||
let config;
|
||||
|
||||
// If there's a tsconfig.json we assume it's a
|
||||
// TypeScript project and set up the config
|
||||
// based on tsconfig.json
|
||||
if (hasTsConfig) {
|
||||
const ts = require(resolve.sync('typescript', {
|
||||
basedir: paths.appNodeModules,
|
||||
}));
|
||||
config = ts.readConfigFile(paths.appTsConfig, ts.sys.readFile).config;
|
||||
// Otherwise we'll check if there is jsconfig.json
|
||||
// for non TS projects.
|
||||
} else if (hasJsConfig) {
|
||||
config = require(paths.appJsConfig);
|
||||
}
|
||||
|
||||
config = config || {};
|
||||
const options = config.compilerOptions || {};
|
||||
|
||||
const additionalModulePaths = getAdditionalModulePaths(options);
|
||||
|
||||
return {
|
||||
additionalModulePaths: additionalModulePaths,
|
||||
webpackAliases: getWebpackAliases(options),
|
||||
jestAliases: getJestAliases(options),
|
||||
hasTsConfig,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = getModules();
|
||||
@@ -1,77 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const getPublicUrlOrPath = require('react-dev-utils/getPublicUrlOrPath');
|
||||
|
||||
// Make sure any symlinks in the project folder are resolved:
|
||||
// https://github.com/facebook/create-react-app/issues/637
|
||||
const appDirectory = fs.realpathSync(process.cwd());
|
||||
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
|
||||
|
||||
// We use `PUBLIC_URL` environment variable or "homepage" field to infer
|
||||
// "public path" at which the app is served.
|
||||
// webpack needs to know it to put the right <script> hrefs into HTML even in
|
||||
// single-page apps that may serve index.html for nested URLs like /todos/42.
|
||||
// We can't use a relative path in HTML because we don't want to load something
|
||||
// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
|
||||
const publicUrlOrPath = getPublicUrlOrPath(
|
||||
process.env.NODE_ENV === 'development',
|
||||
require(resolveApp('package.json')).homepage,
|
||||
process.env.PUBLIC_URL
|
||||
);
|
||||
|
||||
const buildPath = process.env.BUILD_PATH || 'build';
|
||||
|
||||
const moduleFileExtensions = [
|
||||
'web.mjs',
|
||||
'mjs',
|
||||
'web.js',
|
||||
'js',
|
||||
'web.ts',
|
||||
'ts',
|
||||
'web.tsx',
|
||||
'tsx',
|
||||
'json',
|
||||
'web.jsx',
|
||||
'jsx',
|
||||
];
|
||||
|
||||
// Resolve file paths in the same order as webpack
|
||||
const resolveModule = (resolveFn, filePath) => {
|
||||
const extension = moduleFileExtensions.find(extension =>
|
||||
fs.existsSync(resolveFn(`${filePath}.${extension}`))
|
||||
);
|
||||
|
||||
if (extension) {
|
||||
return resolveFn(`${filePath}.${extension}`);
|
||||
}
|
||||
|
||||
return resolveFn(`${filePath}.js`);
|
||||
};
|
||||
|
||||
// config after eject: we're in ./config/
|
||||
module.exports = {
|
||||
dotenv: resolveApp('.env'),
|
||||
appPath: resolveApp('.'),
|
||||
appBuild: resolveApp(buildPath),
|
||||
appPublic: resolveApp('public'),
|
||||
appHtml: resolveApp('public/index.html'),
|
||||
appIndexJs: resolveModule(resolveApp, 'src/index'),
|
||||
appPackageJson: resolveApp('package.json'),
|
||||
appSrc: resolveApp('src'),
|
||||
appTsConfig: resolveApp('tsconfig.json'),
|
||||
appJsConfig: resolveApp('jsconfig.json'),
|
||||
yarnLockFile: resolveApp('yarn.lock'),
|
||||
testsSetup: resolveModule(resolveApp, 'src/setupTests'),
|
||||
proxySetup: resolveApp('src/setupProxy.js'),
|
||||
appNodeModules: resolveApp('node_modules'),
|
||||
appWebpackCache: resolveApp('node_modules/.cache'),
|
||||
appTsBuildInfoFile: resolveApp('node_modules/.cache/tsconfig.tsbuildinfo'),
|
||||
swSrc: resolveModule(resolveApp, 'src/service-worker'),
|
||||
publicUrlOrPath,
|
||||
};
|
||||
|
||||
|
||||
|
||||
module.exports.moduleFileExtensions = moduleFileExtensions;
|
||||
@@ -1,758 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const webpack = require('webpack');
|
||||
const resolve = require('resolve');
|
||||
const HtmlWebpackPlugin = require('html-webpack-plugin');
|
||||
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
|
||||
const InlineChunkHtmlPlugin = require('react-dev-utils/InlineChunkHtmlPlugin');
|
||||
const TerserPlugin = require('terser-webpack-plugin');
|
||||
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
|
||||
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
|
||||
const { WebpackManifestPlugin } = require('webpack-manifest-plugin');
|
||||
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
|
||||
const WorkboxWebpackPlugin = require('workbox-webpack-plugin');
|
||||
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
|
||||
const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent');
|
||||
const ESLintPlugin = require('eslint-webpack-plugin');
|
||||
const paths = require('./paths');
|
||||
const modules = require('./modules');
|
||||
const getClientEnvironment = require('./env');
|
||||
const ModuleNotFoundPlugin = require('react-dev-utils/ModuleNotFoundPlugin');
|
||||
const ForkTsCheckerWebpackPlugin =
|
||||
process.env.TSC_COMPILE_ON_ERROR === 'true'
|
||||
? require('react-dev-utils/ForkTsCheckerWarningWebpackPlugin')
|
||||
: require('react-dev-utils/ForkTsCheckerWebpackPlugin');
|
||||
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
|
||||
|
||||
const createEnvironmentHash = require('./webpack/persistentCache/createEnvironmentHash');
|
||||
|
||||
// Source maps are resource heavy and can cause out of memory issue for large source files.
|
||||
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
|
||||
|
||||
const reactRefreshRuntimeEntry = require.resolve('react-refresh/runtime');
|
||||
const reactRefreshWebpackPluginRuntimeEntry = require.resolve(
|
||||
'@pmmmwh/react-refresh-webpack-plugin'
|
||||
);
|
||||
const babelRuntimeEntry = require.resolve('babel-preset-react-app');
|
||||
const babelRuntimeEntryHelpers = require.resolve(
|
||||
'@babel/runtime/helpers/esm/assertThisInitialized',
|
||||
{ paths: [babelRuntimeEntry] }
|
||||
);
|
||||
const babelRuntimeRegenerator = require.resolve('@babel/runtime/regenerator', {
|
||||
paths: [babelRuntimeEntry],
|
||||
});
|
||||
|
||||
// Some apps do not need the benefits of saving a web request, so not inlining the chunk
|
||||
// makes for a smoother build process.
|
||||
const shouldInlineRuntimeChunk = process.env.INLINE_RUNTIME_CHUNK !== 'false';
|
||||
|
||||
const emitErrorsAsWarnings = process.env.ESLINT_NO_DEV_ERRORS === 'true';
|
||||
const disableESLintPlugin = process.env.DISABLE_ESLINT_PLUGIN === 'true';
|
||||
|
||||
const imageInlineSizeLimit = parseInt(
|
||||
process.env.IMAGE_INLINE_SIZE_LIMIT || '10000'
|
||||
);
|
||||
|
||||
// Check if TypeScript is setup
|
||||
const useTypeScript = fs.existsSync(paths.appTsConfig);
|
||||
|
||||
// Check if Tailwind config exists
|
||||
const useTailwind = fs.existsSync(
|
||||
path.join(paths.appPath, 'tailwind.config.js')
|
||||
);
|
||||
|
||||
// Get the path to the uncompiled service worker (if it exists).
|
||||
const swSrc = paths.swSrc;
|
||||
|
||||
// style files regexes
|
||||
const cssRegex = /\.css$/;
|
||||
const cssModuleRegex = /\.module\.css$/;
|
||||
const sassRegex = /\.(scss|sass)$/;
|
||||
const sassModuleRegex = /\.module\.(scss|sass)$/;
|
||||
|
||||
const hasJsxRuntime = (() => {
|
||||
if (process.env.DISABLE_NEW_JSX_TRANSFORM === 'true') {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
require.resolve('react/jsx-runtime');
|
||||
return true;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
})();
|
||||
|
||||
// This is the production and development configuration.
|
||||
// It is focused on developer experience, fast rebuilds, and a minimal bundle.
|
||||
module.exports = function (webpackEnv) {
|
||||
const isEnvDevelopment = webpackEnv === 'development';
|
||||
const isEnvProduction = webpackEnv === 'production';
|
||||
|
||||
// Variable used for enabling profiling in Production
|
||||
// passed into alias object. Uses a flag if passed into the build command
|
||||
const isEnvProductionProfile =
|
||||
isEnvProduction && process.argv.includes('--profile');
|
||||
|
||||
// We will provide `paths.publicUrlOrPath` to our app
|
||||
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
|
||||
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
|
||||
// Get environment variables to inject into our app.
|
||||
const env = getClientEnvironment(paths.publicUrlOrPath.slice(0, -1));
|
||||
|
||||
const shouldUseReactRefresh = env.raw.FAST_REFRESH;
|
||||
|
||||
// common function to get style loaders
|
||||
const getStyleLoaders = (cssOptions, preProcessor) => {
|
||||
const loaders = [
|
||||
isEnvDevelopment && require.resolve('style-loader'),
|
||||
isEnvProduction && {
|
||||
loader: MiniCssExtractPlugin.loader,
|
||||
// css is located in `static/css`, use '../../' to locate index.html folder
|
||||
// in production `paths.publicUrlOrPath` can be a relative path
|
||||
options: paths.publicUrlOrPath.startsWith('.')
|
||||
? { publicPath: '../../' }
|
||||
: {},
|
||||
},
|
||||
{
|
||||
loader: require.resolve('css-loader'),
|
||||
options: cssOptions,
|
||||
},
|
||||
{
|
||||
// Options for PostCSS as we reference these options twice
|
||||
// Adds vendor prefixing based on your specified browser support in
|
||||
// package.json
|
||||
loader: require.resolve('postcss-loader'),
|
||||
options: {
|
||||
postcssOptions: {
|
||||
// Necessary for external CSS imports to work
|
||||
// https://github.com/facebook/create-react-app/issues/2677
|
||||
ident: 'postcss',
|
||||
config: false,
|
||||
plugins: !useTailwind
|
||||
? [
|
||||
'postcss-flexbugs-fixes',
|
||||
[
|
||||
'postcss-preset-env',
|
||||
{
|
||||
autoprefixer: {
|
||||
flexbox: 'no-2009',
|
||||
},
|
||||
stage: 3,
|
||||
},
|
||||
],
|
||||
// Adds PostCSS Normalize as the reset css with default options,
|
||||
// so that it honors browserslist config in package.json
|
||||
// which in turn let's users customize the target behavior as per their needs.
|
||||
'postcss-normalize',
|
||||
]
|
||||
: [
|
||||
'tailwindcss',
|
||||
'postcss-flexbugs-fixes',
|
||||
[
|
||||
'postcss-preset-env',
|
||||
{
|
||||
autoprefixer: {
|
||||
flexbox: 'no-2009',
|
||||
},
|
||||
stage: 3,
|
||||
},
|
||||
],
|
||||
],
|
||||
},
|
||||
sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
|
||||
},
|
||||
},
|
||||
].filter(Boolean);
|
||||
if (preProcessor) {
|
||||
loaders.push(
|
||||
{
|
||||
loader: require.resolve('resolve-url-loader'),
|
||||
options: {
|
||||
sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
|
||||
root: paths.appSrc,
|
||||
},
|
||||
},
|
||||
{
|
||||
loader: require.resolve(preProcessor),
|
||||
options: {
|
||||
sourceMap: true,
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
return loaders;
|
||||
};
|
||||
|
||||
return {
|
||||
target: ['browserslist'],
|
||||
// Webpack noise constrained to errors and warnings
|
||||
stats: 'errors-warnings',
|
||||
mode: isEnvProduction ? 'production' : isEnvDevelopment && 'development',
|
||||
// Stop compilation early in production
|
||||
bail: isEnvProduction,
|
||||
devtool: isEnvProduction
|
||||
? shouldUseSourceMap
|
||||
? 'source-map'
|
||||
: false
|
||||
: isEnvDevelopment && 'cheap-module-source-map',
|
||||
// These are the "entry points" to our application.
|
||||
// This means they will be the "root" imports that are included in JS bundle.
|
||||
entry: paths.appIndexJs,
|
||||
output: {
|
||||
// The build folder.
|
||||
path: paths.appBuild,
|
||||
// Add /* filename */ comments to generated require()s in the output.
|
||||
pathinfo: isEnvDevelopment,
|
||||
// There will be one main bundle, and one file per asynchronous chunk.
|
||||
// In development, it does not produce real files.
|
||||
filename: isEnvProduction
|
||||
? 'static/js/[name].[contenthash:8].js'
|
||||
: isEnvDevelopment && 'static/js/bundle.js',
|
||||
// There are also additional JS chunk files if you use code splitting.
|
||||
chunkFilename: isEnvProduction
|
||||
? 'static/js/[name].[contenthash:8].chunk.js'
|
||||
: isEnvDevelopment && 'static/js/[name].chunk.js',
|
||||
assetModuleFilename: 'static/media/[name].[hash][ext]',
|
||||
// webpack uses `publicPath` to determine where the app is being served from.
|
||||
// It requires a trailing slash, or the file assets will get an incorrect path.
|
||||
// We inferred the "public path" (such as / or /my-project) from homepage.
|
||||
publicPath: paths.publicUrlOrPath,
|
||||
// Point sourcemap entries to original disk location (format as URL on Windows)
|
||||
devtoolModuleFilenameTemplate: isEnvProduction
|
||||
? info =>
|
||||
path
|
||||
.relative(paths.appSrc, info.absoluteResourcePath)
|
||||
.replace(/\\/g, '/')
|
||||
: isEnvDevelopment &&
|
||||
(info => path.resolve(info.absoluteResourcePath).replace(/\\/g, '/')),
|
||||
},
|
||||
cache: {
|
||||
type: 'filesystem',
|
||||
version: createEnvironmentHash(env.raw),
|
||||
cacheDirectory: paths.appWebpackCache,
|
||||
store: 'pack',
|
||||
buildDependencies: {
|
||||
defaultWebpack: ['webpack/lib/'],
|
||||
config: [__filename],
|
||||
tsconfig: [paths.appTsConfig, paths.appJsConfig].filter(f =>
|
||||
fs.existsSync(f)
|
||||
),
|
||||
},
|
||||
},
|
||||
infrastructureLogging: {
|
||||
level: 'none',
|
||||
},
|
||||
optimization: {
|
||||
minimize: isEnvProduction,
|
||||
minimizer: [
|
||||
// This is only used in production mode
|
||||
new TerserPlugin({
|
||||
terserOptions: {
|
||||
parse: {
|
||||
// We want terser to parse ecma 8 code. However, we don't want it
|
||||
// to apply any minification steps that turns valid ecma 5 code
|
||||
// into invalid ecma 5 code. This is why the 'compress' and 'output'
|
||||
// sections only apply transformations that are ecma 5 safe
|
||||
// https://github.com/facebook/create-react-app/pull/4234
|
||||
ecma: 8,
|
||||
},
|
||||
compress: {
|
||||
ecma: 5,
|
||||
warnings: false,
|
||||
// Disabled because of an issue with Uglify breaking seemingly valid code:
|
||||
// https://github.com/facebook/create-react-app/issues/2376
|
||||
// Pending further investigation:
|
||||
// https://github.com/mishoo/UglifyJS2/issues/2011
|
||||
comparisons: false,
|
||||
// Disabled because of an issue with Terser breaking valid code:
|
||||
// https://github.com/facebook/create-react-app/issues/5250
|
||||
// Pending further investigation:
|
||||
// https://github.com/terser-js/terser/issues/120
|
||||
inline: 2,
|
||||
},
|
||||
mangle: {
|
||||
safari10: true,
|
||||
},
|
||||
// Added for profiling in devtools
|
||||
keep_classnames: isEnvProductionProfile,
|
||||
keep_fnames: isEnvProductionProfile,
|
||||
output: {
|
||||
ecma: 5,
|
||||
comments: false,
|
||||
// Turned on because emoji and regex is not minified properly using default
|
||||
// https://github.com/facebook/create-react-app/issues/2488
|
||||
ascii_only: true,
|
||||
},
|
||||
},
|
||||
}),
|
||||
// This is only used in production mode
|
||||
new CssMinimizerPlugin(),
|
||||
],
|
||||
},
|
||||
resolve: {
|
||||
// This allows you to set a fallback for where webpack should look for modules.
|
||||
// We placed these paths second because we want `node_modules` to "win"
|
||||
// if there are any conflicts. This matches Node resolution mechanism.
|
||||
// https://github.com/facebook/create-react-app/issues/253
|
||||
modules: ['node_modules', paths.appNodeModules].concat(
|
||||
modules.additionalModulePaths || []
|
||||
),
|
||||
// These are the reasonable defaults supported by the Node ecosystem.
|
||||
// We also include JSX as a common component filename extension to support
|
||||
// some tools, although we do not recommend using it, see:
|
||||
// https://github.com/facebook/create-react-app/issues/290
|
||||
// `web` extension prefixes have been added for better support
|
||||
// for React Native Web.
|
||||
extensions: paths.moduleFileExtensions
|
||||
.map(ext => `.${ext}`)
|
||||
.filter(ext => useTypeScript || !ext.includes('ts')),
|
||||
alias: {
|
||||
'@assets': path.resolve(__dirname, '../src/assets'),
|
||||
'@components': path.resolve(__dirname, '../src/components'),
|
||||
'@network': path.resolve(__dirname, '../src/network'),
|
||||
// Support React Native Web
|
||||
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
|
||||
'react-native': 'react-native-web',
|
||||
// Allows for better profiling with ReactDevTools
|
||||
...(isEnvProductionProfile && {
|
||||
'react-dom$': 'react-dom/profiling',
|
||||
'scheduler/tracing': 'scheduler/tracing-profiling',
|
||||
}),
|
||||
...(modules.webpackAliases || {}),
|
||||
},
|
||||
plugins: [
|
||||
// Prevents users from importing files from outside of src/ (or node_modules/).
|
||||
// This often causes confusion because we only process files within src/ with babel.
|
||||
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
|
||||
// please link the files into your node_modules/ and let module-resolution kick in.
|
||||
// Make sure your source files are compiled, as they will not be processed in any way.
|
||||
new ModuleScopePlugin(paths.appSrc, [
|
||||
paths.appPackageJson,
|
||||
reactRefreshRuntimeEntry,
|
||||
reactRefreshWebpackPluginRuntimeEntry,
|
||||
babelRuntimeEntry,
|
||||
babelRuntimeEntryHelpers,
|
||||
babelRuntimeRegenerator,
|
||||
]),
|
||||
],
|
||||
},
|
||||
module: {
|
||||
strictExportPresence: true,
|
||||
rules: [
|
||||
// Handle node_modules packages that contain sourcemaps
|
||||
shouldUseSourceMap && {
|
||||
enforce: 'pre',
|
||||
exclude: /@babel(?:\/|\\{1,2})runtime/,
|
||||
test: /\.(js|mjs|jsx|ts|tsx|css)$/,
|
||||
loader: require.resolve('source-map-loader'),
|
||||
},
|
||||
{
|
||||
// "oneOf" will traverse all following loaders until one will
|
||||
// match the requirements. When no loader matches it will fall
|
||||
// back to the "file" loader at the end of the loader list.
|
||||
oneOf: [
|
||||
// TODO: Merge this config once `image/avif` is in the mime-db
|
||||
// https://github.com/jshttp/mime-db
|
||||
{
|
||||
test: [/\.avif$/],
|
||||
type: 'asset',
|
||||
mimetype: 'image/avif',
|
||||
parser: {
|
||||
dataUrlCondition: {
|
||||
maxSize: imageInlineSizeLimit,
|
||||
},
|
||||
},
|
||||
},
|
||||
// "url" loader works like "file" loader except that it embeds assets
|
||||
// smaller than specified limit in bytes as data URLs to avoid requests.
|
||||
// A missing `test` is equivalent to a match.
|
||||
{
|
||||
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
|
||||
type: 'asset',
|
||||
parser: {
|
||||
dataUrlCondition: {
|
||||
maxSize: imageInlineSizeLimit,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
test: /\.svg$/,
|
||||
use: [
|
||||
{
|
||||
loader: require.resolve('@svgr/webpack'),
|
||||
options: {
|
||||
prettier: false,
|
||||
svgo: false,
|
||||
svgoConfig: {
|
||||
plugins: [{ removeViewBox: false }],
|
||||
},
|
||||
titleProp: true,
|
||||
ref: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
loader: require.resolve('file-loader'),
|
||||
options: {
|
||||
name: 'static/media/[name].[hash].[ext]',
|
||||
},
|
||||
},
|
||||
],
|
||||
issuer: {
|
||||
and: [/\.(ts|tsx|js|jsx|md|mdx)$/],
|
||||
},
|
||||
},
|
||||
// Process application JS with Babel.
|
||||
// The preset includes JSX, Flow, TypeScript, and some ESnext features.
|
||||
{
|
||||
test: /\.(js|mjs|jsx|ts|tsx)$/,
|
||||
include: paths.appSrc,
|
||||
loader: require.resolve('babel-loader'),
|
||||
options: {
|
||||
customize: require.resolve(
|
||||
'babel-preset-react-app/webpack-overrides'
|
||||
),
|
||||
presets: [
|
||||
[
|
||||
require.resolve('babel-preset-react-app'),
|
||||
{
|
||||
runtime: hasJsxRuntime ? 'automatic' : 'classic',
|
||||
},
|
||||
],
|
||||
],
|
||||
|
||||
plugins: [
|
||||
isEnvDevelopment &&
|
||||
shouldUseReactRefresh &&
|
||||
require.resolve('react-refresh/babel'),
|
||||
].filter(Boolean),
|
||||
// This is a feature of `babel-loader` for webpack (not Babel itself).
|
||||
// It enables caching results in ./node_modules/.cache/babel-loader/
|
||||
// directory for faster rebuilds.
|
||||
cacheDirectory: true,
|
||||
// See #6846 for context on why cacheCompression is disabled
|
||||
cacheCompression: false,
|
||||
compact: isEnvProduction,
|
||||
},
|
||||
},
|
||||
// Process any JS outside of the app with Babel.
|
||||
// Unlike the application JS, we only compile the standard ES features.
|
||||
{
|
||||
test: /\.(js|mjs)$/,
|
||||
exclude: /@babel(?:\/|\\{1,2})runtime/,
|
||||
loader: require.resolve('babel-loader'),
|
||||
options: {
|
||||
babelrc: false,
|
||||
configFile: false,
|
||||
compact: false,
|
||||
presets: [
|
||||
[
|
||||
require.resolve('babel-preset-react-app/dependencies'),
|
||||
{ helpers: true },
|
||||
],
|
||||
],
|
||||
cacheDirectory: true,
|
||||
// See #6846 for context on why cacheCompression is disabled
|
||||
cacheCompression: false,
|
||||
|
||||
// Babel sourcemaps are needed for debugging into node_modules
|
||||
// code. Without the options below, debuggers like VSCode
|
||||
// show incorrect code and set breakpoints on the wrong lines.
|
||||
sourceMaps: shouldUseSourceMap,
|
||||
inputSourceMap: shouldUseSourceMap,
|
||||
},
|
||||
},
|
||||
// "postcss" loader applies autoprefixer to our CSS.
|
||||
// "css" loader resolves paths in CSS and adds assets as dependencies.
|
||||
// "style" loader turns CSS into JS modules that inject <style> tags.
|
||||
// In production, we use MiniCSSExtractPlugin to extract that CSS
|
||||
// to a file, but in development "style" loader enables hot editing
|
||||
// of CSS.
|
||||
// By default we support CSS Modules with the extension .module.css
|
||||
{
|
||||
test: cssRegex,
|
||||
exclude: cssModuleRegex,
|
||||
use: getStyleLoaders({
|
||||
importLoaders: 1,
|
||||
sourceMap: isEnvProduction
|
||||
? shouldUseSourceMap
|
||||
: isEnvDevelopment,
|
||||
modules: {
|
||||
mode: 'icss',
|
||||
},
|
||||
}),
|
||||
// Don't consider CSS imports dead code even if the
|
||||
// containing package claims to have no side effects.
|
||||
// Remove this when webpack adds a warning or an error for this.
|
||||
// See https://github.com/webpack/webpack/issues/6571
|
||||
sideEffects: true,
|
||||
},
|
||||
// Adds support for CSS Modules (https://github.com/css-modules/css-modules)
|
||||
// using the extension .module.css
|
||||
{
|
||||
test: cssModuleRegex,
|
||||
use: getStyleLoaders({
|
||||
importLoaders: 1,
|
||||
sourceMap: isEnvProduction
|
||||
? shouldUseSourceMap
|
||||
: isEnvDevelopment,
|
||||
modules: {
|
||||
mode: 'local',
|
||||
getLocalIdent: getCSSModuleLocalIdent,
|
||||
},
|
||||
}),
|
||||
},
|
||||
// Opt-in support for SASS (using .scss or .sass extensions).
|
||||
// By default we support SASS Modules with the
|
||||
// extensions .module.scss or .module.sass
|
||||
{
|
||||
test: sassRegex,
|
||||
exclude: sassModuleRegex,
|
||||
use: getStyleLoaders(
|
||||
{
|
||||
importLoaders: 3,
|
||||
sourceMap: isEnvProduction
|
||||
? shouldUseSourceMap
|
||||
: isEnvDevelopment,
|
||||
modules: {
|
||||
mode: 'icss',
|
||||
},
|
||||
},
|
||||
'sass-loader'
|
||||
),
|
||||
// Don't consider CSS imports dead code even if the
|
||||
// containing package claims to have no side effects.
|
||||
// Remove this when webpack adds a warning or an error for this.
|
||||
// See https://github.com/webpack/webpack/issues/6571
|
||||
sideEffects: true,
|
||||
},
|
||||
// Adds support for CSS Modules, but using SASS
|
||||
// using the extension .module.scss or .module.sass
|
||||
{
|
||||
test: sassModuleRegex,
|
||||
use: getStyleLoaders(
|
||||
{
|
||||
importLoaders: 3,
|
||||
sourceMap: isEnvProduction
|
||||
? shouldUseSourceMap
|
||||
: isEnvDevelopment,
|
||||
modules: {
|
||||
mode: 'local',
|
||||
getLocalIdent: getCSSModuleLocalIdent,
|
||||
},
|
||||
},
|
||||
'sass-loader'
|
||||
),
|
||||
},
|
||||
// "file" loader makes sure those assets get served by WebpackDevServer.
|
||||
// When you `import` an asset, you get its (virtual) filename.
|
||||
// In production, they would get copied to the `build` folder.
|
||||
// This loader doesn't use a "test" so it will catch all modules
|
||||
// that fall through the other loaders.
|
||||
{
|
||||
// Exclude `js` files to keep "css" loader working as it injects
|
||||
// its runtime that would otherwise be processed through "file" loader.
|
||||
// Also exclude `html` and `json` extensions so they get processed
|
||||
// by webpacks internal loaders.
|
||||
exclude: [/^$/, /\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
|
||||
type: 'asset/resource',
|
||||
},
|
||||
// ** STOP ** Are you adding a new loader?
|
||||
// Make sure to add the new loader(s) before the "file" loader.
|
||||
],
|
||||
},
|
||||
].filter(Boolean),
|
||||
},
|
||||
plugins: [
|
||||
// Generates an `index.html` file with the <script> injected.
|
||||
new HtmlWebpackPlugin(
|
||||
Object.assign(
|
||||
{},
|
||||
{
|
||||
inject: true,
|
||||
template: paths.appHtml,
|
||||
},
|
||||
isEnvProduction
|
||||
? {
|
||||
minify: {
|
||||
removeComments: true,
|
||||
collapseWhitespace: true,
|
||||
removeRedundantAttributes: true,
|
||||
useShortDoctype: true,
|
||||
removeEmptyAttributes: true,
|
||||
removeStyleLinkTypeAttributes: true,
|
||||
keepClosingSlash: true,
|
||||
minifyJS: true,
|
||||
minifyCSS: true,
|
||||
minifyURLs: true,
|
||||
},
|
||||
}
|
||||
: undefined
|
||||
)
|
||||
),
|
||||
// Inlines the webpack runtime script. This script is too small to warrant
|
||||
// a network request.
|
||||
// https://github.com/facebook/create-react-app/issues/5358
|
||||
isEnvProduction &&
|
||||
shouldInlineRuntimeChunk &&
|
||||
new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime-.+[.]js/]),
|
||||
// Makes some environment variables available in index.html.
|
||||
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
|
||||
// <link rel="icon" href="%PUBLIC_URL%/favicon.ico">
|
||||
// It will be an empty string unless you specify "homepage"
|
||||
// in `package.json`, in which case it will be the pathname of that URL.
|
||||
new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),
|
||||
// This gives some necessary context to module not found errors, such as
|
||||
// the requesting resource.
|
||||
new ModuleNotFoundPlugin(paths.appPath),
|
||||
// Makes some environment variables available to the JS code, for example:
|
||||
// if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
|
||||
// It is absolutely essential that NODE_ENV is set to production
|
||||
// during a production build.
|
||||
// Otherwise React will be compiled in the very slow development mode.
|
||||
new webpack.DefinePlugin(env.stringified),
|
||||
// Experimental hot reloading for React .
|
||||
// https://github.com/facebook/react/tree/main/packages/react-refresh
|
||||
isEnvDevelopment &&
|
||||
shouldUseReactRefresh &&
|
||||
new ReactRefreshWebpackPlugin({
|
||||
overlay: false,
|
||||
}),
|
||||
// Watcher doesn't work well if you mistype casing in a path so we use
|
||||
// a plugin that prints an error when you attempt to do this.
|
||||
// See https://github.com/facebook/create-react-app/issues/240
|
||||
isEnvDevelopment && new CaseSensitivePathsPlugin(),
|
||||
isEnvProduction &&
|
||||
new MiniCssExtractPlugin({
|
||||
// Options similar to the same options in webpackOptions.output
|
||||
// both options are optional
|
||||
filename: 'static/css/[name].[contenthash:8].css',
|
||||
chunkFilename: 'static/css/[name].[contenthash:8].chunk.css',
|
||||
}),
|
||||
// Generate an asset manifest file with the following content:
|
||||
// - "files" key: Mapping of all asset filenames to their corresponding
|
||||
// output file so that tools can pick it up without having to parse
|
||||
// `index.html`
|
||||
// - "entrypoints" key: Array of files which are included in `index.html`,
|
||||
// can be used to reconstruct the HTML if necessary
|
||||
new WebpackManifestPlugin({
|
||||
fileName: 'asset-manifest.json',
|
||||
publicPath: paths.publicUrlOrPath,
|
||||
generate: (seed, files, entrypoints) => {
|
||||
const manifestFiles = files.reduce((manifest, file) => {
|
||||
manifest[file.name] = file.path;
|
||||
return manifest;
|
||||
}, seed);
|
||||
const entrypointFiles = entrypoints.main.filter(
|
||||
fileName => !fileName.endsWith('.map')
|
||||
);
|
||||
|
||||
return {
|
||||
files: manifestFiles,
|
||||
entrypoints: entrypointFiles,
|
||||
};
|
||||
},
|
||||
}),
|
||||
// Moment.js is an extremely popular library that bundles large locale files
|
||||
// by default due to how webpack interprets its code. This is a practical
|
||||
// solution that requires the user to opt into importing specific locales.
|
||||
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
|
||||
// You can remove this if you don't use Moment.js:
|
||||
new webpack.IgnorePlugin({
|
||||
resourceRegExp: /^\.\/locale$/,
|
||||
contextRegExp: /moment$/,
|
||||
}),
|
||||
// Generate a service worker script that will precache, and keep up to date,
|
||||
// the HTML & assets that are part of the webpack build.
|
||||
isEnvProduction &&
|
||||
fs.existsSync(swSrc) &&
|
||||
new WorkboxWebpackPlugin.InjectManifest({
|
||||
swSrc,
|
||||
dontCacheBustURLsMatching: /\.[0-9a-f]{8}\./,
|
||||
exclude: [/\.map$/, /asset-manifest\.json$/, /LICENSE/],
|
||||
// Bump up the default maximum size (2mb) that's precached,
|
||||
// to make lazy-loading failure scenarios less likely.
|
||||
// See https://github.com/cra-template/pwa/issues/13#issuecomment-722667270
|
||||
maximumFileSizeToCacheInBytes: 5 * 1024 * 1024,
|
||||
}),
|
||||
// TypeScript type checking
|
||||
useTypeScript &&
|
||||
new ForkTsCheckerWebpackPlugin({
|
||||
async: isEnvDevelopment,
|
||||
typescript: {
|
||||
typescriptPath: resolve.sync('typescript', {
|
||||
basedir: paths.appNodeModules,
|
||||
}),
|
||||
configOverwrite: {
|
||||
compilerOptions: {
|
||||
sourceMap: isEnvProduction
|
||||
? shouldUseSourceMap
|
||||
: isEnvDevelopment,
|
||||
skipLibCheck: true,
|
||||
inlineSourceMap: false,
|
||||
declarationMap: false,
|
||||
noEmit: true,
|
||||
incremental: true,
|
||||
tsBuildInfoFile: paths.appTsBuildInfoFile,
|
||||
},
|
||||
},
|
||||
context: paths.appPath,
|
||||
diagnosticOptions: {
|
||||
syntactic: true,
|
||||
},
|
||||
mode: 'write-references',
|
||||
// profile: true,
|
||||
},
|
||||
issue: {
|
||||
// This one is specifically to match during CI tests,
|
||||
// as micromatch doesn't match
|
||||
// '../cra-template-typescript/template/src/App.tsx'
|
||||
// otherwise.
|
||||
include: [
|
||||
{ file: '../**/src/**/*.{ts,tsx}' },
|
||||
{ file: '**/src/**/*.{ts,tsx}' },
|
||||
],
|
||||
exclude: [
|
||||
{ file: '**/src/**/__tests__/**' },
|
||||
{ file: '**/src/**/?(*.){spec|test}.*' },
|
||||
{ file: '**/src/setupProxy.*' },
|
||||
{ file: '**/src/setupTests.*' },
|
||||
],
|
||||
},
|
||||
logger: {
|
||||
infrastructure: 'silent',
|
||||
},
|
||||
}),
|
||||
!disableESLintPlugin &&
|
||||
new ESLintPlugin({
|
||||
// Plugin options
|
||||
extensions: ['js', 'mjs', 'jsx', 'ts', 'tsx'],
|
||||
formatter: require.resolve('react-dev-utils/eslintFormatter'),
|
||||
eslintPath: require.resolve('eslint'),
|
||||
failOnError: !(isEnvDevelopment && emitErrorsAsWarnings),
|
||||
context: paths.appSrc,
|
||||
cache: true,
|
||||
cacheLocation: path.resolve(
|
||||
paths.appNodeModules,
|
||||
'.cache/.eslintcache'
|
||||
),
|
||||
// ESLint class options
|
||||
cwd: paths.appPath,
|
||||
resolvePluginsRelativeTo: __dirname,
|
||||
baseConfig: {
|
||||
extends: [require.resolve('eslint-config-react-app/base')],
|
||||
rules: {
|
||||
...(!hasJsxRuntime && {
|
||||
'react/react-in-jsx-scope': 'error',
|
||||
}),
|
||||
},
|
||||
},
|
||||
}),
|
||||
].filter(Boolean),
|
||||
// Turn off performance processing because we utilize
|
||||
// our own hints via the FileSizeReporter
|
||||
performance: false,
|
||||
};
|
||||
};
|
||||
@@ -1,9 +0,0 @@
|
||||
'use strict';
|
||||
const { createHash } = require('crypto');
|
||||
|
||||
module.exports = env => {
|
||||
const hash = createHash('md5');
|
||||
hash.update(JSON.stringify(env));
|
||||
|
||||
return hash.digest('hex');
|
||||
};
|
||||
@@ -1,127 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const evalSourceMapMiddleware = require('react-dev-utils/evalSourceMapMiddleware');
|
||||
const noopServiceWorkerMiddleware = require('react-dev-utils/noopServiceWorkerMiddleware');
|
||||
const ignoredFiles = require('react-dev-utils/ignoredFiles');
|
||||
const redirectServedPath = require('react-dev-utils/redirectServedPathMiddleware');
|
||||
const paths = require('./paths');
|
||||
const getHttpsConfig = require('./getHttpsConfig');
|
||||
|
||||
const host = process.env.HOST || '0.0.0.0';
|
||||
const sockHost = process.env.WDS_SOCKET_HOST;
|
||||
const sockPath = process.env.WDS_SOCKET_PATH; // default: '/ws'
|
||||
const sockPort = process.env.WDS_SOCKET_PORT;
|
||||
|
||||
module.exports = function (proxy, allowedHost) {
|
||||
const disableFirewall =
|
||||
!proxy || process.env.DANGEROUSLY_DISABLE_HOST_CHECK === 'true';
|
||||
return {
|
||||
// WebpackDevServer 2.4.3 introduced a security fix that prevents remote
|
||||
// websites from potentially accessing local content through DNS rebinding:
|
||||
// https://github.com/webpack/webpack-dev-server/issues/887
|
||||
// https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a
|
||||
// However, it made several existing use cases such as development in cloud
|
||||
// environment or subdomains in development significantly more complicated:
|
||||
// https://github.com/facebook/create-react-app/issues/2271
|
||||
// https://github.com/facebook/create-react-app/issues/2233
|
||||
// While we're investigating better solutions, for now we will take a
|
||||
// compromise. Since our WDS configuration only serves files in the `public`
|
||||
// folder we won't consider accessing them a vulnerability. However, if you
|
||||
// use the `proxy` feature, it gets more dangerous because it can expose
|
||||
// remote code execution vulnerabilities in backends like Django and Rails.
|
||||
// So we will disable the host check normally, but enable it if you have
|
||||
// specified the `proxy` setting. Finally, we let you override it if you
|
||||
// really know what you're doing with a special environment variable.
|
||||
// Note: ["localhost", ".localhost"] will support subdomains - but we might
|
||||
// want to allow setting the allowedHosts manually for more complex setups
|
||||
allowedHosts: disableFirewall ? 'all' : [allowedHost],
|
||||
headers: {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Methods': '*',
|
||||
'Access-Control-Allow-Headers': '*',
|
||||
},
|
||||
// Enable gzip compression of generated files.
|
||||
compress: true,
|
||||
static: {
|
||||
// By default WebpackDevServer serves physical files from current directory
|
||||
// in addition to all the virtual build products that it serves from memory.
|
||||
// This is confusing because those files won’t automatically be available in
|
||||
// production build folder unless we copy them. However, copying the whole
|
||||
// project directory is dangerous because we may expose sensitive files.
|
||||
// Instead, we establish a convention that only files in `public` directory
|
||||
// get served. Our build script will copy `public` into the `build` folder.
|
||||
// In `index.html`, you can get URL of `public` folder with %PUBLIC_URL%:
|
||||
// <link rel="icon" href="%PUBLIC_URL%/favicon.ico">
|
||||
// In JavaScript code, you can access it with `process.env.PUBLIC_URL`.
|
||||
// Note that we only recommend to use `public` folder as an escape hatch
|
||||
// for files like `favicon.ico`, `manifest.json`, and libraries that are
|
||||
// for some reason broken when imported through webpack. If you just want to
|
||||
// use an image, put it in `src` and `import` it from JavaScript instead.
|
||||
directory: paths.appPublic,
|
||||
publicPath: [paths.publicUrlOrPath],
|
||||
// By default files from `contentBase` will not trigger a page reload.
|
||||
watch: {
|
||||
// Reportedly, this avoids CPU overload on some systems.
|
||||
// https://github.com/facebook/create-react-app/issues/293
|
||||
// src/node_modules is not ignored to support absolute imports
|
||||
// https://github.com/facebook/create-react-app/issues/1065
|
||||
ignored: ignoredFiles(paths.appSrc),
|
||||
},
|
||||
},
|
||||
client: {
|
||||
webSocketURL: {
|
||||
// Enable custom sockjs pathname for websocket connection to hot reloading server.
|
||||
// Enable custom sockjs hostname, pathname and port for websocket connection
|
||||
// to hot reloading server.
|
||||
hostname: sockHost,
|
||||
pathname: sockPath,
|
||||
port: sockPort,
|
||||
},
|
||||
overlay: {
|
||||
errors: true,
|
||||
warnings: false,
|
||||
},
|
||||
},
|
||||
devMiddleware: {
|
||||
// It is important to tell WebpackDevServer to use the same "publicPath" path as
|
||||
// we specified in the webpack config. When homepage is '.', default to serving
|
||||
// from the root.
|
||||
// remove last slash so user can land on `/test` instead of `/test/`
|
||||
publicPath: paths.publicUrlOrPath.slice(0, -1),
|
||||
},
|
||||
|
||||
https: getHttpsConfig(),
|
||||
host,
|
||||
historyApiFallback: {
|
||||
// Paths with dots should still use the history fallback.
|
||||
// See https://github.com/facebook/create-react-app/issues/387.
|
||||
disableDotRule: true,
|
||||
index: paths.publicUrlOrPath,
|
||||
},
|
||||
// `proxy` is run between `before` and `after` `webpack-dev-server` hooks
|
||||
proxy,
|
||||
onBeforeSetupMiddleware(devServer) {
|
||||
// Keep `evalSourceMapMiddleware`
|
||||
// middlewares before `redirectServedPath` otherwise will not have any effect
|
||||
// This lets us fetch source contents from webpack for the error overlay
|
||||
devServer.app.use(evalSourceMapMiddleware(devServer));
|
||||
|
||||
if (fs.existsSync(paths.proxySetup)) {
|
||||
// This registers user provided middleware for proxy reasons
|
||||
require(paths.proxySetup)(devServer.app);
|
||||
}
|
||||
},
|
||||
onAfterSetupMiddleware(devServer) {
|
||||
// Redirect to `PUBLIC_URL` or `homepage` from `package.json` if url not match
|
||||
devServer.app.use(redirectServedPath(paths.publicUrlOrPath));
|
||||
|
||||
// This service worker file is effectively a 'no-op' that will reset any
|
||||
// previous service worker registered for the same host:port combination.
|
||||
// We do this in development to avoid hitting the production cache if
|
||||
// it used the same host and port.
|
||||
// https://github.com/facebook/create-react-app/issues/2272#issuecomment-302832432
|
||||
devServer.app.use(noopServiceWorkerMiddleware(paths.publicUrlOrPath));
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,25 @@
|
||||
# Yakit Browser Agent Native Host
|
||||
|
||||
The Native Host is a small stdio-to-loopback-WebSocket transport. It does not store pairing credentials and does not execute browser commands itself. It forwards the normal Bridge v3 server challenge and extension authentication messages; Yak validates the origin-bound paired device signature and returns the engine identity, engine instance, connection, session, task, grant, protocol, and capability identity.
|
||||
|
||||
Build from the Yak repository:
|
||||
|
||||
```bash
|
||||
go build -o yakit-browser-agent-host ./common/browser/nativehostcmd
|
||||
```
|
||||
|
||||
Install for Linux or macOS, using the ID shown by `chrome://extensions` for an unpacked build:
|
||||
|
||||
```bash
|
||||
./native-host/install.sh \
|
||||
--host-binary /absolute/path/to/yakit-browser-agent-host \
|
||||
--extension-id YOUR_CHROME_EXTENSION_ID
|
||||
```
|
||||
|
||||
On Windows, run PowerShell without administrator privileges:
|
||||
|
||||
```powershell
|
||||
.\native-host\install.ps1 -HostBinary C:\path\yakit-browser-agent-host.exe -ExtensionId YOUR_CHROME_EXTENSION_ID
|
||||
```
|
||||
|
||||
The installer registers Chrome, Chromium, Edge, Brave, and Firefox per-user locations. Chrome supplies its extension origin to the host. Firefox supplies the Native Host manifest path and add-on ID; the host verifies that ID against `allowed_extensions` before deriving its Bridge origin. It writes only the loopback endpoint to the user configuration directory. Run with `--uninstall` on POSIX or `-Uninstall` on Windows to remove the registrations; uninstall does not require an extension ID. When Chrome runs on Windows and development runs in WSL, build/install the Windows host with `install.ps1`; a Linux Native Host cannot be launched by Windows Chrome.
|
||||
@@ -0,0 +1,71 @@
|
||||
param(
|
||||
[string]$ExtensionId = "",
|
||||
[string]$HostBinary = "yakit-browser-agent-host.exe",
|
||||
[string]$FirefoxId = "[email protected]",
|
||||
[string]$Endpoint = "ws://127.0.0.1:64333/extension",
|
||||
[switch]$Uninstall
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
$Utf8NoBom = New-Object System.Text.UTF8Encoding($false)
|
||||
$HostName = "com.yaklang.browser_agent"
|
||||
$InstallRoot = Join-Path $env:LOCALAPPDATA "Yakit\BrowserAgent"
|
||||
$ConfigRoot = Join-Path $env:APPDATA "yakit"
|
||||
$ManifestPath = Join-Path $InstallRoot "$HostName.json"
|
||||
$RegistryTargets = @(
|
||||
"HKCU:\Software\Google\Chrome\NativeMessagingHosts\$HostName",
|
||||
"HKCU:\Software\Chromium\NativeMessagingHosts\$HostName",
|
||||
"HKCU:\Software\Microsoft\Edge\NativeMessagingHosts\$HostName",
|
||||
"HKCU:\Software\BraveSoftware\Brave-Browser\NativeMessagingHosts\$HostName",
|
||||
"HKCU:\Software\Mozilla\NativeMessagingHosts\$HostName"
|
||||
)
|
||||
|
||||
function Write-JsonFile {
|
||||
param([Parameter(Mandatory = $true)][string]$Path, [Parameter(Mandatory = $true)][object]$Value)
|
||||
[System.IO.File]::WriteAllText($Path, ($Value | ConvertTo-Json -Depth 4), $script:Utf8NoBom)
|
||||
}
|
||||
|
||||
if ($Uninstall) {
|
||||
foreach ($Target in $RegistryTargets) { Remove-Item $Target -Recurse -Force -ErrorAction SilentlyContinue }
|
||||
Remove-Item $InstallRoot -Recurse -Force -ErrorAction SilentlyContinue
|
||||
Remove-Item (Join-Path $ConfigRoot "browser-agent-native-host.json") -Force -ErrorAction SilentlyContinue
|
||||
Write-Host "Removed $HostName."
|
||||
exit 0
|
||||
}
|
||||
|
||||
if ($Endpoint -notmatch '^wss?://(127\.0\.0\.1|localhost|\[::1\])(:[0-9]+)?/') {
|
||||
throw "Endpoint must use ws:// or wss:// with an explicit loopback host."
|
||||
}
|
||||
if ([string]::IsNullOrWhiteSpace($ExtensionId)) {
|
||||
throw "ExtensionId is required when installing the Native Host."
|
||||
}
|
||||
$ResolvedBinary = (Resolve-Path $HostBinary).Path
|
||||
New-Item $InstallRoot -ItemType Directory -Force | Out-Null
|
||||
New-Item $ConfigRoot -ItemType Directory -Force | Out-Null
|
||||
$InstalledBinary = Join-Path $InstallRoot "yakit-browser-agent-host.exe"
|
||||
Copy-Item $ResolvedBinary $InstalledBinary -Force
|
||||
Write-JsonFile -Path (Join-Path $ConfigRoot "browser-agent-native-host.json") -Value @{ endpoint = $Endpoint }
|
||||
|
||||
Write-JsonFile -Path $ManifestPath -Value @{
|
||||
name = $HostName
|
||||
description = "Yakit Browser Agent Native Host"
|
||||
path = $InstalledBinary
|
||||
type = "stdio"
|
||||
allowed_origins = @("chrome-extension://$ExtensionId/")
|
||||
}
|
||||
|
||||
$FirefoxManifestPath = Join-Path $InstallRoot "$HostName.firefox.json"
|
||||
Write-JsonFile -Path $FirefoxManifestPath -Value @{
|
||||
name = $HostName
|
||||
description = "Yakit Browser Agent Native Host"
|
||||
path = $InstalledBinary
|
||||
type = "stdio"
|
||||
allowed_extensions = @($FirefoxId)
|
||||
}
|
||||
|
||||
foreach ($Target in $RegistryTargets) {
|
||||
New-Item $Target -Force | Out-Null
|
||||
$Value = if ($Target -like "*Mozilla*") { $FirefoxManifestPath } else { $ManifestPath }
|
||||
Set-Item $Target -Value $Value
|
||||
}
|
||||
Write-Host "Installed $HostName at $InstalledBinary"
|
||||
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
host_name="com.yaklang.browser_agent"
|
||||
host_binary=""
|
||||
extension_id=""
|
||||
firefox_id="[email protected]"
|
||||
endpoint="ws://127.0.0.1:64333/extension"
|
||||
uninstall=false
|
||||
|
||||
usage() {
|
||||
printf '%s\n' "Usage: $0 --extension-id ID [--host-binary PATH] [--endpoint WS_URL] [--firefox-id ID] [--uninstall]"
|
||||
}
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--host-binary) host_binary="${2:-}"; shift 2 ;;
|
||||
--extension-id) extension_id="${2:-}"; shift 2 ;;
|
||||
--firefox-id) firefox_id="${2:-}"; shift 2 ;;
|
||||
--endpoint) endpoint="${2:-}"; shift 2 ;;
|
||||
--uninstall) uninstall=true; shift ;;
|
||||
-h|--help) usage; exit 0 ;;
|
||||
*) printf 'Unknown option: %s\n' "$1" >&2; usage >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
case "$(uname -s)" in
|
||||
Darwin)
|
||||
install_root="$HOME/Library/Application Support/Yakit/BrowserAgent"
|
||||
config_root="$HOME/Library/Application Support/yakit"
|
||||
chrome_roots=(
|
||||
"$HOME/Library/Application Support/Google/Chrome/NativeMessagingHosts"
|
||||
"$HOME/Library/Application Support/Chromium/NativeMessagingHosts"
|
||||
"$HOME/Library/Application Support/Microsoft Edge/NativeMessagingHosts"
|
||||
"$HOME/Library/Application Support/BraveSoftware/Brave-Browser/NativeMessagingHosts"
|
||||
)
|
||||
firefox_root="$HOME/Library/Application Support/Mozilla/NativeMessagingHosts"
|
||||
;;
|
||||
Linux)
|
||||
install_root="${XDG_DATA_HOME:-$HOME/.local/share}/yakit/browser-agent"
|
||||
config_root="${XDG_CONFIG_HOME:-$HOME/.config}/yakit"
|
||||
chrome_roots=(
|
||||
"$HOME/.config/google-chrome/NativeMessagingHosts"
|
||||
"$HOME/.config/chromium/NativeMessagingHosts"
|
||||
"$HOME/.config/microsoft-edge/NativeMessagingHosts"
|
||||
"$HOME/.config/BraveSoftware/Brave-Browser/NativeMessagingHosts"
|
||||
)
|
||||
firefox_root="$HOME/.mozilla/native-messaging-hosts"
|
||||
;;
|
||||
*) printf 'Unsupported operating system. Use install.ps1 on Windows.\n' >&2; exit 1 ;;
|
||||
esac
|
||||
|
||||
manifest_name="$host_name.json"
|
||||
if [[ "$uninstall" == true ]]; then
|
||||
for directory in "${chrome_roots[@]}" "$firefox_root"; do rm -f "$directory/$manifest_name"; done
|
||||
rm -f "$install_root/yakit-browser-agent-host" "$config_root/browser-agent-native-host.json"
|
||||
printf 'Removed %s manifests and host binary.\n' "$host_name"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [[ -z "$extension_id" ]]; then printf '%s\n' '--extension-id is required for Chrome/Chromium.' >&2; exit 2; fi
|
||||
if [[ -z "$host_binary" ]]; then host_binary="$(command -v yakit-browser-agent-host || true)"; fi
|
||||
if [[ -z "$host_binary" || ! -x "$host_binary" ]]; then
|
||||
printf '%s\n' 'Host binary not found. Build it with: go build -o yakit-browser-agent-host ./common/browser/nativehostcmd' >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ ! "$endpoint" =~ ^wss?://(127\.0\.0\.1|localhost|\[::1\])(:[0-9]+)?/ ]]; then
|
||||
printf '%s\n' 'Endpoint must use ws:// or wss:// with an explicit loopback host.' >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
mkdir -p "$install_root" "$config_root"
|
||||
install -m 0755 "$host_binary" "$install_root/yakit-browser-agent-host"
|
||||
printf '{"endpoint":"%s"}\n' "$endpoint" > "$config_root/browser-agent-native-host.json"
|
||||
|
||||
for directory in "${chrome_roots[@]}"; do
|
||||
mkdir -p "$directory"
|
||||
printf '{\n "name": "%s",\n "description": "Yakit Browser Agent Native Host",\n "path": "%s",\n "type": "stdio",\n "allowed_origins": ["chrome-extension://%s/"]\n}\n' \
|
||||
"$host_name" "$install_root/yakit-browser-agent-host" "$extension_id" > "$directory/$manifest_name"
|
||||
done
|
||||
|
||||
mkdir -p "$firefox_root"
|
||||
printf '{\n "name": "%s",\n "description": "Yakit Browser Agent Native Host",\n "path": "%s",\n "type": "stdio",\n "allowed_extensions": ["%s"]\n}\n' \
|
||||
"$host_name" "$install_root/yakit-browser-agent-host" "$firefox_id" > "$firefox_root/$manifest_name"
|
||||
|
||||
printf 'Installed %s at %s\n' "$host_name" "$install_root/yakit-browser-agent-host"
|
||||
@@ -1,153 +1,71 @@
|
||||
{
|
||||
"name": "yakit-chrome-client",
|
||||
"version": "0.1.0",
|
||||
"description": "Yakit Browser Extension",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@pmmmwh/react-refresh-webpack-plugin": "^0.5.3",
|
||||
"@svgr/webpack": "^8.1.0",
|
||||
"@testing-library/jest-dom": "^5.17.0",
|
||||
"@testing-library/react": "^13.4.0",
|
||||
"@testing-library/user-event": "^13.5.0",
|
||||
"ahooks": "^3.7.10",
|
||||
"antd": "^5.17.2",
|
||||
"babel-jest": "^27.4.2",
|
||||
"babel-plugin-named-asset-import": "^0.3.8",
|
||||
"babel-preset-react-app": "^10.0.1",
|
||||
"bfj": "^7.0.2",
|
||||
"browserslist": "^4.18.1",
|
||||
"camelcase": "^6.2.1",
|
||||
"case-sensitive-paths-webpack-plugin": "^2.4.0",
|
||||
"classnames": "^2.5.1",
|
||||
"css-minimizer-webpack-plugin": "^3.2.0",
|
||||
"dotenv": "^10.0.0",
|
||||
"dotenv-expand": "^5.1.0",
|
||||
"eslint": "^8.3.0",
|
||||
"eslint-config-react-app": "^7.0.1",
|
||||
"eslint-webpack-plugin": "^3.1.1",
|
||||
"file-loader": "^6.2.0",
|
||||
"fs-extra": "^10.0.0",
|
||||
"identity-obj-proxy": "^3.0.0",
|
||||
"jest": "^27.4.3",
|
||||
"jest-resolve": "^27.4.2",
|
||||
"jest-watch-typeahead": "^1.0.0",
|
||||
"mini-css-extract-plugin": "^2.4.5",
|
||||
"postcss": "^8.4.4",
|
||||
"postcss-flexbugs-fixes": "^5.0.2",
|
||||
"postcss-loader": "^6.2.1",
|
||||
"postcss-normalize": "^10.0.1",
|
||||
"postcss-preset-env": "^7.0.1",
|
||||
"prompts": "^2.4.2",
|
||||
"react": "^18.2.0",
|
||||
"react-app-polyfill": "^3.0.0",
|
||||
"react-dev-utils": "^12.0.1",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-refresh": "^0.11.0",
|
||||
"resolve": "^1.20.0",
|
||||
"resolve-url-loader": "^5.0.0",
|
||||
"sass-loader": "^12.3.0",
|
||||
"semver": "^7.3.5",
|
||||
"source-map-loader": "^3.0.0",
|
||||
"tailwindcss": "^3.0.2",
|
||||
"terser-webpack-plugin": "^5.2.5",
|
||||
"web-vitals": "^2.1.4",
|
||||
"webpack-dev-server": "^4.6.0",
|
||||
"webpack-manifest-plugin": "^4.0.2",
|
||||
"workbox-webpack-plugin": "^6.4.1"
|
||||
},
|
||||
"version": "0.2.3",
|
||||
"type": "module",
|
||||
"packageManager": "[email protected]",
|
||||
"scripts": {
|
||||
"start": "node scripts/start.js",
|
||||
"build": "cross-env NODE_ENV=production node scripts/build.js",
|
||||
"watch": "cross-env NODE_ENV=development webpack --config webpack.config.js",
|
||||
"test": "node scripts/test.js"
|
||||
"dev": "wxt",
|
||||
"dev:wsl": "node scripts/dev-wsl.mjs",
|
||||
"dev:firefox": "wxt -b firefox",
|
||||
"build": "wxt build",
|
||||
"build:store": "wxt build -b chrome --mode store",
|
||||
"build:enterprise": "wxt build -b chrome --mode enterprise",
|
||||
"build:firefox": "wxt build -b firefox",
|
||||
"build:firefox:amo": "wxt build -b firefox --mv3 --mode store",
|
||||
"zip": "wxt zip",
|
||||
"zip:firefox": "wxt zip -b firefox",
|
||||
"compile": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"audit:build": "node scripts/audit-build.mjs",
|
||||
"verify:production": "pnpm test && pnpm compile && pnpm build:store && pnpm build:enterprise && pnpm build:firefox && pnpm build:firefox:amo && pnpm audit:build",
|
||||
"verify:ui": "node scripts/verify-ui.mjs",
|
||||
"verify:ui:store": "EXTENSION_PATH=.output/chrome-mv3-store node scripts/verify-ui.mjs",
|
||||
"verify:ui:enterprise": "EXTENSION_PATH=.output/chrome-mv3-enterprise node scripts/verify-ui.mjs",
|
||||
"verify:ui:enterprise:fallback": "ENABLE_USER_SCRIPTS=0 EXTENSION_PATH=.output/chrome-mv3-enterprise node scripts/verify-ui.mjs",
|
||||
"verify:aesrsa": "node scripts/verify-aesrsa-transaction.mjs",
|
||||
"verify:aesserver": "node scripts/verify-aesserver-transaction.mjs",
|
||||
"verify:des": "node scripts/verify-des-transaction.mjs",
|
||||
"verify:agent-contract:aes": "node scripts/verify-aes-agent-contract.mjs",
|
||||
"verify:agent-contract:aesrsa": "node scripts/verify-aesrsa-transaction.mjs",
|
||||
"verify:agent-contract:holdout": "AGENT_CONTRACT_HOLDOUT_ONLY=1 EXTENSION_PATH=.output/chrome-mv3-enterprise node scripts/verify-ui.mjs",
|
||||
"verify:g4": "node scripts/verify-g4-protocols.mjs",
|
||||
"verify:native": "node scripts/verify-native-host.mjs",
|
||||
"postinstall": "wxt prepare"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": [
|
||||
"react-app",
|
||||
"react-app/jest"
|
||||
]
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
">0.2%",
|
||||
"not dead",
|
||||
"not op_mini all"
|
||||
],
|
||||
"development": [
|
||||
"last 1 chrome version",
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
},
|
||||
"jest": {
|
||||
"roots": [
|
||||
"<rootDir>/src"
|
||||
],
|
||||
"collectCoverageFrom": [
|
||||
"src/**/*.{js,jsx,ts,tsx}",
|
||||
"!src/**/*.d.ts"
|
||||
],
|
||||
"setupFiles": [
|
||||
"react-app-polyfill/jsdom"
|
||||
],
|
||||
"setupFilesAfterEnv": [
|
||||
"<rootDir>/src/setupTests.js"
|
||||
],
|
||||
"testMatch": [
|
||||
"<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}",
|
||||
"<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}"
|
||||
],
|
||||
"testEnvironment": "jsdom",
|
||||
"transform": {
|
||||
"^.+\\.(js|jsx|mjs|cjs|ts|tsx)$": "<rootDir>/config/jest/babelTransform.js",
|
||||
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
|
||||
"^(?!.*\\.(js|jsx|mjs|cjs|ts|tsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
|
||||
},
|
||||
"transformIgnorePatterns": [
|
||||
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs|cjs|ts|tsx)$",
|
||||
"^.+\\.module\\.(css|sass|scss)$"
|
||||
],
|
||||
"modulePaths": [],
|
||||
"moduleNameMapper": {
|
||||
"^react-native$": "react-native-web",
|
||||
"^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy"
|
||||
},
|
||||
"moduleFileExtensions": [
|
||||
"web.js",
|
||||
"js",
|
||||
"web.ts",
|
||||
"ts",
|
||||
"web.tsx",
|
||||
"tsx",
|
||||
"json",
|
||||
"web.jsx",
|
||||
"jsx",
|
||||
"node"
|
||||
],
|
||||
"watchPlugins": [
|
||||
"jest-watch-typeahead/filename",
|
||||
"jest-watch-typeahead/testname"
|
||||
],
|
||||
"resetMocks": true
|
||||
},
|
||||
"babel": {
|
||||
"presets": [
|
||||
"react-app"
|
||||
]
|
||||
"dependencies": {
|
||||
"@radix-ui/react-slot": "^1.3.0",
|
||||
"@radix-ui/react-switch": "^1.3.3",
|
||||
"@radix-ui/react-tabs": "^1.1.17",
|
||||
"@radix-ui/react-tooltip": "^1.2.12",
|
||||
"@valibot/to-json-schema": "1.7.1",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"lucide-react": "^1.24.0",
|
||||
"react": "^19.2.7",
|
||||
"react-dom": "^19.2.7",
|
||||
"uuid": "^14.0.1",
|
||||
"valibot": "^1.4.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.24.1",
|
||||
"@babel/preset-env": "^7.24.1",
|
||||
"@babel/preset-react": "^7.24.1",
|
||||
"@types/chrome": "^0.0.268",
|
||||
"babel-loader": "^9.1.3",
|
||||
"copy-webpack-plugin": "^12.0.2",
|
||||
"cross-env": "^7.0.3",
|
||||
"css-loader": "^6.10.0",
|
||||
"html-webpack-plugin": "^5.6.0",
|
||||
"style-loader": "^3.3.4",
|
||||
"ts-loader": "^9.5.1",
|
||||
"typescript": "^5.4.2",
|
||||
"webpack": "^5.90.3",
|
||||
"webpack-cli": "^5.1.4"
|
||||
"@types/jsrsasign": "10.5.15",
|
||||
"@types/node": "^22.0.0",
|
||||
"@types/react": "^19.2.17",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@types/ws": "^8.18.1",
|
||||
"@wxt-dev/module-react": "^1.2.2",
|
||||
"adm-zip": "^0.5.16",
|
||||
"ali-oss": "^6.21.0",
|
||||
"jose": "6.2.3",
|
||||
"jsencrypt": "3.5.4",
|
||||
"jsrsasign": "11.1.3",
|
||||
"node-forge": "1.4.0",
|
||||
"playwright-core": "^1.61.1",
|
||||
"sm-crypto": "0.4.0",
|
||||
"typescript": "^7.0.2",
|
||||
"vitest": "^4.1.10",
|
||||
"ws": "^8.21.1",
|
||||
"wxt": "^0.20.27"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
import {ActionType, WebSocketManager} from './socket.js';
|
||||
|
||||
|
||||
console.info("Chrome Extenstion Background is loaded")
|
||||
|
||||
const websocketManager = new WebSocketManager();
|
||||
|
||||
|
||||
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
|
||||
console.log("msg", msg)
|
||||
switch (msg.action) {
|
||||
case ActionType.CONNECT:
|
||||
console.info("Start to connect websocket")
|
||||
const host = msg['host'] || "127.0.0.1"
|
||||
const port = msg['port'] || 11212
|
||||
websocketManager.connectWebsocket(`ws://${host}:${port}/?token=${"a"}`, port)
|
||||
break;
|
||||
case ActionType.DISCONNECT:
|
||||
websocketManager.disconnectWebsocket();
|
||||
break;
|
||||
case ActionType.SET_PROXY:
|
||||
chrome.proxy.settings.set({
|
||||
value: {
|
||||
mode: "fixed_servers",
|
||||
rules: {
|
||||
singleProxy: {
|
||||
scheme: msg.scheme,
|
||||
host: msg.host,
|
||||
port: parseInt(`${msg.port}`)
|
||||
}
|
||||
}
|
||||
},
|
||||
scope: 'regular',
|
||||
});
|
||||
break;
|
||||
case ActionType.CLEAR_PROXY:
|
||||
chrome.proxy.settings.clear({})
|
||||
break;
|
||||
case ActionType.PROXY_STATUS:
|
||||
chrome.proxy.settings.get({}, function (details) {
|
||||
if (details.value && details.value.mode === "fixed_servers") {
|
||||
let proxyConfig = details.value.rules.singleProxy;
|
||||
chrome.runtime.sendMessage({
|
||||
enable: true,
|
||||
proxy: `${proxyConfig.scheme}://${proxyConfig.host}:${proxyConfig.port}`
|
||||
})
|
||||
} else {
|
||||
chrome.runtime.sendMessage({enable: false, proxy: ""})
|
||||
}
|
||||
});
|
||||
break;
|
||||
case ActionType.INJECT_SCRIPT:
|
||||
(async () => {
|
||||
try {
|
||||
// 注入 JS 脚本
|
||||
await chrome.scripting.executeScript({
|
||||
target: {tabId: msg.tabId},
|
||||
files: ['content.js']
|
||||
});
|
||||
|
||||
// 发送消息
|
||||
const response = await chrome.tabs.sendMessage(msg.tabId, {
|
||||
type: ActionType.INJECT_SCRIPT,
|
||||
value: msg.value
|
||||
});
|
||||
|
||||
console.log("response", response);
|
||||
if (response && response.action === ActionType.TO_EXTENSION_PAGE) {
|
||||
await chrome.runtime.sendMessage(response);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Script or CSS injection failed:', err);
|
||||
}
|
||||
})();
|
||||
break
|
||||
}
|
||||
|
||||
})
|
||||
|
||||
const pageFunction = (code) => {
|
||||
chrome.runtime.sendMessage({code}, response => {
|
||||
if (response && response.success) {
|
||||
console.log('Result:', response.result);
|
||||
} else {
|
||||
console.error('Error:', response.error);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
(() => {
|
||||
if (window.contentScriptInjected) {
|
||||
return;
|
||||
}
|
||||
window.contentScriptInjected = true;
|
||||
// 检查并插入 CSS 样式
|
||||
const styleId = 'injected-css-style';
|
||||
if (!document.getElementById(styleId)) {
|
||||
const style = document.createElement('style');
|
||||
style.id = styleId;
|
||||
style.textContent = `
|
||||
body {
|
||||
border: 3px solid red;
|
||||
position: relative; /* Ensure the body is positioned to allow the pseudo-element */
|
||||
}
|
||||
body::after {
|
||||
content: "Injection successful";
|
||||
display: block;
|
||||
position: fixed;
|
||||
top: 10px;
|
||||
right: 10px;
|
||||
background: green;
|
||||
color: white;
|
||||
padding: 5px 10px;
|
||||
font-size: 16px;
|
||||
z-index: 1000;
|
||||
}
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
|
||||
if (request.type === 'yakit_inject_script') {
|
||||
const injectedScriptURL = chrome.runtime.getURL('inject.js');
|
||||
const script = document.createElement('script');
|
||||
script.src = injectedScriptURL;
|
||||
script.onload = () => {
|
||||
window.postMessage({type: request.value.mode, value: request.value}, '*');
|
||||
script.remove();
|
||||
};
|
||||
(document.head || document.documentElement).appendChild(script);
|
||||
window.addEventListener('message', function onMessage(event) {
|
||||
if (event.source !== window || event.data.type !== 'FROM_INJECT_JS') {
|
||||
return;
|
||||
}
|
||||
window.removeEventListener('message', onMessage);
|
||||
// Send the result to the background script
|
||||
// chrome.runtime.sendMessage({ action: 'yakit_to_extension_page', result: event.data.result });
|
||||
// 直接向向发送端返回结果
|
||||
sendResponse({action: 'yakit_to_extension_page', result: event.data.result});
|
||||
});
|
||||
return true;
|
||||
}
|
||||
});
|
||||
})()
|
||||
|
||||
|
Before Width: | Height: | Size: 6.5 KiB After Width: | Height: | Size: 6.5 KiB |
|
Before Width: | Height: | Size: 1.9 KiB After Width: | Height: | Size: 1.9 KiB |
|
Before Width: | Height: | Size: 3.0 KiB After Width: | Height: | Size: 3.0 KiB |
|
Before Width: | Height: | Size: 50 KiB After Width: | Height: | Size: 50 KiB |
@@ -1,12 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
||||
<meta name="theme-color" content="#000000"/>
|
||||
<title>React App</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,37 +0,0 @@
|
||||
(() => {
|
||||
if (window.injectedMessageListener) {
|
||||
return;
|
||||
}
|
||||
window.injectedMessageListener = true;
|
||||
|
||||
window.addEventListener('message', function onMessage(event) {
|
||||
if (event.source !== window) {
|
||||
return;
|
||||
}
|
||||
let result
|
||||
switch (event.data.type) {
|
||||
case 'CONTENT_CALL_FUNCTION':
|
||||
const fn_name = event.data.value.fn_name;
|
||||
const args = event.data.value.args;
|
||||
result = window[fn_name](args);
|
||||
window.postMessage({type: 'FROM_INJECT_JS', result: result}, '*');
|
||||
break;
|
||||
case 'CONTENT_EVAL_CODE':
|
||||
const code = event.data.value.code;
|
||||
result = (() => {
|
||||
try {
|
||||
return eval(code);
|
||||
} catch (e) {
|
||||
// console.error("Error evaluating code:", e);
|
||||
return e.toString();
|
||||
}
|
||||
})();
|
||||
// console.log("CONTENT_EVAL_CODE result: ", result);
|
||||
window.postMessage({type: 'FROM_INJECT_JS', result: result}, '*');
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
});
|
||||
})();
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-03/schema#",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"bridgeTransport": {
|
||||
"title": "Bridge transport",
|
||||
"description": "Lock the extension to native or loopback WebSocket transport.",
|
||||
"type": "string",
|
||||
"enum": ["native", "websocket"]
|
||||
},
|
||||
"bridgeEndpoint": {
|
||||
"title": "Bridge endpoint",
|
||||
"description": "Managed loopback WebSocket endpoint.",
|
||||
"type": "string"
|
||||
},
|
||||
"nativeHost": {
|
||||
"title": "Native Messaging host",
|
||||
"type": "string"
|
||||
},
|
||||
"autoConnect": {
|
||||
"title": "Connect automatically",
|
||||
"type": "boolean"
|
||||
},
|
||||
"disableWebSocket": {
|
||||
"title": "Require Native Messaging",
|
||||
"type": "boolean"
|
||||
},
|
||||
"floatingPanelEnabled": {
|
||||
"title": "Enable the page floating panel",
|
||||
"type": "boolean"
|
||||
},
|
||||
"maxGrantMinutes": {
|
||||
"title": "Maximum grant duration in minutes",
|
||||
"type": "integer",
|
||||
"minimum": 5,
|
||||
"maximum": 1440
|
||||
},
|
||||
"grantAllowedOrigins": {
|
||||
"title": "Origins that may be shared with an Agent",
|
||||
"type": "array",
|
||||
"items": { "type": "string" }
|
||||
},
|
||||
"allowProgramEval": {
|
||||
"title": "Allow program Eval grants",
|
||||
"type": "boolean"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
{
|
||||
"manifest_version": 3,
|
||||
"name": "Yakit Chrome Endpoint",
|
||||
"version": "1.0",
|
||||
"description": "A Endpoint for Yakit MITM or more",
|
||||
"action": {
|
||||
"default_popup": "index.html",
|
||||
"default_icon": {
|
||||
"16": "/images/icon16.png",
|
||||
"48": "/images/icon48.png",
|
||||
"128": "/images/icon128.png"
|
||||
}
|
||||
},
|
||||
"background": {
|
||||
"service_worker": "background.js",
|
||||
"type": "module"
|
||||
},
|
||||
"permissions": [
|
||||
"webNavigation",
|
||||
"activeTab",
|
||||
"scripting",
|
||||
"tabs",
|
||||
"proxy",
|
||||
"storage",
|
||||
"webRequest"
|
||||
],
|
||||
"host_permissions": [
|
||||
"<all_urls>"
|
||||
],
|
||||
|
||||
"web_accessible_resources": [
|
||||
{
|
||||
"resources": ["inject.js"],
|
||||
"matches": ["<all_urls>"],
|
||||
"use_dynamic_url": true
|
||||
}
|
||||
],
|
||||
"icons": {
|
||||
"16": "/images/icon16.png",
|
||||
"48": "/images/icon48.png",
|
||||
"128": "/images/icon128.png"
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
export const ActionType = {
|
||||
CONNECT: 'connect',
|
||||
DISCONNECT: 'disconnect',
|
||||
STATUS: 'status',
|
||||
PROXY_STATUS: 'proxy_status',
|
||||
SET_PROXY: 'set_proxy',
|
||||
CLEAR_PROXY: 'clear_proxy',
|
||||
INJECT_SCRIPT: 'yakit_inject_script',
|
||||
TO_EXTENSION_PAGE: "yakit_to_extension_page",
|
||||
}
|
||||
|
||||
export class WebSocketManager {
|
||||
constructor() {
|
||||
this.socket = null;
|
||||
this.intervalId = null;
|
||||
}
|
||||
|
||||
connectWebsocket(url, port) {
|
||||
this.disconnectWebsocket();
|
||||
this.socket = new WebSocket(url);
|
||||
|
||||
this.socket.onopen = () => {
|
||||
chrome.runtime.sendMessage({action: ActionType.STATUS, connected: true, port: port});
|
||||
this.startHeartbeat();
|
||||
};
|
||||
|
||||
this.socket.onmessage = (event) => {
|
||||
this.handleMessage(event.data);
|
||||
};
|
||||
|
||||
this.socket.onclose = () => {
|
||||
chrome.runtime.sendMessage({action: ActionType.STATUS, connected: false});
|
||||
};
|
||||
|
||||
this.socket.onerror = (error) => {
|
||||
console.error("WebSocket Error:", error);
|
||||
};
|
||||
}
|
||||
|
||||
disconnectWebsocket() {
|
||||
if (this.socket) {
|
||||
try {
|
||||
this.socket.close();
|
||||
chrome.runtime.sendMessage({action: ActionType.STATUS, connected: false});
|
||||
} catch (e) {
|
||||
console.error("Error closing websocket:", e);
|
||||
}
|
||||
this.socket = null;
|
||||
this.stopHeartbeat();
|
||||
}
|
||||
}
|
||||
|
||||
startHeartbeat() {
|
||||
this.intervalId = setInterval(() => this.heartbeat(), 3000);
|
||||
}
|
||||
|
||||
stopHeartbeat() {
|
||||
if (this.intervalId) {
|
||||
clearInterval(this.intervalId);
|
||||
this.intervalId = null;
|
||||
}
|
||||
}
|
||||
|
||||
heartbeat() {
|
||||
if (this.isConnected()) {
|
||||
try {
|
||||
this.socket.send(JSON.stringify({"type": "heartbeat"}));
|
||||
} catch (e) {
|
||||
console.error("Error sending heartbeat:", e);
|
||||
}
|
||||
} else {
|
||||
this.disconnectWebsocket();
|
||||
}
|
||||
}
|
||||
|
||||
isConnected() {
|
||||
return this.socket && this.socket.readyState === WebSocket.OPEN;
|
||||
}
|
||||
|
||||
handleMessage(message) {
|
||||
console.log("message", message)
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 36 KiB |
@@ -0,0 +1,149 @@
|
||||
import { access, readFile, stat } from 'node:fs/promises';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { gzipSync } from 'node:zlib';
|
||||
|
||||
const root = resolve(import.meta.dirname, '..');
|
||||
const MIB = 1024 * 1024;
|
||||
const TOTAL_PACKAGE_BUDGET = Math.floor(1.25 * MIB);
|
||||
// Bundle sizes remain visible in the audit report, but are advisory. Product
|
||||
// acceptance is based on runtime behavior, security boundaries and measured
|
||||
// responsiveness rather than a fixed package-size gate.
|
||||
const BRIDGE_BACKGROUND_BUDGET = 204 * 1024;
|
||||
const BRIDGE_BACKGROUND_GZIP_BUDGET = 60 * 1024;
|
||||
const ENTERPRISE_BACKGROUND_GZIP_BUDGET = 61 * 1024;
|
||||
const CHROMIUM_EXTENSION_ID = 'mcnaombmlombekhbonfndagbcfhmoail';
|
||||
// Recorder, callable registry and Pipeline runtime are installed only for an
|
||||
// explicitly selected document. Keep their budget separate from the always-on
|
||||
// Service Worker so moving work out of startup code remains measurable.
|
||||
const MAIN_WORLD_PIPELINE_BUDGET = 36 * 1024;
|
||||
const FIXTURE_LEAK_SIGNATURES = [
|
||||
'127.0.0.1:82',
|
||||
'192.168.3.3:8080',
|
||||
'/encrypt/aes.php',
|
||||
'/encrypt/rsa.php',
|
||||
'/semantic-adapter-submit',
|
||||
'/opaque-worker-submit',
|
||||
'recorder-webcrypto-envelope-474',
|
||||
'worker-boundary-holdout-811',
|
||||
'semantic-sm-plaintext-821',
|
||||
'semantic-forge-plaintext-822',
|
||||
'module-recording-',
|
||||
'"password":"123456"',
|
||||
];
|
||||
|
||||
const targets = [
|
||||
{ name: 'store', dir: '.output/chrome-mv3-store', contentBudget: 12 * 1024, backgroundBudget: BRIDGE_BACKGROUND_BUDGET, backgroundGzipBudget: BRIDGE_BACKGROUND_GZIP_BUDGET, totalBudget: TOTAL_PACKAGE_BUDGET, directEval: false, userScripts: true, execution: 'user-scripts' },
|
||||
{ name: 'enterprise', dir: '.output/chrome-mv3-enterprise', contentBudget: 16 * 1024, backgroundBudget: BRIDGE_BACKGROUND_BUDGET, backgroundGzipBudget: ENTERPRISE_BACKGROUND_GZIP_BUDGET, totalBudget: TOTAL_PACKAGE_BUDGET, directEval: true, userScripts: true, execution: 'user-scripts+injected-fallback' },
|
||||
{ name: 'firefox', dir: '.output/firefox-mv2', contentBudget: 16 * 1024, backgroundBudget: BRIDGE_BACKGROUND_BUDGET, backgroundGzipBudget: BRIDGE_BACKGROUND_GZIP_BUDGET, totalBudget: TOTAL_PACKAGE_BUDGET, directEval: true, userScripts: false, execution: 'injected-bridge' },
|
||||
{ name: 'firefox-amo', dir: '.output/firefox-mv3-store', contentBudget: 12 * 1024, backgroundBudget: BRIDGE_BACKGROUND_BUDGET, backgroundGzipBudget: BRIDGE_BACKGROUND_GZIP_BUDGET, totalBudget: TOTAL_PACKAGE_BUDGET, directEval: false, userScripts: false, execution: 'invoke-only' },
|
||||
];
|
||||
|
||||
async function fileSize(path) {
|
||||
return (await stat(path)).size;
|
||||
}
|
||||
|
||||
async function exists(path) {
|
||||
try {
|
||||
await access(path);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function assert(condition, message) {
|
||||
if (!condition) throw new Error(message);
|
||||
}
|
||||
|
||||
async function directorySize(path) {
|
||||
const { readdir } = await import('node:fs/promises');
|
||||
let total = 0;
|
||||
for (const entry of await readdir(path, { withFileTypes: true })) {
|
||||
const child = join(path, entry.name);
|
||||
total += entry.isDirectory() ? await directorySize(child) : await fileSize(child);
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
async function assertNoFixtureLeakage(path, targetName) {
|
||||
const { readdir } = await import('node:fs/promises');
|
||||
const findings = [];
|
||||
async function visit(directory) {
|
||||
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
||||
const child = join(directory, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
await visit(child);
|
||||
continue;
|
||||
}
|
||||
if (!/\.(?:css|html|js|json|map)$/i.test(entry.name)) continue;
|
||||
const source = await readFile(child, 'utf8');
|
||||
for (const signature of FIXTURE_LEAK_SIGNATURES) {
|
||||
if (source.includes(signature)) findings.push(`${child.slice(path.length + 1)} -> ${signature}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
await visit(path);
|
||||
assert(findings.length === 0, `${targetName} 生产产物混入靶场 fixture:${findings.join(', ')}`);
|
||||
}
|
||||
|
||||
const report = [];
|
||||
for (const target of targets) {
|
||||
const isFirefox = target.name.startsWith('firefox');
|
||||
const output = resolve(root, target.dir);
|
||||
assert(await exists(output), `${target.name} 产物不存在,请先运行对应构建命令`);
|
||||
await assertNoFixtureLeakage(output, target.name);
|
||||
const manifest = JSON.parse(await readFile(join(output, 'manifest.json'), 'utf8'));
|
||||
const contentBytes = await fileSize(join(output, 'content-scripts/agent.js'));
|
||||
const backgroundSource = await readFile(join(output, 'background.js'));
|
||||
const backgroundBytes = backgroundSource.byteLength;
|
||||
const backgroundGzipBytes = gzipSync(backgroundSource).byteLength;
|
||||
const recorderBytes = await fileSize(join(output, 'page-recorder-main-world.js'));
|
||||
const totalBytes = await directorySize(output);
|
||||
const sizeAdvisories = [];
|
||||
const directEvalExists = await exists(join(output, 'page-main-world.js'));
|
||||
const resources = (manifest.web_accessible_resources || []).flatMap((entry) => typeof entry === 'string' ? [entry] : entry.resources || []);
|
||||
const dynamicResourceGroup = (manifest.web_accessible_resources || []).find((entry) => typeof entry !== 'string' && entry.resources?.includes('floating.html'));
|
||||
|
||||
if (!isFirefox) {
|
||||
assert(typeof manifest.key === 'string', `${target.name} 缺少固定扩展公钥`);
|
||||
const extensionId = createHash('sha256').update(Buffer.from(manifest.key, 'base64')).digest('hex').slice(0, 32).replace(/[0-9a-f]/g, (digit) => String.fromCharCode(97 + Number.parseInt(digit, 16)));
|
||||
assert(extensionId === CHROMIUM_EXTENSION_ID, `${target.name} 扩展 ID 漂移:${extensionId}`);
|
||||
}
|
||||
|
||||
if (contentBytes > target.contentBudget) sizeAdvisories.push(`content script ${contentBytes}B > ${target.contentBudget}B reference`);
|
||||
if (backgroundBytes > target.backgroundBudget) sizeAdvisories.push(`background ${backgroundBytes}B > ${target.backgroundBudget}B reference`);
|
||||
if (backgroundGzipBytes > target.backgroundGzipBudget) sizeAdvisories.push(`background gzip ${backgroundGzipBytes}B > ${target.backgroundGzipBudget}B reference`);
|
||||
if (recorderBytes > MAIN_WORLD_PIPELINE_BUDGET) sizeAdvisories.push(`MAIN-world runtime ${recorderBytes}B > ${MAIN_WORLD_PIPELINE_BUDGET}B reference`);
|
||||
if (totalBytes > target.totalBudget) sizeAdvisories.push(`package ${totalBytes}B > ${target.totalBudget}B reference`);
|
||||
assert(directEvalExists === target.directEval, `${target.name} page-main-world.js 存在状态不符合构建策略`);
|
||||
assert(resources.includes('page-main-world.js') === target.directEval, `${target.name} page-main-world.js 暴露状态不符合构建策略`);
|
||||
assert((manifest.permissions || []).includes('userScripts') === target.userScripts, `${target.name} userScripts 权限不符合构建策略`);
|
||||
if (target.name === 'store' || target.name === 'firefox-amo') {
|
||||
assert(!backgroundSource.toString().includes('(0,eval)'), `${target.name} background 不得包含间接 Eval 实现`);
|
||||
}
|
||||
assert((manifest.permissions || []).includes('webRequest'), `${target.name} 缺少网络捕获所需 webRequest 权限`);
|
||||
assert((manifest.permissions || []).includes('webNavigation'), `${target.name} 缺少 frame/document 生命周期所需 webNavigation 权限`);
|
||||
assert((manifest.permissions || []).includes('debugger') === !isFirefox, `${target.name} debugger 权限不符合 Chromium-only 深度捕获策略`);
|
||||
assert(!(manifest.permissions || []).includes('activeTab'), `${target.name} 不应申请未使用的 activeTab 权限`);
|
||||
assert(!(manifest.permissions || []).includes('nativeMessaging') && (manifest.optional_permissions || []).includes('nativeMessaging'), `${target.name} Native Messaging 必须按需授权`);
|
||||
assert((manifest.permissions || []).includes(isFirefox ? 'webRequestBlocking' : 'webRequestAuthProvider'), `${target.name} 缺少代理认证权限`);
|
||||
assert(manifest.storage?.managed_schema === 'managed-storage-schema.json', `${target.name} 缺少企业 managed storage schema`);
|
||||
assert(await exists(join(output, 'managed-storage-schema.json')), `${target.name} managed storage schema 未打包`);
|
||||
if (!isFirefox) assert(!(manifest.permissions || []).includes('webRequestBlocking'), `${target.name} 不应申请阻断或修改网络请求的 webRequestBlocking 权限`);
|
||||
assert(resources.includes('floating.html'), `${target.name} 没有公开按需浮动页`);
|
||||
if (manifest.manifest_version === 3) assert(dynamicResourceGroup?.use_dynamic_url === true, `${target.name} 浮动页必须使用动态资源 URL`);
|
||||
|
||||
report.push({
|
||||
target: target.name,
|
||||
contentScriptKiB: Number((contentBytes / 1024).toFixed(2)),
|
||||
backgroundKiB: Number((backgroundBytes / 1024).toFixed(2)),
|
||||
backgroundGzipKiB: Number((backgroundGzipBytes / 1024).toFixed(2)),
|
||||
recorderKiB: Number((recorderBytes / 1024).toFixed(2)),
|
||||
totalKiB: Number((totalBytes / 1024).toFixed(2)),
|
||||
sizeAdvisories,
|
||||
execution: target.execution,
|
||||
});
|
||||
}
|
||||
|
||||
console.log(JSON.stringify(report, null, 2));
|
||||
@@ -0,0 +1,105 @@
|
||||
import {mkdtemp, readFile, rm} from 'node:fs/promises'
|
||||
import {tmpdir} from 'node:os'
|
||||
import {join, resolve} from 'node:path'
|
||||
import {chromium} from 'playwright-core'
|
||||
import {resolveChromiumPath} from './resolve-chromium.mjs'
|
||||
|
||||
const root = resolve(import.meta.dirname, '..')
|
||||
|
||||
export async function extensionRequest(page, action, payload = {}) {
|
||||
return page.evaluate(async ({requestAction, requestPayload}) => {
|
||||
const response = await chrome.runtime.sendMessage({action: requestAction, payload: requestPayload})
|
||||
if (!response?.ok) throw new Error(response?.error?.message || response?.error || requestAction)
|
||||
return response.data
|
||||
}, {requestAction: action, requestPayload: payload})
|
||||
}
|
||||
|
||||
export async function waitFor(page, action, payload, predicate, timeoutMs = 15_000) {
|
||||
const deadline = Date.now() + timeoutMs
|
||||
let value
|
||||
while (Date.now() < deadline) {
|
||||
value = await extensionRequest(page, action, payload)
|
||||
if (predicate(value)) return value
|
||||
await page.waitForTimeout(150)
|
||||
}
|
||||
throw new Error(`Timed out waiting for ${action}: ${JSON.stringify(value)}`)
|
||||
}
|
||||
|
||||
export async function launchBrowserAgentContractHarness({
|
||||
profilePrefix,
|
||||
targetURL,
|
||||
extensionPath = resolve(root, process.env.EXTENSION_PATH || '.output/chrome-mv3-enterprise'),
|
||||
}) {
|
||||
const manifest = JSON.parse(await readFile(resolve(extensionPath, 'manifest.json'), 'utf8'))
|
||||
const executablePath = await resolveChromiumPath()
|
||||
const userDataDir = await mkdtemp(join(tmpdir(), profilePrefix))
|
||||
const context = await chromium.launchPersistentContext(userDataDir, {
|
||||
executablePath,
|
||||
headless: true,
|
||||
viewport: {width: 1280, height: 760},
|
||||
args: [
|
||||
`--disable-extensions-except=${extensionPath}`,
|
||||
`--load-extension=${extensionPath}`,
|
||||
'--no-first-run',
|
||||
'--no-default-browser-check',
|
||||
],
|
||||
})
|
||||
try {
|
||||
let serviceWorker = context.serviceWorkers()[0]
|
||||
if (!serviceWorker) serviceWorker = await context.waitForEvent('serviceworker', {timeout: 15_000})
|
||||
const extensionId = new URL(serviceWorker.url()).host
|
||||
|
||||
if (manifest.permissions?.includes('userScripts')) {
|
||||
const extensionsPage = await context.newPage()
|
||||
await extensionsPage.goto(`chrome://extensions/?id=${extensionId}`)
|
||||
const toggle = extensionsPage.locator('#allow-user-scripts cr-toggle')
|
||||
await toggle.waitFor({state: 'visible', timeout: 10_000})
|
||||
if (!await toggle.evaluate((element) => Boolean(element.checked))) await toggle.click()
|
||||
await extensionsPage.close()
|
||||
}
|
||||
|
||||
const targetPage = await context.newPage()
|
||||
targetPage.on('dialog', (dialog) => void dialog.dismiss())
|
||||
await targetPage.goto(targetURL)
|
||||
|
||||
const controlPage = await context.newPage()
|
||||
await controlPage.goto(`chrome-extension://${extensionId}/options.html`)
|
||||
const tabId = await controlPage.evaluate(async (url) => {
|
||||
const tabs = await chrome.tabs.query({})
|
||||
return tabs.find((tab) => tab.url === url)?.id
|
||||
}, targetPage.url())
|
||||
if (!tabId) throw new Error(`Could not resolve target tab ${targetPage.url()}`)
|
||||
|
||||
return {
|
||||
context,
|
||||
controlPage,
|
||||
extensionId,
|
||||
tabId,
|
||||
targetPage,
|
||||
async close() {
|
||||
await context.close().catch(() => undefined)
|
||||
await rm(userDataDir, {recursive: true, force: true})
|
||||
},
|
||||
}
|
||||
} catch (error) {
|
||||
await context.close().catch(() => undefined)
|
||||
await rm(userDataDir, {recursive: true, force: true})
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export function transformedFetchOptions(execution, originalHeaders) {
|
||||
const headers = new Map(originalHeaders.map((header) => [header.name.toLowerCase(), {
|
||||
name: header.name,
|
||||
value: header.value,
|
||||
}]))
|
||||
for (const name of execution.removeHeaders || []) headers.delete(name.toLowerCase())
|
||||
for (const header of execution.setHeaders || []) {
|
||||
headers.set(header.name.toLowerCase(), {name: header.name, value: header.value})
|
||||
}
|
||||
return {
|
||||
method: 'POST',
|
||||
headers: Object.fromEntries([...headers.values()].map((header) => [header.name, header.value])),
|
||||
body: Buffer.from(execution.bodyBase64, 'base64'),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Merges the freshly packaged release (dist/release-entry.json) into the
|
||||
* public manifest and writes manifest.json + manifest.json.sha256.txt.
|
||||
*
|
||||
* The manifest is the single entry point consumers read: `latest` plus a
|
||||
* bounded `versions[]` history. Artifact objects are immutable and their URLs
|
||||
* are never rewritten; only this manifest moves.
|
||||
*
|
||||
* Usage:
|
||||
* node scripts/build-manifest.mjs --release-entry=dist/release-entry.json \
|
||||
* [--existing-manifest=dist/existing-manifest.json] [--max-versions=10] \
|
||||
* --output=dist/manifest.json --checksum-output=dist/manifest.json.sha256.txt
|
||||
*/
|
||||
import { createHash } from 'node:crypto';
|
||||
import { readFile, writeFile } from 'node:fs/promises';
|
||||
import { resolve } from 'node:path';
|
||||
|
||||
const root = resolve(import.meta.dirname, '..');
|
||||
|
||||
function parseArgs(argv) {
|
||||
const out = {};
|
||||
for (const arg of argv) {
|
||||
if (!arg.startsWith('--')) throw new Error(`unexpected argument: ${arg}`);
|
||||
const eq = arg.indexOf('=');
|
||||
const key = eq === -1 ? arg.slice(2) : arg.slice(2, eq);
|
||||
out[key] = eq === -1 ? true : arg.slice(eq + 1);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function artifactFingerprint(artifacts) {
|
||||
return artifacts.map((a) => `${a.variant}:${a.sha256}`).sort().join('|');
|
||||
}
|
||||
|
||||
function toVersionEntry(entry) {
|
||||
return {
|
||||
version: entry.version,
|
||||
published_at: entry.built_at,
|
||||
commit: entry.commit ?? null,
|
||||
artifacts: entry.artifacts.map((a) => ({
|
||||
variant: a.variant,
|
||||
browser: a.browser,
|
||||
mode: a.mode,
|
||||
filename: a.filename,
|
||||
url: a.url,
|
||||
sha256: a.sha256,
|
||||
size: a.size,
|
||||
checksum_url: a.checksum_url,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function validate(manifest) {
|
||||
if (!Array.isArray(manifest.versions) || manifest.versions.length === 0) {
|
||||
throw new Error('manifest must contain at least one version');
|
||||
}
|
||||
if (manifest.latest !== manifest.versions[0].version) {
|
||||
throw new Error(`manifest.latest (${manifest.latest}) must equal versions[0].version (${manifest.versions[0].version})`);
|
||||
}
|
||||
const seen = new Set();
|
||||
for (const versionEntry of manifest.versions) {
|
||||
if (seen.has(versionEntry.version)) throw new Error(`duplicate version in manifest: ${versionEntry.version}`);
|
||||
seen.add(versionEntry.version);
|
||||
if (!Array.isArray(versionEntry.artifacts) || versionEntry.artifacts.length === 0) {
|
||||
throw new Error(`version ${versionEntry.version} has no artifacts`);
|
||||
}
|
||||
const variants = new Set();
|
||||
for (const artifact of versionEntry.artifacts) {
|
||||
if (variants.has(artifact.variant)) throw new Error(`duplicate variant ${artifact.variant} in version ${versionEntry.version}`);
|
||||
variants.add(artifact.variant);
|
||||
if (!/^[0-9a-f]{64}$/.test(artifact.sha256)) throw new Error(`artifact ${artifact.filename}: bad sha256`);
|
||||
if (!Number.isInteger(artifact.size) || artifact.size <= 0) throw new Error(`artifact ${artifact.filename}: bad size`);
|
||||
if (!/^https?:\/\//.test(artifact.url)) throw new Error(`artifact ${artifact.filename}: url must be absolute`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
if (!args['release-entry']) throw new Error('--release-entry is required');
|
||||
if (!args.output) throw new Error('--output is required');
|
||||
if (!args['checksum-output']) throw new Error('--checksum-output is required');
|
||||
|
||||
const entry = JSON.parse(await readFile(resolve(root, String(args['release-entry'])), 'utf8'));
|
||||
const maxVersions = Number.parseInt(String(args['max-versions'] ?? '10'), 10);
|
||||
if (!Number.isInteger(maxVersions) || maxVersions < 1) throw new Error('--max-versions must be a positive integer');
|
||||
|
||||
let versions = [];
|
||||
let existingUpdatedAt = null;
|
||||
let existingManifestBytes = null;
|
||||
if (args['existing-manifest']) {
|
||||
try {
|
||||
existingManifestBytes = await readFile(resolve(root, String(args['existing-manifest'])));
|
||||
const existing = JSON.parse(existingManifestBytes.toString('utf8'));
|
||||
versions = Array.isArray(existing.versions) ? existing.versions : [];
|
||||
existingUpdatedAt = typeof existing.updated_at === 'string' ? existing.updated_at : null;
|
||||
} catch (err) {
|
||||
if (err?.code !== 'ENOENT') throw err;
|
||||
console.log('existing manifest not found; starting a fresh history');
|
||||
}
|
||||
}
|
||||
|
||||
const newEntry = toVersionEntry(entry);
|
||||
const idx = versions.findIndex((v) => v.version === entry.version);
|
||||
if (idx >= 0 && artifactFingerprint(versions[idx].artifacts) === artifactFingerprint(entry.artifacts)) {
|
||||
// Idempotent rerun: keep the original entry (published_at stays stable).
|
||||
console.log(`version ${entry.version} already in manifest with identical artifacts; kept as-is`);
|
||||
} else {
|
||||
if (idx >= 0) {
|
||||
versions.splice(idx, 1);
|
||||
console.log(`version ${entry.version} re-published with different artifacts; replaced entry`);
|
||||
}
|
||||
versions.unshift(newEntry);
|
||||
}
|
||||
versions = versions.slice(0, maxVersions);
|
||||
|
||||
// Preserve the previous updated_at when nothing actually changed: a no-op
|
||||
// re-publish would otherwise produce new manifest bytes (and a new checksum)
|
||||
// for identical content, racing the CDN's cache window.
|
||||
const candidate = { latest: versions[0].version, updated_at: '__now__', versions };
|
||||
const rebuildWith = (updatedAt) => JSON.stringify({ ...candidate, updated_at: updatedAt }, null, 2);
|
||||
const previousBytes = existingManifestBytes ? existingManifestBytes.toString('utf8').trimEnd() : null;
|
||||
const unchanged = existingUpdatedAt !== null && previousBytes === rebuildWith(existingUpdatedAt);
|
||||
const manifest = { ...candidate, updated_at: unchanged ? existingUpdatedAt : new Date().toISOString() };
|
||||
validate(manifest);
|
||||
|
||||
const bytes = Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
|
||||
await writeFile(resolve(root, String(args.output)), bytes);
|
||||
const sha256 = createHash('sha256').update(bytes).digest('hex');
|
||||
await writeFile(resolve(root, String(args['checksum-output'])), `${sha256} manifest.json\n`);
|
||||
console.log(`manifest written: ${args.output} (latest=${manifest.latest}, ${versions.length} version(s) retained${unchanged ? ', content unchanged' : ''})`);
|
||||
@@ -1,217 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
// Do this as the first thing so that any code reading it knows the right env.
|
||||
process.env.BABEL_ENV = 'production';
|
||||
process.env.NODE_ENV = 'production';
|
||||
|
||||
// Makes the script crash on unhandled rejections instead of silently
|
||||
// ignoring them. In the future, promise rejections that are not handled will
|
||||
// terminate the Node.js process with a non-zero exit code.
|
||||
process.on('unhandledRejection', err => {
|
||||
throw err;
|
||||
});
|
||||
|
||||
// Ensure environment variables are read.
|
||||
require('../config/env');
|
||||
|
||||
const path = require('path');
|
||||
const chalk = require('react-dev-utils/chalk');
|
||||
const fs = require('fs-extra');
|
||||
const bfj = require('bfj');
|
||||
const webpack = require('webpack');
|
||||
const configFactory = require('../config/webpack.config');
|
||||
const paths = require('../config/paths');
|
||||
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
|
||||
const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
|
||||
const printHostingInstructions = require('react-dev-utils/printHostingInstructions');
|
||||
const FileSizeReporter = require('react-dev-utils/FileSizeReporter');
|
||||
const printBuildError = require('react-dev-utils/printBuildError');
|
||||
|
||||
const measureFileSizesBeforeBuild =
|
||||
FileSizeReporter.measureFileSizesBeforeBuild;
|
||||
const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild;
|
||||
const useYarn = fs.existsSync(paths.yarnLockFile);
|
||||
|
||||
// These sizes are pretty large. We'll warn for bundles exceeding them.
|
||||
const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024;
|
||||
const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024;
|
||||
|
||||
const isInteractive = process.stdout.isTTY;
|
||||
|
||||
// Warn and crash if required files are missing
|
||||
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const argv = process.argv.slice(2);
|
||||
const writeStatsJson = argv.indexOf('--stats') !== -1;
|
||||
|
||||
// Generate configuration
|
||||
const config = configFactory('production');
|
||||
|
||||
// We require that you explicitly set browsers and do not fall back to
|
||||
// browserslist defaults.
|
||||
const { checkBrowsers } = require('react-dev-utils/browsersHelper');
|
||||
checkBrowsers(paths.appPath, isInteractive)
|
||||
.then(() => {
|
||||
// First, read the current file sizes in build directory.
|
||||
// This lets us display how much they changed later.
|
||||
return measureFileSizesBeforeBuild(paths.appBuild);
|
||||
})
|
||||
.then(previousFileSizes => {
|
||||
// Remove all content but keep the directory so that
|
||||
// if you're in it, you don't end up in Trash
|
||||
fs.emptyDirSync(paths.appBuild);
|
||||
// Merge with the public folder
|
||||
copyPublicFolder();
|
||||
// Start the webpack build
|
||||
return build(previousFileSizes);
|
||||
})
|
||||
.then(
|
||||
({ stats, previousFileSizes, warnings }) => {
|
||||
if (warnings.length) {
|
||||
console.log(chalk.yellow('Compiled with warnings.\n'));
|
||||
console.log(warnings.join('\n\n'));
|
||||
console.log(
|
||||
'\nSearch for the ' +
|
||||
chalk.underline(chalk.yellow('keywords')) +
|
||||
' to learn more about each warning.'
|
||||
);
|
||||
console.log(
|
||||
'To ignore, add ' +
|
||||
chalk.cyan('// eslint-disable-next-line') +
|
||||
' to the line before.\n'
|
||||
);
|
||||
} else {
|
||||
console.log(chalk.green('Compiled successfully.\n'));
|
||||
}
|
||||
|
||||
console.log('File sizes after gzip:\n');
|
||||
printFileSizesAfterBuild(
|
||||
stats,
|
||||
previousFileSizes,
|
||||
paths.appBuild,
|
||||
WARN_AFTER_BUNDLE_GZIP_SIZE,
|
||||
WARN_AFTER_CHUNK_GZIP_SIZE
|
||||
);
|
||||
console.log();
|
||||
|
||||
const appPackage = require(paths.appPackageJson);
|
||||
const publicUrl = paths.publicUrlOrPath;
|
||||
const publicPath = config.output.publicPath;
|
||||
const buildFolder = path.relative(process.cwd(), paths.appBuild);
|
||||
printHostingInstructions(
|
||||
appPackage,
|
||||
publicUrl,
|
||||
publicPath,
|
||||
buildFolder,
|
||||
useYarn
|
||||
);
|
||||
},
|
||||
err => {
|
||||
const tscCompileOnError = process.env.TSC_COMPILE_ON_ERROR === 'true';
|
||||
if (tscCompileOnError) {
|
||||
console.log(
|
||||
chalk.yellow(
|
||||
'Compiled with the following type errors (you may want to check these before deploying your app):\n'
|
||||
)
|
||||
);
|
||||
printBuildError(err);
|
||||
} else {
|
||||
console.log(chalk.red('Failed to compile.\n'));
|
||||
printBuildError(err);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
)
|
||||
.catch(err => {
|
||||
if (err && err.message) {
|
||||
console.log(err.message);
|
||||
}
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
// Create the production build and print the deployment instructions.
|
||||
function build(previousFileSizes) {
|
||||
console.log('Creating an optimized production build...');
|
||||
|
||||
const compiler = webpack(config);
|
||||
return new Promise((resolve, reject) => {
|
||||
compiler.run((err, stats) => {
|
||||
let messages;
|
||||
if (err) {
|
||||
if (!err.message) {
|
||||
return reject(err);
|
||||
}
|
||||
|
||||
let errMessage = err.message;
|
||||
|
||||
// Add additional information for postcss errors
|
||||
if (Object.prototype.hasOwnProperty.call(err, 'postcssNode')) {
|
||||
errMessage +=
|
||||
'\nCompileError: Begins at CSS selector ' +
|
||||
err['postcssNode'].selector;
|
||||
}
|
||||
|
||||
messages = formatWebpackMessages({
|
||||
errors: [errMessage],
|
||||
warnings: [],
|
||||
});
|
||||
} else {
|
||||
messages = formatWebpackMessages(
|
||||
stats.toJson({ all: false, warnings: true, errors: true })
|
||||
);
|
||||
}
|
||||
if (messages.errors.length) {
|
||||
// Only keep the first error. Others are often indicative
|
||||
// of the same problem, but confuse the reader with noise.
|
||||
if (messages.errors.length > 1) {
|
||||
messages.errors.length = 1;
|
||||
}
|
||||
return reject(new Error(messages.errors.join('\n\n')));
|
||||
}
|
||||
if (
|
||||
process.env.CI &&
|
||||
(typeof process.env.CI !== 'string' ||
|
||||
process.env.CI.toLowerCase() !== 'false') &&
|
||||
messages.warnings.length
|
||||
) {
|
||||
// Ignore sourcemap warnings in CI builds. See #8227 for more info.
|
||||
const filteredWarnings = messages.warnings.filter(
|
||||
w => !/Failed to parse source map/.test(w)
|
||||
);
|
||||
if (filteredWarnings.length) {
|
||||
console.log(
|
||||
chalk.yellow(
|
||||
'\nTreating warnings as errors because process.env.CI = true.\n' +
|
||||
'Most CI servers set it automatically.\n'
|
||||
)
|
||||
);
|
||||
return reject(new Error(filteredWarnings.join('\n\n')));
|
||||
}
|
||||
}
|
||||
|
||||
const resolveArgs = {
|
||||
stats,
|
||||
previousFileSizes,
|
||||
warnings: messages.warnings,
|
||||
};
|
||||
|
||||
if (writeStatsJson) {
|
||||
return bfj
|
||||
.write(paths.appBuild + '/bundle-stats.json', stats.toJson())
|
||||
.then(() => resolve(resolveArgs))
|
||||
.catch(error => reject(new Error(error)));
|
||||
}
|
||||
|
||||
return resolve(resolveArgs);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function copyPublicFolder() {
|
||||
fs.copySync(paths.appPublic, paths.appBuild, {
|
||||
dereference: true,
|
||||
filter: file => file !== paths.appHtml,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { createInterface } from 'node:readline';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { access, mkdir, realpath } from 'node:fs/promises';
|
||||
import { constants } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
|
||||
const root = process.cwd();
|
||||
const output = resolve(root, '.output/chrome-mv3-dev');
|
||||
const manifest = resolve(output, 'manifest.json');
|
||||
const profile = resolve(root, '.wxt/chrome-wsl-profile');
|
||||
const chrome = process.env.CHROME_PATH || '/usr/bin/google-chrome';
|
||||
|
||||
await access(chrome, constants.X_OK).catch(() => {
|
||||
throw new Error(`Chrome is not executable: ${chrome}. Set CHROME_PATH to override it.`);
|
||||
});
|
||||
await mkdir(profile, { recursive: true });
|
||||
const resolvedChrome = await realpath(chrome);
|
||||
const isBrandedChrome = resolvedChrome.startsWith('/opt/google/chrome/');
|
||||
|
||||
const wxt = spawn(process.execPath, [resolve(root, 'node_modules/wxt/bin/wxt.mjs')], {
|
||||
cwd: root,
|
||||
env: process.env,
|
||||
stdio: ['inherit', 'pipe', 'pipe'],
|
||||
});
|
||||
|
||||
const pipeLines = (stream, destination) => {
|
||||
const reader = createInterface({ input: stream });
|
||||
reader.on('line', (line) => {
|
||||
if (!line.includes('Cannot open browser when using WSL')) destination.write(`${line}\n`);
|
||||
});
|
||||
};
|
||||
pipeLines(wxt.stdout, process.stdout);
|
||||
pipeLines(wxt.stderr, process.stderr);
|
||||
|
||||
const waitForManifest = async () => {
|
||||
for (let attempt = 0; attempt < 200; attempt += 1) {
|
||||
if (wxt.exitCode !== null) throw new Error(`WXT exited before producing ${manifest}`);
|
||||
try {
|
||||
await access(manifest, constants.R_OK);
|
||||
return;
|
||||
} catch {
|
||||
await new Promise((resolveWait) => setTimeout(resolveWait, 100));
|
||||
}
|
||||
}
|
||||
throw new Error(`Timed out waiting for ${manifest}`);
|
||||
};
|
||||
|
||||
let chromeProcess;
|
||||
const shutdown = async (signal) => {
|
||||
if (chromeProcess?.exitCode === null) chromeProcess.kill(signal);
|
||||
if (wxt.exitCode === null) wxt.kill(signal);
|
||||
};
|
||||
process.once('SIGINT', () => void shutdown('SIGINT'));
|
||||
process.once('SIGTERM', () => void shutdown('SIGTERM'));
|
||||
|
||||
try {
|
||||
await waitForManifest();
|
||||
const chromeArgs = [
|
||||
`--user-data-dir=${profile}`,
|
||||
'--disable-gpu',
|
||||
'--no-first-run',
|
||||
'--no-default-browser-check',
|
||||
];
|
||||
if (!isBrandedChrome || process.env.WXT_AUTO_LOAD_EXTENSION === '1') {
|
||||
chromeArgs.push(`--disable-extensions-except=${output}`, `--load-extension=${output}`, 'about:blank');
|
||||
} else {
|
||||
chromeArgs.push('chrome://extensions');
|
||||
}
|
||||
chromeProcess = spawn(chrome, chromeArgs, { cwd: root, env: process.env, stdio: 'inherit' });
|
||||
if (isBrandedChrome && process.env.WXT_AUTO_LOAD_EXTENSION !== '1') {
|
||||
process.stdout.write(`\nOpened official Chrome with the persistent WXT profile.\nChrome 137+ ignores --load-extension in branded builds. On first run, enable Developer mode and load:\n${output}\nProfile: ${profile}\n`);
|
||||
} else {
|
||||
process.stdout.write(`\nOpened ${chrome} with the WXT development extension.\nProfile: ${profile}\n`);
|
||||
}
|
||||
} catch (error) {
|
||||
await shutdown('SIGTERM');
|
||||
throw error;
|
||||
}
|
||||
|
||||
await new Promise((resolveExit) => wxt.once('exit', resolveExit));
|
||||
if (chromeProcess?.exitCode === null) chromeProcess.kill('SIGTERM');
|
||||
@@ -0,0 +1,143 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Packages the release variants from .output into dist/<version>/ and writes
|
||||
* dist/release-entry.json recording filename/size/sha256/url for every
|
||||
* artifact, plus per-artifact .sha256.txt checksum files.
|
||||
*
|
||||
* The variant table must stay in sync with `verify:production` (package.json)
|
||||
* and scripts/audit-build.mjs — those define the published surface.
|
||||
*
|
||||
* Usage:
|
||||
* node scripts/package-release.mjs --public-base-url=https://aliyun-oss.yaklang.com/chrome-extension [--dist=dist]
|
||||
*/
|
||||
import { execFile } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { createReadStream, readdirSync } from 'node:fs';
|
||||
import { access } from 'node:fs/promises';
|
||||
import { mkdir, readFile, stat, writeFile } from 'node:fs/promises';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { pipeline } from 'node:stream/promises';
|
||||
import { promisify } from 'node:util';
|
||||
import AdmZip from 'adm-zip';
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const root = resolve(import.meta.dirname, '..');
|
||||
|
||||
const VARIANTS = [
|
||||
{ variant: 'chrome-store', browser: 'chrome', mode: 'store', dir: '.output/chrome-mv3-store' },
|
||||
{ variant: 'chrome-enterprise', browser: 'chrome', mode: 'enterprise', dir: '.output/chrome-mv3-enterprise' },
|
||||
{ variant: 'firefox', browser: 'firefox', mode: 'production', dir: '.output/firefox-mv2' },
|
||||
{ variant: 'firefox-amo', browser: 'firefox', mode: 'store', dir: '.output/firefox-mv3-store' },
|
||||
];
|
||||
|
||||
function parseArgs(argv) {
|
||||
const out = {};
|
||||
for (const arg of argv) {
|
||||
if (!arg.startsWith('--')) throw new Error(`unexpected argument: ${arg}`);
|
||||
const eq = arg.indexOf('=');
|
||||
const key = eq === -1 ? arg.slice(2) : arg.slice(2, eq);
|
||||
out[key] = eq === -1 ? true : arg.slice(eq + 1);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function exists(path) {
|
||||
try {
|
||||
await access(path);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function sha256File(path) {
|
||||
const hash = createHash('sha256');
|
||||
await pipeline(createReadStream(path), hash);
|
||||
return hash.digest('hex');
|
||||
}
|
||||
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
if (!args['public-base-url']) {
|
||||
throw new Error('--public-base-url is required (e.g. https://aliyun-oss.yaklang.com/chrome-extension)');
|
||||
}
|
||||
const baseUrl = String(args['public-base-url']).replace(/\/+$/, '');
|
||||
const distDir = resolve(root, String(args.dist ?? 'dist'));
|
||||
|
||||
const pkg = JSON.parse(await readFile(resolve(root, 'package.json'), 'utf8'));
|
||||
const { version } = pkg;
|
||||
|
||||
let commit = null;
|
||||
try {
|
||||
const { stdout } = await execFileAsync('git', ['rev-parse', 'HEAD'], { cwd: root });
|
||||
commit = stdout.trim();
|
||||
} catch {
|
||||
// Not fatal: local runs outside a git worktree still package fine.
|
||||
}
|
||||
// Reproducibility must hold per VERSION, not per commit: a workflow that fails
|
||||
// late (e.g. at the summary step) gets fixed on a follow-up commit and re-run
|
||||
// for the same version, and the immutable no-overwrite guard then needs the
|
||||
// rebuilt zip to match byte-for-byte. So pin entry timestamps to a fixed
|
||||
// epoch (SOURCE_DATE_EPOCH convention) instead of anything commit-derived.
|
||||
const FIXED_EPOCH = Date.UTC(2025, 0, 1);
|
||||
const pinned = new Date(Math.floor((Number(process.env.SOURCE_DATE_EPOCH) || FIXED_EPOCH) / 2000) * 2000); // DOS time has 2s granularity
|
||||
|
||||
// readdir order is not stable across machines, and adm-zip preserves it.
|
||||
// Walk sorted so every runner emits entries in the same order.
|
||||
function collectSorted(dir, base = '') {
|
||||
const files = [];
|
||||
const entries = readdirSync(dir, { withFileTypes: true });
|
||||
entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
||||
for (const entry of entries) {
|
||||
const rel = base ? `${base}/${entry.name}` : entry.name;
|
||||
if (entry.isDirectory()) files.push(...collectSorted(join(dir, entry.name), rel));
|
||||
else files.push(rel);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
const versionDir = resolve(distDir, version);
|
||||
await mkdir(versionDir, { recursive: true });
|
||||
|
||||
const artifacts = [];
|
||||
for (const target of VARIANTS) {
|
||||
const outputDir = resolve(root, target.dir);
|
||||
if (!(await exists(resolve(outputDir, 'manifest.json')))) {
|
||||
throw new Error(`${target.variant}: ${target.dir}/manifest.json missing — run the build first (pnpm verify:production)`);
|
||||
}
|
||||
const builtManifest = JSON.parse(await readFile(resolve(outputDir, 'manifest.json'), 'utf8'));
|
||||
if (builtManifest.version !== version) {
|
||||
throw new Error(`${target.variant}: built manifest version ${builtManifest.version} != package.json version ${version}`);
|
||||
}
|
||||
|
||||
const filename = `${target.variant}-${version}.zip`;
|
||||
const zipPath = resolve(versionDir, filename);
|
||||
// Entry paths are relative to the output dir so manifest.json sits at the
|
||||
// zip root, which is what browsers expect from a sideloaded extension.
|
||||
const zip = new AdmZip();
|
||||
for (const rel of collectSorted(outputDir)) {
|
||||
const slash = rel.lastIndexOf('/');
|
||||
const dir = slash === -1 ? '' : rel.slice(0, slash);
|
||||
zip.addLocalFile(join(outputDir, rel), dir, rel.slice(slash + 1));
|
||||
}
|
||||
for (const entry of zip.getEntries()) entry.header.time = pinned;
|
||||
await zip.writeZipPromise(zipPath);
|
||||
const sha256 = await sha256File(zipPath);
|
||||
const size = (await stat(zipPath)).size;
|
||||
await writeFile(resolve(versionDir, `${filename}.sha256.txt`), `${sha256} ${filename}\n`);
|
||||
|
||||
artifacts.push({
|
||||
variant: target.variant,
|
||||
browser: target.browser,
|
||||
mode: target.mode,
|
||||
filename,
|
||||
url: `${baseUrl}/${version}/${filename}`,
|
||||
sha256,
|
||||
size,
|
||||
checksum_url: `${baseUrl}/${version}/${filename}.sha256.txt`,
|
||||
});
|
||||
console.log(`packaged ${filename} (${size} bytes, sha256 ${sha256.slice(0, 12)}…)`);
|
||||
}
|
||||
|
||||
const entry = { version, commit, built_at: new Date().toISOString(), artifacts };
|
||||
await writeFile(resolve(distDir, 'release-entry.json'), `${JSON.stringify(entry, null, 2)}\n`);
|
||||
console.log(`release entry written: ${resolve(distDir, 'release-entry.json').slice(root.length + 1)} (version ${version})`);
|
||||
@@ -0,0 +1,150 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Publishes release artifacts and the manifest to Aliyun OSS.
|
||||
*
|
||||
* The contract mirrors yaklang/browser-binaries-mirror:
|
||||
* - versioned artifacts are immutable: one-year immutable cache headers,
|
||||
* sha256 user meta, x-oss-forbid-overwrite on upload; an existing object
|
||||
* with a different sha256 is a hard error, an identical one is skipped
|
||||
* - manifest.json is mutable: five-minute cache; it is published first and
|
||||
* its checksum second, so consumers can always detect a torn publish by
|
||||
* verifying the checksum file
|
||||
*
|
||||
* Credentials come from OSS_KEY_ID / OSS_KEY_SECRET (org-level secrets).
|
||||
*
|
||||
* Usage:
|
||||
* OSS_KEY_ID=… OSS_KEY_SECRET=… node scripts/publish-oss.mjs release \
|
||||
* --release-entry=dist/release-entry.json [--dist=dist]
|
||||
* [--endpoint=https://oss-accelerate.aliyuncs.com] [--bucket=yaklang] [--prefix=chrome-extension]
|
||||
* OSS_KEY_ID=… OSS_KEY_SECRET=… node scripts/publish-oss.mjs manifest \
|
||||
* --manifest=dist/manifest.json --manifest-checksum=dist/manifest.json.sha256.txt [endpoint/bucket/prefix]
|
||||
*/
|
||||
import { createHash } from 'node:crypto';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { resolve } from 'node:path';
|
||||
import OSSModule from 'ali-oss';
|
||||
|
||||
const OSS = OSSModule.default ?? OSSModule;
|
||||
const root = resolve(import.meta.dirname, '..');
|
||||
|
||||
const ARTIFACT_CACHE = 'public, max-age=31536000, immutable';
|
||||
const MANIFEST_CACHE = 'public, max-age=300, must-revalidate';
|
||||
|
||||
function parseArgs(argv) {
|
||||
const out = {};
|
||||
for (const arg of argv) {
|
||||
if (!arg.startsWith('--')) throw new Error(`unexpected argument: ${arg}`);
|
||||
const eq = arg.indexOf('=');
|
||||
const key = eq === -1 ? arg.slice(2) : arg.slice(2, eq);
|
||||
out[key] = eq === -1 ? true : arg.slice(eq + 1);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const [subcommand, ...rest] = process.argv.slice(2);
|
||||
const args = parseArgs(rest);
|
||||
const endpoint = String(args.endpoint ?? 'https://oss-accelerate.aliyuncs.com');
|
||||
const bucket = String(args.bucket ?? 'yaklang');
|
||||
const prefix = String(args.prefix ?? 'chrome-extension').replace(/^\/+|\/+$/g, '');
|
||||
|
||||
const accessKeyId = process.env.OSS_KEY_ID;
|
||||
const accessKeySecret = process.env.OSS_KEY_SECRET;
|
||||
if (!accessKeyId || !accessKeySecret) {
|
||||
throw new Error('OSS_KEY_ID and OSS_KEY_SECRET must be set in the environment');
|
||||
}
|
||||
if (subcommand !== 'release' && subcommand !== 'manifest') {
|
||||
throw new Error(`unknown subcommand: ${subcommand ?? '(none)'} — expected "release" or "manifest"`);
|
||||
}
|
||||
|
||||
const client = new OSS({ accessKeyId, accessKeySecret, bucket, endpoint, secure: true });
|
||||
|
||||
const sha256 = (buffer) => createHash('sha256').update(buffer).digest('hex');
|
||||
|
||||
// head() resolves to { meta, res, status }: raw headers live at res.headers
|
||||
// and x-oss-meta-* values are pre-parsed into meta.
|
||||
async function headObject(key) {
|
||||
try {
|
||||
const result = await client.head(key);
|
||||
return {
|
||||
size: Number(result.res.headers['content-length']),
|
||||
sha256: result.meta?.sha256 ?? null,
|
||||
};
|
||||
} catch (err) {
|
||||
if (err && (err.status === 404 || err.code === 'NoSuchKey')) return null;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
async function putObject(key, buffer, { mime, cacheControl, forbidOverwrite }) {
|
||||
const digest = sha256(buffer);
|
||||
await client.put(key, buffer, {
|
||||
mime,
|
||||
headers: {
|
||||
'Cache-Control': cacheControl,
|
||||
...(forbidOverwrite ? { 'x-oss-forbid-overwrite': 'true' } : {}),
|
||||
},
|
||||
meta: { sha256: digest },
|
||||
});
|
||||
const head = await headObject(key);
|
||||
if (!head) throw new Error(`upload verification failed, object missing: oss://${bucket}/${key}`);
|
||||
if (head.size !== buffer.length || head.sha256 !== digest) {
|
||||
throw new Error(`upload verification failed: oss://${bucket}/${key} (size ${head.size}/${buffer.length}, sha256 ${head.sha256}/${digest})`);
|
||||
}
|
||||
}
|
||||
|
||||
async function putImmutable(key, buffer, mime) {
|
||||
const digest = sha256(buffer);
|
||||
const existing = await headObject(key);
|
||||
if (existing) {
|
||||
if (existing.size === buffer.length && existing.sha256 === digest) {
|
||||
console.log(`skip (identical object already published): oss://${bucket}/${key}`);
|
||||
return;
|
||||
}
|
||||
throw new Error(
|
||||
`refusing to overwrite non-matching immutable object: oss://${bucket}/${key} ` +
|
||||
`(remote size=${existing.size} sha256=${existing.sha256 ?? 'unknown'}, local size=${buffer.length} sha256=${digest})`,
|
||||
);
|
||||
}
|
||||
await putObject(key, buffer, { mime, cacheControl: ARTIFACT_CACHE, forbidOverwrite: true });
|
||||
console.log(`uploaded: oss://${bucket}/${key} (${buffer.length} bytes)`);
|
||||
}
|
||||
|
||||
async function putMutable(key, buffer, mime) {
|
||||
await putObject(key, buffer, { mime, cacheControl: MANIFEST_CACHE, forbidOverwrite: false });
|
||||
console.log(`published: oss://${bucket}/${key}`);
|
||||
}
|
||||
|
||||
async function runRelease() {
|
||||
if (!args['release-entry']) throw new Error('release subcommand requires --release-entry');
|
||||
const entry = JSON.parse(await readFile(resolve(root, String(args['release-entry'])), 'utf8'));
|
||||
const versionDir = resolve(root, String(args.dist ?? 'dist'), entry.version);
|
||||
for (const artifact of entry.artifacts) {
|
||||
const zip = await readFile(resolve(versionDir, artifact.filename));
|
||||
const digest = sha256(zip);
|
||||
if (digest !== artifact.sha256) {
|
||||
throw new Error(`${artifact.filename}: on-disk sha256 ${digest} != release entry ${artifact.sha256}`);
|
||||
}
|
||||
await putImmutable(`${prefix}/${entry.version}/${artifact.filename}`, zip, 'application/zip');
|
||||
const checksum = await readFile(resolve(versionDir, `${artifact.filename}.sha256.txt`));
|
||||
await putImmutable(`${prefix}/${entry.version}/${artifact.filename}.sha256.txt`, checksum, 'text/plain; charset=utf-8');
|
||||
}
|
||||
}
|
||||
|
||||
async function runManifest() {
|
||||
if (!args.manifest) throw new Error('manifest subcommand requires --manifest');
|
||||
if (!args['manifest-checksum']) throw new Error('manifest subcommand requires --manifest-checksum');
|
||||
const manifest = await readFile(resolve(root, String(args.manifest)));
|
||||
const checksum = await readFile(resolve(root, String(args['manifest-checksum'])), 'utf8');
|
||||
const expected = `${sha256(manifest)} manifest.json\n`;
|
||||
if (checksum !== expected) {
|
||||
throw new Error('manifest checksum file does not match manifest.json content');
|
||||
}
|
||||
await putMutable(`${prefix}/manifest.json`, manifest, 'application/json; charset=utf-8');
|
||||
await putMutable(`${prefix}/manifest.json.sha256.txt`, Buffer.from(checksum, 'utf8'), 'text/plain; charset=utf-8');
|
||||
}
|
||||
|
||||
if (subcommand === 'release') {
|
||||
await runRelease();
|
||||
} else {
|
||||
await runManifest();
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { constants } from 'node:fs';
|
||||
import { access, readdir } from 'node:fs/promises';
|
||||
import { homedir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
|
||||
async function executable(path) {
|
||||
if (!path) return false;
|
||||
try {
|
||||
await access(path, constants.X_OK);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function resolveChromiumPath() {
|
||||
for (const candidate of [process.env.CHROMIUM_PATH, process.env.CHROME_PATH]) {
|
||||
if (await executable(candidate)) return candidate;
|
||||
}
|
||||
|
||||
const cacheRoot = process.env.PLAYWRIGHT_BROWSERS_PATH || join(homedir(), '.cache', 'ms-playwright');
|
||||
let entries = [];
|
||||
try {
|
||||
entries = (await readdir(cacheRoot, { withFileTypes: true }))
|
||||
.filter((entry) => entry.isDirectory() && entry.name.startsWith('chromium-'))
|
||||
.map((entry) => entry.name)
|
||||
.sort((left, right) => Number(right.slice(9)) - Number(left.slice(9)));
|
||||
} catch {
|
||||
// The final error below lists the supported configuration options.
|
||||
}
|
||||
for (const entry of entries) {
|
||||
for (const relative of ['chrome-linux64/chrome', 'chrome-linux/chrome']) {
|
||||
const candidate = join(cacheRoot, entry, relative);
|
||||
if (await executable(candidate)) return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
for (const command of ['google-chrome-for-testing', 'chromium', 'chromium-browser']) {
|
||||
const resolved = spawnSync('which', [command], { encoding: 'utf8' }).stdout.trim();
|
||||
if (await executable(resolved)) return resolved;
|
||||
}
|
||||
throw new Error('Unpacked-capable Chromium not found. Set CHROMIUM_PATH or install Chromium/Playwright Chromium.');
|
||||
}
|
||||
@@ -1,154 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
// Do this as the first thing so that any code reading it knows the right env.
|
||||
process.env.BABEL_ENV = 'development';
|
||||
process.env.NODE_ENV = 'development';
|
||||
|
||||
// Makes the script crash on unhandled rejections instead of silently
|
||||
// ignoring them. In the future, promise rejections that are not handled will
|
||||
// terminate the Node.js process with a non-zero exit code.
|
||||
process.on('unhandledRejection', err => {
|
||||
throw err;
|
||||
});
|
||||
|
||||
// Ensure environment variables are read.
|
||||
require('../config/env');
|
||||
|
||||
const fs = require('fs');
|
||||
const chalk = require('react-dev-utils/chalk');
|
||||
const webpack = require('webpack');
|
||||
const WebpackDevServer = require('webpack-dev-server');
|
||||
const clearConsole = require('react-dev-utils/clearConsole');
|
||||
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
|
||||
const {
|
||||
choosePort,
|
||||
createCompiler,
|
||||
prepareProxy,
|
||||
prepareUrls,
|
||||
} = require('react-dev-utils/WebpackDevServerUtils');
|
||||
const openBrowser = require('react-dev-utils/openBrowser');
|
||||
const semver = require('semver');
|
||||
const paths = require('../config/paths');
|
||||
const configFactory = require('../config/webpack.config');
|
||||
const createDevServerConfig = require('../config/webpackDevServer.config');
|
||||
const getClientEnvironment = require('../config/env');
|
||||
const react = require(require.resolve('react', { paths: [paths.appPath] }));
|
||||
|
||||
const env = getClientEnvironment(paths.publicUrlOrPath.slice(0, -1));
|
||||
const useYarn = fs.existsSync(paths.yarnLockFile);
|
||||
const isInteractive = process.stdout.isTTY;
|
||||
|
||||
// Warn and crash if required files are missing
|
||||
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Tools like Cloud9 rely on this.
|
||||
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
|
||||
const HOST = process.env.HOST || '0.0.0.0';
|
||||
|
||||
if (process.env.HOST) {
|
||||
console.log(
|
||||
chalk.cyan(
|
||||
`Attempting to bind to HOST environment variable: ${chalk.yellow(
|
||||
chalk.bold(process.env.HOST)
|
||||
)}`
|
||||
)
|
||||
);
|
||||
console.log(
|
||||
`If this was unintentional, check that you haven't mistakenly set it in your shell.`
|
||||
);
|
||||
console.log(
|
||||
`Learn more here: ${chalk.yellow('https://cra.link/advanced-config')}`
|
||||
);
|
||||
console.log();
|
||||
}
|
||||
|
||||
// We require that you explicitly set browsers and do not fall back to
|
||||
// browserslist defaults.
|
||||
const { checkBrowsers } = require('react-dev-utils/browsersHelper');
|
||||
checkBrowsers(paths.appPath, isInteractive)
|
||||
.then(() => {
|
||||
// We attempt to use the default port but if it is busy, we offer the user to
|
||||
// run on a different port. `choosePort()` Promise resolves to the next free port.
|
||||
return choosePort(HOST, DEFAULT_PORT);
|
||||
})
|
||||
.then(port => {
|
||||
if (port == null) {
|
||||
// We have not found a port.
|
||||
return;
|
||||
}
|
||||
|
||||
const config = configFactory('development');
|
||||
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
|
||||
const appName = require(paths.appPackageJson).name;
|
||||
|
||||
const useTypeScript = fs.existsSync(paths.appTsConfig);
|
||||
const urls = prepareUrls(
|
||||
protocol,
|
||||
HOST,
|
||||
port,
|
||||
paths.publicUrlOrPath.slice(0, -1)
|
||||
);
|
||||
// Create a webpack compiler that is configured with custom messages.
|
||||
const compiler = createCompiler({
|
||||
appName,
|
||||
config,
|
||||
urls,
|
||||
useYarn,
|
||||
useTypeScript,
|
||||
webpack,
|
||||
});
|
||||
// Load proxy config
|
||||
const proxySetting = require(paths.appPackageJson).proxy;
|
||||
const proxyConfig = prepareProxy(
|
||||
proxySetting,
|
||||
paths.appPublic,
|
||||
paths.publicUrlOrPath
|
||||
);
|
||||
// Serve webpack assets generated by the compiler over a web server.
|
||||
const serverConfig = {
|
||||
...createDevServerConfig(proxyConfig, urls.lanUrlForConfig),
|
||||
host: HOST,
|
||||
port,
|
||||
};
|
||||
const devServer = new WebpackDevServer(serverConfig, compiler);
|
||||
// Launch WebpackDevServer.
|
||||
devServer.startCallback(() => {
|
||||
if (isInteractive) {
|
||||
clearConsole();
|
||||
}
|
||||
|
||||
if (env.raw.FAST_REFRESH && semver.lt(react.version, '16.10.0')) {
|
||||
console.log(
|
||||
chalk.yellow(
|
||||
`Fast Refresh requires React 16.10 or higher. You are using React ${react.version}.`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
console.log(chalk.cyan('Starting the development server...\n'));
|
||||
openBrowser(urls.localUrlForBrowser);
|
||||
});
|
||||
|
||||
['SIGINT', 'SIGTERM'].forEach(function (sig) {
|
||||
process.on(sig, function () {
|
||||
devServer.close();
|
||||
process.exit();
|
||||
});
|
||||
});
|
||||
|
||||
if (process.env.CI !== 'true') {
|
||||
// Gracefully exit when stdin ends
|
||||
process.stdin.on('end', function () {
|
||||
devServer.close();
|
||||
process.exit();
|
||||
});
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
if (err && err.message) {
|
||||
console.log(err.message);
|
||||
}
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -1,52 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
// Do this as the first thing so that any code reading it knows the right env.
|
||||
process.env.BABEL_ENV = 'test';
|
||||
process.env.NODE_ENV = 'test';
|
||||
process.env.PUBLIC_URL = '';
|
||||
|
||||
// Makes the script crash on unhandled rejections instead of silently
|
||||
// ignoring them. In the future, promise rejections that are not handled will
|
||||
// terminate the Node.js process with a non-zero exit code.
|
||||
process.on('unhandledRejection', err => {
|
||||
throw err;
|
||||
});
|
||||
|
||||
// Ensure environment variables are read.
|
||||
require('../config/env');
|
||||
|
||||
const jest = require('jest');
|
||||
const execSync = require('child_process').execSync;
|
||||
let argv = process.argv.slice(2);
|
||||
|
||||
function isInGitRepository() {
|
||||
try {
|
||||
execSync('git rev-parse --is-inside-work-tree', { stdio: 'ignore' });
|
||||
return true;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isInMercurialRepository() {
|
||||
try {
|
||||
execSync('hg --cwd . root', { stdio: 'ignore' });
|
||||
return true;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Watch unless on CI or explicitly running all tests
|
||||
if (
|
||||
!process.env.CI &&
|
||||
argv.indexOf('--watchAll') === -1 &&
|
||||
argv.indexOf('--watchAll=false') === -1
|
||||
) {
|
||||
// https://github.com/facebook/create-react-app/issues/5210
|
||||
const hasSourceControl = isInGitRepository() || isInMercurialRepository();
|
||||
argv.push(hasSourceControl ? '--watch' : '--watchAll');
|
||||
}
|
||||
|
||||
|
||||
jest.run(argv);
|
||||
@@ -0,0 +1,140 @@
|
||||
import {
|
||||
extensionRequest,
|
||||
launchBrowserAgentContractHarness,
|
||||
transformedFetchOptions,
|
||||
} from './browser-agent-contract-harness.mjs'
|
||||
|
||||
const targetURL = process.env.AES_TARGET || 'http://127.0.0.1:82/'
|
||||
const plaintext = {username: 'admin', password: '123456'}
|
||||
let harness
|
||||
|
||||
try {
|
||||
harness = await launchBrowserAgentContractHarness({
|
||||
profilePrefix: 'yakit-aes-contract-',
|
||||
targetURL,
|
||||
})
|
||||
const {controlPage, tabId, targetPage} = harness
|
||||
let browserRequestCount = 0
|
||||
targetPage.on('request', (request) => {
|
||||
if (new URL(request.url()).pathname === '/encrypt/aes.php') browserRequestCount += 1
|
||||
})
|
||||
|
||||
await extensionRequest(controlPage, 'recording.start', {
|
||||
tabId,
|
||||
frameId: 0,
|
||||
captureValues: true,
|
||||
maxEntries: 120,
|
||||
maxValueBytes: 8_192,
|
||||
})
|
||||
await targetPage.locator('#username').fill('admin')
|
||||
await targetPage.locator('#password').fill('wrong-password')
|
||||
await targetPage.getByRole('button', {name: '登录', exact: true}).click()
|
||||
await targetPage.getByRole('button', {name: 'AES固定Key', exact: true}).click()
|
||||
await targetPage.waitForTimeout(500)
|
||||
if (browserRequestCount !== 1) {
|
||||
throw new Error(`Initial AES recording expected one real request, received ${browserRequestCount}`)
|
||||
}
|
||||
|
||||
const snapshot = await extensionRequest(
|
||||
controlPage,
|
||||
'recording.get',
|
||||
{tabId, frameId: 0, limit: 120},
|
||||
)
|
||||
const candidate = snapshot.profileCandidates?.find((item) => (
|
||||
item.status === 'ready'
|
||||
&& new URL(item.request?.url, targetURL).pathname === '/encrypt/aes.php'
|
||||
&& item.source?.callHandleId
|
||||
))
|
||||
if (!candidate) {
|
||||
throw new Error(`Single-call AES candidate was not ready after one recording: ${JSON.stringify(snapshot)}`)
|
||||
}
|
||||
|
||||
const callable = await extensionRequest(controlPage, 'callable.create', {
|
||||
tabId,
|
||||
frameId: 0,
|
||||
source: 'recording',
|
||||
callHandleId: candidate.source.callHandleId,
|
||||
name: 'CryptoJS AES recorded call',
|
||||
})
|
||||
if (callable.kind !== 'recorded-call') {
|
||||
throw new Error(`AES callable was not retained from the recording: ${JSON.stringify(callable)}`)
|
||||
}
|
||||
|
||||
const plainPacket = {
|
||||
method: 'POST',
|
||||
url: new URL('/encrypt/aes.php', targetURL).toString(),
|
||||
headers: [{name: 'Content-Type', value: 'application/json'}],
|
||||
bodyBase64: Buffer.from(JSON.stringify(plaintext)).toString('base64'),
|
||||
}
|
||||
const proposal = await extensionRequest(controlPage, 'analysis.profile.propose', {
|
||||
tabId,
|
||||
frameId: 0,
|
||||
candidateId: candidate.id,
|
||||
callableId: callable.id,
|
||||
inputPaths: ['body'],
|
||||
name: 'AES deterministic contract',
|
||||
})
|
||||
if (proposal?.proposal?.compiler !== 'browser-transform-guided-v1') {
|
||||
throw new Error(`AES Profile was not deterministically compiled: ${JSON.stringify(proposal)}`)
|
||||
}
|
||||
|
||||
const validation = await extensionRequest(controlPage, 'analysis.profile.validate', {
|
||||
tabId,
|
||||
frameId: 0,
|
||||
candidateId: candidate.id,
|
||||
callableId: callable.id,
|
||||
inputPaths: ['body'],
|
||||
name: 'AES deterministic contract',
|
||||
packet: plainPacket,
|
||||
comparisonMode: 'structure',
|
||||
})
|
||||
if (!validation?.valid || !validation?.saveEligible
|
||||
|| validation.proofLevel !== 'structure'
|
||||
|| validation.validationDraft?.contractVersion !== 1) {
|
||||
throw new Error(`AES Profile validation failed: ${JSON.stringify(validation)}`)
|
||||
}
|
||||
if (browserRequestCount !== 1) {
|
||||
throw new Error(`AES Profile validation leaked a real browser request; observed ${browserRequestCount}`)
|
||||
}
|
||||
|
||||
const validationDraft = await extensionRequest(
|
||||
controlPage,
|
||||
'analysis.profile.validation.latest',
|
||||
{tabId, frameId: 0},
|
||||
)
|
||||
if (!validationDraft || validationDraft.id !== validation.validationDraft.id
|
||||
|| validationDraft.contractVersion !== 1 || validationDraft.profile?.id) {
|
||||
throw new Error(`AES Yakit handoff draft is invalid: ${JSON.stringify(validationDraft)}`)
|
||||
}
|
||||
const savedProfile = await extensionRequest(
|
||||
controlPage,
|
||||
'transform.profile.save',
|
||||
validationDraft.profile,
|
||||
)
|
||||
const execution = await extensionRequest(controlPage, 'transform.execute', {
|
||||
profileId: savedProfile.id,
|
||||
direction: 'request',
|
||||
packet: plainPacket,
|
||||
})
|
||||
const wireBody = Buffer.from(execution.bodyBase64, 'base64').toString('utf8')
|
||||
const form = new URLSearchParams(wireBody)
|
||||
const encryptedData = form.get('encryptedData')
|
||||
if (!encryptedData || encryptedData.startsWith('{') || form.size !== 1) {
|
||||
throw new Error(`AES Profile produced an invalid or nested form envelope: ${wireBody}`)
|
||||
}
|
||||
if (browserRequestCount !== 1) {
|
||||
throw new Error(`Saved AES Profile leaked a real browser request; observed ${browserRequestCount}`)
|
||||
}
|
||||
|
||||
const response = await fetch(
|
||||
execution.url,
|
||||
transformedFetchOptions(execution, plainPacket.headers),
|
||||
)
|
||||
const result = await response.json()
|
||||
if (!result.success) throw new Error(`Target server rejected the AES Profile output: ${JSON.stringify(result)}`)
|
||||
process.stdout.write(
|
||||
'AES Agent contract verified: one recording produced a callable, deterministic Profile, Yakit confirmation draft, and server-accepted wire request.\n',
|
||||
)
|
||||
} finally {
|
||||
await harness?.close()
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
import {
|
||||
extensionRequest,
|
||||
launchBrowserAgentContractHarness,
|
||||
transformedFetchOptions,
|
||||
waitFor,
|
||||
} from './browser-agent-contract-harness.mjs'
|
||||
|
||||
const targetURL = process.env.AESRSA_TARGET || 'http://127.0.0.1:82/'
|
||||
let harness
|
||||
|
||||
try {
|
||||
harness = await launchBrowserAgentContractHarness({
|
||||
profilePrefix: 'yakit-aesrsa-',
|
||||
targetURL,
|
||||
})
|
||||
const {controlPage, tabId, targetPage} = harness
|
||||
let browserRequestCount = 0
|
||||
targetPage.on('request', (request) => {
|
||||
if (new URL(request.url()).pathname === '/encrypt/aesrsa.php') browserRequestCount += 1
|
||||
})
|
||||
|
||||
await extensionRequest(controlPage, 'recording.start', {
|
||||
tabId, frameId: 0, captureValues: true, maxEntries: 120, maxValueBytes: 8_192,
|
||||
})
|
||||
await targetPage.locator('#username').fill('admin')
|
||||
await targetPage.locator('#password').fill('wrong-password')
|
||||
await targetPage.getByRole('button', { name: '登录', exact: true }).click()
|
||||
await targetPage.getByRole('button', { name: 'AES+Rsa加密', exact: true }).click()
|
||||
await targetPage.waitForTimeout(500)
|
||||
if (browserRequestCount !== 1) throw new Error(`Initial recording expected one real request, received ${browserRequestCount}`)
|
||||
|
||||
const snapshot = await extensionRequest(controlPage, 'recording.get', { tabId, frameId: 0, limit: 120 })
|
||||
const candidate = snapshot.profileCandidates?.find((item) => (
|
||||
item.status === 'capture-required'
|
||||
&& item.sources?.length === 3
|
||||
&& new URL(item.request?.url, targetURL).pathname === '/encrypt/aesrsa.php'
|
||||
))
|
||||
if (!candidate) throw new Error(`AES+RSA request-level candidate was not inferred: ${JSON.stringify(snapshot)}`)
|
||||
const matcherEvent = snapshot.events?.find((event) => event.id === candidate.capturePlan?.matcherEventId)
|
||||
if (!matcherEvent?.crypto?.adapterId || !matcherEvent.wrapperHandleId) {
|
||||
throw new Error(`AES+RSA candidate has no deep-capture matcher: ${JSON.stringify(candidate)}`)
|
||||
}
|
||||
await extensionRequest(controlPage, 'deep.capture.start', {
|
||||
tabId,
|
||||
frameId: 0,
|
||||
matcher: {
|
||||
kind: 'crypto',
|
||||
adapterId: matcherEvent.crypto.adapterId,
|
||||
operation: matcherEvent.crypto.operation,
|
||||
wrapperHandleId: matcherEvent.wrapperHandleId,
|
||||
scriptUrl: matcherEvent.scriptUrl,
|
||||
frameHints: candidate.capturePlan.frameHints,
|
||||
},
|
||||
})
|
||||
|
||||
await targetPage.locator('#username').fill('admin')
|
||||
await targetPage.locator('#password').fill('wrong-password')
|
||||
await targetPage.getByRole('button', { name: '登录', exact: true }).click()
|
||||
let replayClickFailure
|
||||
const replayClick = targetPage.getByRole('button', { name: 'AES+Rsa加密', exact: true })
|
||||
.click({ noWaitAfter: true, timeout: 20_000 })
|
||||
.catch((reason) => { replayClickFailure = reason })
|
||||
const paused = await waitFor(controlPage, 'deep.capture.status', { tabId, frameId: 0 }, (value) => (
|
||||
value?.state === 'paused' && value.pause?.collecting !== true
|
||||
), 20_000)
|
||||
const automatic = paused.pause?.automaticCapture
|
||||
const frame = paused.pause?.frames?.find((item) => item.id === automatic?.frameId)
|
||||
if (automatic?.state !== 'ready' || automatic.strategy !== 'request-transaction'
|
||||
|| frame?.functionName !== 'sendDataAesRsa') {
|
||||
throw new Error(`Deep capture did not select sendDataAesRsa as a request transaction: ${JSON.stringify(paused)}`)
|
||||
}
|
||||
|
||||
const callable = await extensionRequest(controlPage, 'callable.create', {
|
||||
tabId,
|
||||
frameId: 0,
|
||||
source: 'deep-capture',
|
||||
strategy: 'request-transaction',
|
||||
callFrameId: frame.id,
|
||||
name: 'sendDataAesRsa 请求事务',
|
||||
candidateId: candidate.id,
|
||||
})
|
||||
if (callable.kind !== 'request-transaction' || callable.inputSlots?.[0]?.name !== 'body') {
|
||||
throw new Error(`Captured callable is not a request transaction: ${JSON.stringify(callable)}`)
|
||||
}
|
||||
await replayClick
|
||||
if (replayClickFailure) throw replayClickFailure
|
||||
await targetPage.waitForTimeout(300)
|
||||
if (browserRequestCount !== 1) {
|
||||
throw new Error(`Deep-capture replay leaked a real request; observed ${browserRequestCount}`)
|
||||
}
|
||||
|
||||
const plaintext = { username: 'admin', password: '123456' }
|
||||
let execution
|
||||
try {
|
||||
execution = await extensionRequest(controlPage, 'callable.execute', {
|
||||
tabId,
|
||||
frameId: 0,
|
||||
callableId: callable.id,
|
||||
args: [plaintext],
|
||||
})
|
||||
} catch (reason) {
|
||||
const diagnostics = await controlPage.evaluate(async ({ targetTabId, callableId }) => {
|
||||
const tab = await chrome.tabs.get(targetTabId).catch(() => undefined)
|
||||
const [injection] = await chrome.scripting.executeScript({
|
||||
target: { tabId: targetTabId, frameIds: [0] },
|
||||
world: 'MAIN',
|
||||
func: async (registryKey, protocolVersion, requestedCallableId) => {
|
||||
const controller = globalThis[registryKey]
|
||||
let directExecution
|
||||
try {
|
||||
directExecution = {
|
||||
ok: true,
|
||||
value: await controller?.command('callable.execute', {
|
||||
callableId: requestedCallableId,
|
||||
args: [{ username: 'admin', password: '123456' }],
|
||||
}),
|
||||
}
|
||||
} catch (error) {
|
||||
directExecution = {
|
||||
ok: false,
|
||||
error: error instanceof Error ? `${error.name}: ${error.message}\n${error.stack || ''}` : String(error),
|
||||
}
|
||||
}
|
||||
return {
|
||||
href: location.href,
|
||||
controllerVersion: controller?.version,
|
||||
expectedVersion: protocolVersion,
|
||||
callables: typeof controller?.command === 'function' ? controller.command('callable.list', {}) : [],
|
||||
directExecution,
|
||||
}
|
||||
},
|
||||
args: ['__YAKIT_PAGE_RECORDER_V8__', 8, callableId],
|
||||
}).catch(() => [])
|
||||
return { tabUrl: tab?.url, page: injection?.result }
|
||||
}, { targetTabId: tabId, callableId: callable.id })
|
||||
const selectedFrame = {
|
||||
functionName: frame.functionName,
|
||||
functionInspection: frame.functionInspection,
|
||||
scopes: frame.scopes,
|
||||
}
|
||||
throw new Error(`Callable execution failed: ${reason instanceof Error ? reason.message : String(reason)}; browserRequests=${browserRequestCount}; frame=${JSON.stringify(selectedFrame)}; diagnostics=${JSON.stringify(diagnostics)}`)
|
||||
}
|
||||
const envelope = execution.value
|
||||
for (const field of ['encryptedData', 'encryptedKey', 'encryptedIv']) {
|
||||
if (typeof envelope?.[field] !== 'string' || !envelope[field]) {
|
||||
throw new Error(`Transaction output is missing ${field}: ${JSON.stringify(execution)}`)
|
||||
}
|
||||
}
|
||||
if (browserRequestCount !== 1) {
|
||||
throw new Error(`Transaction execution leaked a real browser request; observed ${browserRequestCount}`)
|
||||
}
|
||||
try {
|
||||
await extensionRequest(controlPage, 'callable.execute', {
|
||||
tabId,
|
||||
frameId: 0,
|
||||
callableId: callable.id,
|
||||
args: [plaintext],
|
||||
})
|
||||
} catch (reason) {
|
||||
throw new Error(
|
||||
`Captured request transaction is not repeatable: ${reason instanceof Error ? reason.message : String(reason)}`,
|
||||
)
|
||||
}
|
||||
|
||||
const plainPacket = {
|
||||
method: 'POST',
|
||||
url: new URL('/encrypt/aesrsa.php', targetURL).toString(),
|
||||
headers: [{ name: 'Content-Type', value: 'application/json' }],
|
||||
bodyBase64: Buffer.from(JSON.stringify(plaintext)).toString('base64'),
|
||||
}
|
||||
const proposal = await extensionRequest(controlPage, 'analysis.profile.propose', {
|
||||
tabId,
|
||||
frameId: 0,
|
||||
candidateId: candidate.id,
|
||||
callableId: callable.id,
|
||||
inputPaths: ['body'],
|
||||
name: 'AES+RSA deterministic contract',
|
||||
})
|
||||
if (proposal?.proposal?.compiler !== 'browser-transform-guided-v1'
|
||||
|| proposal?.profile?.request?.enabled !== true) {
|
||||
throw new Error(`Deterministic profile proposal was not compiled: ${JSON.stringify(proposal)}`)
|
||||
}
|
||||
|
||||
let validation
|
||||
try {
|
||||
validation = await extensionRequest(controlPage, 'analysis.profile.validate', {
|
||||
tabId,
|
||||
frameId: 0,
|
||||
candidateId: candidate.id,
|
||||
callableId: callable.id,
|
||||
inputPaths: ['body'],
|
||||
name: 'AES+RSA deterministic contract',
|
||||
packet: plainPacket,
|
||||
comparisonMode: 'structure',
|
||||
})
|
||||
} catch (reason) {
|
||||
throw new Error(
|
||||
`Deterministic profile validation could not execute: ${reason instanceof Error ? reason.message : String(reason)}; `
|
||||
+ `packet=${JSON.stringify(plainPacket)}; profile=${JSON.stringify(proposal.profile)}`,
|
||||
)
|
||||
}
|
||||
if (!validation?.valid || !validation?.saveEligible
|
||||
|| validation.proofLevel !== 'structure'
|
||||
|| validation.validationDraft?.contractVersion !== 1
|
||||
|| !validation.validationDraft?.id) {
|
||||
throw new Error(`Deterministic profile validation failed: ${JSON.stringify(validation)}`)
|
||||
}
|
||||
if (browserRequestCount !== 1) {
|
||||
throw new Error(`Profile validation leaked a real browser request; observed ${browserRequestCount}`)
|
||||
}
|
||||
|
||||
const validationDraft = await extensionRequest(
|
||||
controlPage,
|
||||
'analysis.profile.validation.latest',
|
||||
{ tabId, frameId: 0 },
|
||||
)
|
||||
if (!validationDraft || validationDraft.contractVersion !== 1
|
||||
|| validationDraft.id !== validation.validationDraft.id
|
||||
|| validationDraft.profile?.id) {
|
||||
throw new Error(`Yakit handoff draft is missing or already persisted: ${JSON.stringify(validationDraft)}`)
|
||||
}
|
||||
|
||||
const savedProfile = await extensionRequest(
|
||||
controlPage,
|
||||
'transform.profile.save',
|
||||
validationDraft.profile,
|
||||
)
|
||||
const profiles = await extensionRequest(controlPage, 'transform.profile.list', { tabId, frameId: 0 })
|
||||
if (!savedProfile?.id || !profiles.some((profile) => profile.id === savedProfile.id)) {
|
||||
throw new Error(`Confirmed profile was not persisted: ${JSON.stringify({ savedProfile, profiles })}`)
|
||||
}
|
||||
|
||||
const profileExecution = await extensionRequest(controlPage, 'transform.execute', {
|
||||
profileId: savedProfile.id,
|
||||
direction: 'request',
|
||||
packet: plainPacket,
|
||||
})
|
||||
const transformedEnvelope = JSON.parse(
|
||||
Buffer.from(profileExecution.bodyBase64, 'base64').toString('utf8'),
|
||||
)
|
||||
for (const field of ['encryptedData', 'encryptedKey', 'encryptedIv']) {
|
||||
if (typeof transformedEnvelope?.[field] !== 'string' || !transformedEnvelope[field]) {
|
||||
throw new Error(`Saved profile output is missing ${field}: ${JSON.stringify(profileExecution)}`)
|
||||
}
|
||||
}
|
||||
if (browserRequestCount !== 1) {
|
||||
throw new Error(`Saved profile execution leaked a real browser request; observed ${browserRequestCount}`)
|
||||
}
|
||||
|
||||
const response = await fetch(
|
||||
profileExecution.url,
|
||||
transformedFetchOptions(profileExecution, plainPacket.headers),
|
||||
)
|
||||
const result = await response.json()
|
||||
if (!result.success) throw new Error(`Target server rejected the saved Profile output: ${JSON.stringify(result)}`)
|
||||
|
||||
await targetPage.reload()
|
||||
const staleProfile = await waitFor(
|
||||
controlPage,
|
||||
'transform.profile.list',
|
||||
{ tabId, frameId: 0 },
|
||||
(items) => items?.find((item) => item.id === savedProfile.id)?.recovery?.state === 'stale',
|
||||
10_000,
|
||||
).then((items) => items.find((item) => item.id === savedProfile.id))
|
||||
if (staleProfile.enabled || staleProfile.recovery?.capture?.automatic !== true) {
|
||||
throw new Error(`Reloaded Profile did not fail closed with an automatic Recovery Plan: ${JSON.stringify(staleProfile)}`)
|
||||
}
|
||||
|
||||
await extensionRequest(controlPage, 'transform.recovery.start', { id: savedProfile.id })
|
||||
await targetPage.locator('#username').fill('admin')
|
||||
await targetPage.locator('#password').fill('wrong-password')
|
||||
await targetPage.getByRole('button', { name: '登录', exact: true }).click()
|
||||
let recoveryClickFailure
|
||||
const recoveryClick = targetPage.getByRole('button', { name: 'AES+Rsa加密', exact: true })
|
||||
.click({ noWaitAfter: true, timeout: 20_000 })
|
||||
.catch((reason) => { recoveryClickFailure = reason })
|
||||
const recoveryPause = await waitFor(controlPage, 'deep.capture.status', {
|
||||
tabId, frameId: 0,
|
||||
}, (value) => value?.state === 'paused' && value.pause?.collecting !== true, 20_000)
|
||||
const recoveryAutomatic = recoveryPause.pause?.automaticCapture
|
||||
if (recoveryAutomatic?.state !== 'ready' || !recoveryAutomatic.frameId
|
||||
|| recoveryAutomatic.strategy !== 'request-transaction') {
|
||||
throw new Error(`Recovery Plan did not locate the request transaction: ${JSON.stringify(recoveryPause)}`)
|
||||
}
|
||||
const recovery = await extensionRequest(controlPage, 'transform.recovery.capture', {
|
||||
id: savedProfile.id,
|
||||
...recoveryPause.target,
|
||||
callFrameId: recoveryAutomatic.frameId,
|
||||
strategy: recoveryAutomatic.strategy,
|
||||
})
|
||||
await recoveryClick
|
||||
if (recoveryClickFailure) throw recoveryClickFailure
|
||||
if (recovery.state !== 'validation-required' || !recovery.pending?.callableId) {
|
||||
throw new Error(`Recovery capture was not staged for validation: ${JSON.stringify(recovery)}`)
|
||||
}
|
||||
const recoveryValidation = await extensionRequest(controlPage, 'transform.recovery.validate', {
|
||||
id: savedProfile.id,
|
||||
packet: plainPacket,
|
||||
})
|
||||
if (recoveryValidation.recovery?.state !== 'confirmation-required'
|
||||
|| !recoveryValidation.recovery.validation?.id) {
|
||||
throw new Error(`Recovered Profile did not require explicit confirmation: ${JSON.stringify(recoveryValidation)}`)
|
||||
}
|
||||
const recoveredProfile = await extensionRequest(controlPage, 'transform.recovery.confirm', {
|
||||
id: savedProfile.id,
|
||||
validationId: recoveryValidation.recovery.validation.id,
|
||||
})
|
||||
if (recoveredProfile.id !== savedProfile.id || recoveredProfile.recovery?.state !== 'ready'
|
||||
|| recoveredProfile.target.documentId === savedProfile.target.documentId) {
|
||||
throw new Error(`Recovery confirmation did not atomically replace the document binding: ${JSON.stringify(recoveredProfile)}`)
|
||||
}
|
||||
const recoveredExecution = await extensionRequest(controlPage, 'transform.execute', {
|
||||
profileId: recoveredProfile.id,
|
||||
direction: 'request',
|
||||
packet: plainPacket,
|
||||
})
|
||||
const recoveredResponse = await fetch(
|
||||
recoveredExecution.url,
|
||||
transformedFetchOptions(recoveredExecution, plainPacket.headers),
|
||||
)
|
||||
const recoveredResult = await recoveredResponse.json()
|
||||
if (!recoveredResult.success) {
|
||||
throw new Error(`Target server rejected the recovered Profile output: ${JSON.stringify(recoveredResult)}`)
|
||||
}
|
||||
process.stdout.write(
|
||||
'AES+RSA Agent contract verified: evidence compiled, validated, saved, reloaded stale, recovered through one request-boundary capture, revalidated, explicitly confirmed, and accepted by the target server.\n',
|
||||
)
|
||||
} finally {
|
||||
await harness?.close()
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
import {
|
||||
extensionRequest,
|
||||
launchBrowserAgentContractHarness,
|
||||
transformedFetchOptions,
|
||||
waitFor,
|
||||
} from './browser-agent-contract-harness.mjs'
|
||||
|
||||
const targetURL = process.env.AESSERVER_TARGET || 'http://127.0.0.1:82/'
|
||||
const keyPath = '/encrypt/server_generate_key.php'
|
||||
const requestPath = '/encrypt/aesserver.php'
|
||||
const plaintext = {username: 'admin', password: '123456'}
|
||||
let harness
|
||||
|
||||
function pathOf(url) {
|
||||
return new URL(url, targetURL).pathname
|
||||
}
|
||||
|
||||
function snapshotSummary(snapshot) {
|
||||
return {
|
||||
events: snapshot.events?.map((event) => ({
|
||||
sequence: event.sequence,
|
||||
kind: event.kind,
|
||||
operation: event.operation,
|
||||
url: event.url ? pathOf(event.url) : undefined,
|
||||
})),
|
||||
candidates: snapshot.profileCandidates?.map((candidate) => ({
|
||||
status: candidate.status,
|
||||
request: pathOf(candidate.request?.url || ''),
|
||||
prerequisites: candidate.capturePlan?.transaction?.prerequisites?.map((step) => pathOf(step.url)),
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
function dependencySummary(snapshot, candidate) {
|
||||
const eventIds = new Set(candidate.evidence?.flatMap((item) => item.eventIds || []))
|
||||
return {
|
||||
evidence: candidate.evidence?.filter((item) => item.kind === 'response-boundary'),
|
||||
events: snapshot.events?.filter((event) => eventIds.has(event.id)).map((event) => ({
|
||||
id: event.id,
|
||||
sequence: event.sequence,
|
||||
kind: event.kind,
|
||||
operation: event.operation,
|
||||
inputs: event.inputs?.map((item) => item.path),
|
||||
outputs: event.outputs?.map((item) => item.path),
|
||||
})),
|
||||
links: snapshot.links?.filter((link) => eventIds.has(link.fromEventId) || eventIds.has(link.toEventId))
|
||||
.map((link) => ({kind: link.kind, fromPath: link.fromPath, toPath: link.toPath})),
|
||||
}
|
||||
}
|
||||
|
||||
async function performLogin(targetPage, password = 'wrong-password') {
|
||||
await targetPage.locator('#username').fill('admin')
|
||||
await targetPage.locator('#password').fill(password)
|
||||
await targetPage.getByRole('button', {name: '登录', exact: true}).click()
|
||||
return targetPage.getByRole('button', {name: 'AES服务端获取Key', exact: true})
|
||||
}
|
||||
|
||||
try {
|
||||
harness = await launchBrowserAgentContractHarness({
|
||||
profilePrefix: 'yakit-aesserver-',
|
||||
targetURL,
|
||||
})
|
||||
const {controlPage, tabId, targetPage} = harness
|
||||
const observed = {key: 0, terminal: 0}
|
||||
targetPage.on('request', (request) => {
|
||||
const path = pathOf(request.url())
|
||||
if (path === keyPath) observed.key += 1
|
||||
if (path === requestPath) observed.terminal += 1
|
||||
})
|
||||
|
||||
await extensionRequest(controlPage, 'recording.start', {
|
||||
tabId,
|
||||
frameId: 0,
|
||||
captureValues: true,
|
||||
maxEntries: 160,
|
||||
maxValueBytes: 8_192,
|
||||
})
|
||||
await (await performLogin(targetPage)).click()
|
||||
await targetPage.waitForTimeout(600)
|
||||
if (observed.key !== 1 || observed.terminal !== 1) {
|
||||
throw new Error(`Initial operation did not produce the expected two-request flow: ${JSON.stringify(observed)}`)
|
||||
}
|
||||
|
||||
const snapshot = await extensionRequest(
|
||||
controlPage,
|
||||
'recording.get',
|
||||
{tabId, frameId: 0, limit: 160},
|
||||
)
|
||||
const candidate = snapshot.profileCandidates?.find((item) => (
|
||||
item.status === 'capture-required'
|
||||
&& pathOf(item.request?.url || '') === requestPath
|
||||
&& item.capturePlan?.transaction?.prerequisites?.some((step) => pathOf(step.url) === keyPath)
|
||||
))
|
||||
if (!candidate) {
|
||||
throw new Error(`Recording did not infer the online key dependency: ${JSON.stringify(snapshotSummary(snapshot))}`)
|
||||
}
|
||||
const transaction = candidate.capturePlan.transaction
|
||||
if (transaction.version !== 2
|
||||
|| transaction.prerequisites.length !== 1
|
||||
|| transaction.prerequisites[0].boundary !== 'fetch'
|
||||
|| transaction.prerequisites[0].response.bodyFormat !== 'json'
|
||||
|| !transaction.prerequisites[0].response.requiredPaths.includes('body.aes_key')
|
||||
|| !transaction.prerequisites[0].response.requiredPaths.includes('body.aes_iv')
|
||||
|| transaction.request.boundary !== 'fetch'
|
||||
|| pathOf(transaction.request.url) !== requestPath) {
|
||||
throw new Error(`Inferred request transaction is not evidence-complete: ${JSON.stringify({
|
||||
transaction,
|
||||
dependency: dependencySummary(snapshot, candidate),
|
||||
})}`)
|
||||
}
|
||||
|
||||
const matcherEvent = snapshot.events?.find((event) => event.id === candidate.capturePlan.matcherEventId)
|
||||
if (!matcherEvent?.crypto?.adapterId || !matcherEvent.wrapperHandleId) {
|
||||
throw new Error(`Online-key candidate has no deep-capture matcher: ${JSON.stringify(candidate)}`)
|
||||
}
|
||||
await extensionRequest(controlPage, 'deep.capture.start', {
|
||||
tabId,
|
||||
frameId: 0,
|
||||
matcher: {
|
||||
kind: 'crypto',
|
||||
adapterId: matcherEvent.crypto.adapterId,
|
||||
operation: matcherEvent.crypto.operation,
|
||||
wrapperHandleId: matcherEvent.wrapperHandleId,
|
||||
scriptUrl: matcherEvent.scriptUrl,
|
||||
frameHints: candidate.capturePlan.frameHints,
|
||||
},
|
||||
})
|
||||
|
||||
const replayButton = await performLogin(targetPage)
|
||||
let replayFailure
|
||||
const replay = replayButton.click({noWaitAfter: true, timeout: 20_000})
|
||||
.catch((reason) => { replayFailure = reason })
|
||||
const paused = await waitFor(
|
||||
controlPage,
|
||||
'deep.capture.status',
|
||||
{tabId, frameId: 0},
|
||||
(value) => value?.state === 'paused' && value.pause?.collecting !== true,
|
||||
20_000,
|
||||
)
|
||||
const automatic = paused.pause?.automaticCapture
|
||||
const frame = paused.pause?.frames?.find((item) => item.id === automatic?.frameId)
|
||||
if (automatic?.state !== 'ready'
|
||||
|| automatic.strategy !== 'request-transaction'
|
||||
|| frame?.functionName !== 'fetchAndSendDataAes') {
|
||||
throw new Error(`Deep capture selected an invalid strategy: ${JSON.stringify({automatic, functionName: frame?.functionName})}`)
|
||||
}
|
||||
const callable = await extensionRequest(controlPage, 'callable.create', {
|
||||
tabId,
|
||||
frameId: 0,
|
||||
source: 'deep-capture',
|
||||
strategy: 'request-transaction',
|
||||
callFrameId: frame.id,
|
||||
name: '在线取钥请求事务',
|
||||
candidateId: candidate.id,
|
||||
})
|
||||
await replay
|
||||
if (replayFailure) throw replayFailure
|
||||
await targetPage.waitForTimeout(300)
|
||||
if (observed.key !== 2 || observed.terminal !== 1) {
|
||||
throw new Error(`Deep capture did not preserve the prerequisite/terminal boundary: ${JSON.stringify(observed)}`)
|
||||
}
|
||||
|
||||
const beforeCallable = {...observed}
|
||||
const callableExecution = await extensionRequest(controlPage, 'callable.execute', {
|
||||
tabId,
|
||||
frameId: 0,
|
||||
callableId: callable.id,
|
||||
args: [plaintext],
|
||||
})
|
||||
if (typeof callableExecution.value?.encryptedData !== 'string') {
|
||||
throw new Error(`Request transaction did not return the terminal envelope: ${JSON.stringify(callableExecution)}`)
|
||||
}
|
||||
if (observed.key !== beforeCallable.key + 1 || observed.terminal !== beforeCallable.terminal) {
|
||||
throw new Error(`Callable execution leaked or skipped a request: ${JSON.stringify({beforeCallable, observed})}`)
|
||||
}
|
||||
|
||||
const plainPacket = {
|
||||
method: 'POST',
|
||||
url: new URL(requestPath, targetURL).toString(),
|
||||
headers: [{name: 'Content-Type', value: 'application/json'}],
|
||||
bodyBase64: Buffer.from(JSON.stringify(plaintext)).toString('base64'),
|
||||
}
|
||||
const validation = await extensionRequest(controlPage, 'analysis.profile.validate', {
|
||||
tabId,
|
||||
frameId: 0,
|
||||
candidateId: candidate.id,
|
||||
callableId: callable.id,
|
||||
inputPaths: ['body'],
|
||||
name: '在线取钥明文网关',
|
||||
packet: plainPacket,
|
||||
comparisonMode: 'structure',
|
||||
})
|
||||
if (!validation?.valid || !validation?.saveEligible || !validation.validationDraft?.id) {
|
||||
throw new Error(`Online-key Profile validation failed: ${JSON.stringify({
|
||||
valid: validation?.valid,
|
||||
saveEligible: validation?.saveEligible,
|
||||
proofLevel: validation?.proofLevel,
|
||||
})}`)
|
||||
}
|
||||
const validationDraft = await extensionRequest(
|
||||
controlPage,
|
||||
'analysis.profile.validation.latest',
|
||||
{tabId, frameId: 0},
|
||||
)
|
||||
if (!validationDraft?.profile || validationDraft.id !== validation.validationDraft.id) {
|
||||
throw new Error('Validated online-key Profile draft was not available for confirmation')
|
||||
}
|
||||
const savedProfile = await extensionRequest(
|
||||
controlPage,
|
||||
'transform.profile.save',
|
||||
validationDraft.profile,
|
||||
)
|
||||
if (
|
||||
savedProfile.requestTransaction?.callableId !== callable.id
|
||||
|| savedProfile.requestTransaction?.transaction?.version !== 2
|
||||
) {
|
||||
throw new Error('Saved Profile did not retain its trusted request-transaction binding')
|
||||
}
|
||||
|
||||
const beforeProfile = {...observed}
|
||||
const execution = await extensionRequest(controlPage, 'transform.execute', {
|
||||
profileId: savedProfile.id,
|
||||
direction: 'request',
|
||||
packet: plainPacket,
|
||||
})
|
||||
if (observed.key !== beforeProfile.key + 1 || observed.terminal !== beforeProfile.terminal) {
|
||||
throw new Error(`Saved Profile leaked or skipped a request: ${JSON.stringify({beforeProfile, observed})}`)
|
||||
}
|
||||
const sessionHeader = execution.setHeaders?.find((header) => header.name.toLowerCase() === 'cookie')
|
||||
if (!sessionHeader?.value.includes('PHPSESSID=')) {
|
||||
throw new Error(`Saved Profile did not bind the browser session to the outgoing packet: ${JSON.stringify(execution)}`)
|
||||
}
|
||||
const wireBody = JSON.parse(Buffer.from(execution.bodyBase64, 'base64').toString('utf8'))
|
||||
if (typeof wireBody.encryptedData !== 'string' || Object.keys(wireBody).length !== 1) {
|
||||
throw new Error(`Saved Profile produced an invalid terminal envelope: ${JSON.stringify(wireBody)}`)
|
||||
}
|
||||
|
||||
const response = await fetch(
|
||||
execution.url,
|
||||
transformedFetchOptions(execution, plainPacket.headers),
|
||||
)
|
||||
const result = await response.json()
|
||||
if (!result.success) {
|
||||
throw new Error(`Target server rejected the session-bound Profile output: ${JSON.stringify(result)}`)
|
||||
}
|
||||
process.stdout.write(
|
||||
'Online-key transaction verified: evidence inferred one bounded prerequisite, the browser sent no terminal request during replay, the saved Profile exported its browser session, and the target server accepted the final packet.\n',
|
||||
)
|
||||
} finally {
|
||||
await harness?.close()
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import {
|
||||
extensionRequest,
|
||||
launchBrowserAgentContractHarness,
|
||||
transformedFetchOptions,
|
||||
waitFor,
|
||||
} from './browser-agent-contract-harness.mjs'
|
||||
|
||||
const targetURL = process.env.DES_TARGET || 'http://127.0.0.1:82/'
|
||||
const requestPath = '/encrypt/des.php'
|
||||
const plaintext = {username: 'admin', password: '123456'}
|
||||
let harness
|
||||
|
||||
function pathOf(url) {
|
||||
return new URL(url, targetURL).pathname
|
||||
}
|
||||
|
||||
async function performLogin(targetPage, password = 'wrong-password') {
|
||||
await targetPage.locator('#username').fill('admin')
|
||||
await targetPage.locator('#password').fill(password)
|
||||
await targetPage.getByRole('button', {name: '登录', exact: true}).click()
|
||||
return targetPage.getByRole('button', {name: 'Des规律Key', exact: true})
|
||||
}
|
||||
|
||||
try {
|
||||
harness = await launchBrowserAgentContractHarness({
|
||||
profilePrefix: 'yakit-des-',
|
||||
targetURL,
|
||||
})
|
||||
const {controlPage, tabId, targetPage} = harness
|
||||
let browserRequestCount = 0
|
||||
targetPage.on('request', (request) => {
|
||||
if (pathOf(request.url()) === requestPath) browserRequestCount += 1
|
||||
})
|
||||
|
||||
await extensionRequest(controlPage, 'recording.start', {
|
||||
tabId, frameId: 0, captureValues: true, maxEntries: 120, maxValueBytes: 8_192,
|
||||
})
|
||||
await (await performLogin(targetPage)).click()
|
||||
await targetPage.waitForTimeout(500)
|
||||
if (browserRequestCount !== 1) throw new Error(`Initial DES recording expected one request, received ${browserRequestCount}`)
|
||||
|
||||
const snapshot = await extensionRequest(controlPage, 'recording.get', {tabId, frameId: 0, limit: 120})
|
||||
const candidate = snapshot.profileCandidates?.find((item) => pathOf(item.request?.url || '') === requestPath)
|
||||
if (!candidate || candidate.status !== 'capture-required') {
|
||||
throw new Error(`Structured DES output was not routed through business-envelope capture: ${JSON.stringify(candidate)}`)
|
||||
}
|
||||
const matcherEvent = snapshot.events?.find((event) => event.id === candidate.capturePlan?.matcherEventId)
|
||||
if (matcherEvent?.crypto?.family !== 'symmetric'
|
||||
|| !matcherEvent.crypto.operation.toLowerCase().includes('des')
|
||||
|| !matcherEvent.wrapperHandleId) {
|
||||
throw new Error(`DES candidate has no reusable crypto matcher: ${JSON.stringify(matcherEvent)}`)
|
||||
}
|
||||
|
||||
await extensionRequest(controlPage, 'deep.capture.start', {
|
||||
tabId,
|
||||
frameId: 0,
|
||||
matcher: {
|
||||
kind: 'crypto',
|
||||
adapterId: matcherEvent.crypto.adapterId,
|
||||
operation: matcherEvent.crypto.operation,
|
||||
wrapperHandleId: matcherEvent.wrapperHandleId,
|
||||
scriptUrl: matcherEvent.scriptUrl,
|
||||
frameHints: candidate.capturePlan.frameHints,
|
||||
},
|
||||
})
|
||||
const replayButton = await performLogin(targetPage)
|
||||
let replayFailure
|
||||
const replay = replayButton.click({noWaitAfter: true, timeout: 20_000})
|
||||
.catch((reason) => { replayFailure = reason })
|
||||
const paused = await waitFor(controlPage, 'deep.capture.status', {tabId, frameId: 0}, (value) => (
|
||||
value?.state === 'paused' && value.pause?.collecting !== true
|
||||
), 20_000)
|
||||
const automatic = paused.pause?.automaticCapture
|
||||
const frame = paused.pause?.frames?.find((item) => item.id === automatic?.frameId)
|
||||
if (automatic?.state !== 'ready' || automatic.strategy !== 'request-transaction'
|
||||
|| frame?.functionName !== 'encryptAndSendDataDES') {
|
||||
throw new Error(`DES deep capture did not select its business request envelope: ${JSON.stringify({automatic, frame})}`)
|
||||
}
|
||||
const callable = await extensionRequest(controlPage, 'callable.create', {
|
||||
tabId,
|
||||
frameId: 0,
|
||||
source: 'deep-capture',
|
||||
strategy: 'request-transaction',
|
||||
callFrameId: frame.id,
|
||||
name: 'DES 请求事务',
|
||||
candidateId: candidate.id,
|
||||
})
|
||||
await replay
|
||||
if (replayFailure) throw replayFailure
|
||||
await targetPage.waitForTimeout(250)
|
||||
if (browserRequestCount !== 1) throw new Error(`DES capture leaked a terminal request; observed ${browserRequestCount}`)
|
||||
|
||||
const callableExecution = await extensionRequest(controlPage, 'callable.execute', {
|
||||
tabId, frameId: 0, callableId: callable.id, args: [plaintext],
|
||||
})
|
||||
if (callableExecution.value?.username !== plaintext.username
|
||||
|| !/^[a-f0-9]+$/i.test(callableExecution.value?.password || '')) {
|
||||
throw new Error(`DES request transaction did not preserve the Hex envelope: ${JSON.stringify(callableExecution)}`)
|
||||
}
|
||||
|
||||
const plainPacket = {
|
||||
method: 'POST',
|
||||
url: new URL(requestPath, targetURL).toString(),
|
||||
headers: [{name: 'Content-Type', value: 'application/json'}],
|
||||
bodyBase64: Buffer.from(JSON.stringify(plaintext)).toString('base64'),
|
||||
}
|
||||
const validation = await extensionRequest(controlPage, 'analysis.profile.validate', {
|
||||
tabId,
|
||||
frameId: 0,
|
||||
candidateId: candidate.id,
|
||||
callableId: callable.id,
|
||||
inputPaths: ['body'],
|
||||
name: 'DES 明文网关',
|
||||
packet: plainPacket,
|
||||
comparisonMode: 'structure',
|
||||
})
|
||||
if (!validation?.valid || !validation?.saveEligible || !validation.validationDraft?.id) {
|
||||
throw new Error(`DES Profile validation failed: ${JSON.stringify(validation)}`)
|
||||
}
|
||||
const validationDraft = await extensionRequest(controlPage, 'analysis.profile.validation.latest', {tabId, frameId: 0})
|
||||
const savedProfile = await extensionRequest(controlPage, 'transform.profile.save', validationDraft.profile)
|
||||
const explanationText = JSON.stringify(savedProfile.explanation)
|
||||
if (!explanationText.includes('DES') || explanationText.includes(plaintext.password)) {
|
||||
throw new Error(`DES semantic explanation is missing or persisted plaintext: ${explanationText}`)
|
||||
}
|
||||
|
||||
const execution = await extensionRequest(controlPage, 'transform.execute', {
|
||||
profileId: savedProfile.id,
|
||||
direction: 'request',
|
||||
packet: plainPacket,
|
||||
})
|
||||
const wireBody = JSON.parse(Buffer.from(execution.bodyBase64, 'base64').toString('utf8'))
|
||||
if (wireBody.username !== plaintext.username || !/^[a-f0-9]+$/i.test(wireBody.password || '')) {
|
||||
throw new Error(`Saved DES Profile produced an invalid terminal body: ${JSON.stringify(wireBody)}`)
|
||||
}
|
||||
if (!execution.nodeTrace?.length || !execution.fieldChanges?.some((change) => change.path === 'body.password')) {
|
||||
throw new Error(`Saved DES Profile did not return an explainable runtime trace: ${JSON.stringify(execution)}`)
|
||||
}
|
||||
if (browserRequestCount !== 1) throw new Error(`DES Profile execution leaked a browser request; observed ${browserRequestCount}`)
|
||||
|
||||
const response = await fetch(execution.url, transformedFetchOptions(execution, plainPacket.headers))
|
||||
const result = await response.json()
|
||||
if (!result.success) throw new Error(`Target server rejected the saved DES Profile output: ${JSON.stringify(result)}`)
|
||||
process.stdout.write('DES transaction verified: the structured CipherParams result required business-envelope capture, replay preserved Hex serialization, runtime evidence stayed value-free, and the target accepted the final packet.\n')
|
||||
} finally {
|
||||
await harness?.close()
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
import { createServer } from 'node:http';
|
||||
import { createRequire } from 'node:module';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { chromium } from 'playwright-core';
|
||||
import { KEYUTIL, KJUR } from 'jsrsasign';
|
||||
import { compactDecrypt, jwtVerify } from 'jose';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const root = resolve(import.meta.dirname, '..');
|
||||
const recorderPath = resolve(root, '.output/chrome-mv3/page-recorder-main-world.js');
|
||||
const jsrsasignPath = resolve(dirname(require.resolve('jsrsasign')), 'jsrsasign-all-min.js');
|
||||
const joseIndexPath = fileURLToPath(import.meta.resolve('jose'));
|
||||
const joseRoot = dirname(joseIndexPath);
|
||||
const executablePath = process.env.CHROME_PATH || '/usr/bin/google-chrome';
|
||||
|
||||
function assert(condition, message) {
|
||||
if (!condition) throw new Error(message);
|
||||
}
|
||||
|
||||
function listen(server) {
|
||||
return new Promise((resolveListen, reject) => {
|
||||
server.once('error', reject);
|
||||
server.listen(0, '127.0.0.1', () => resolveListen(server.address()));
|
||||
});
|
||||
}
|
||||
|
||||
function close(server) {
|
||||
return new Promise((resolveClose) => server.close(() => resolveClose()));
|
||||
}
|
||||
|
||||
function readBody(request) {
|
||||
return new Promise((resolveBody, reject) => {
|
||||
const chunks = [];
|
||||
let bytes = 0;
|
||||
request.on('data', (chunk) => {
|
||||
bytes += chunk.length;
|
||||
if (bytes > 1024 * 1024) {
|
||||
reject(new Error('G4 browser fixture body exceeded 1 MiB'));
|
||||
request.destroy();
|
||||
return;
|
||||
}
|
||||
chunks.push(chunk);
|
||||
});
|
||||
request.on('end', () => resolveBody(Buffer.concat(chunks).toString('utf8')));
|
||||
request.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
let capturedRequest;
|
||||
const server = createServer(async (request, response) => {
|
||||
try {
|
||||
const url = new URL(request.url || '/', 'http://127.0.0.1');
|
||||
if (url.pathname === '/') {
|
||||
response.setHeader('Content-Type', 'text/html; charset=utf-8');
|
||||
response.end('<!doctype html><html><body><button id="run">Run G4 fixture</button><script src="/jsrsasign.js"></script><script type="module">import * as jose from "/jose/index.js"; window.jose = {...jose}; window.__g4Ready = true;</script></body></html>');
|
||||
return;
|
||||
}
|
||||
if (url.pathname === '/jsrsasign.js') {
|
||||
response.setHeader('Content-Type', 'text/javascript; charset=utf-8');
|
||||
response.end(await readFile(jsrsasignPath));
|
||||
return;
|
||||
}
|
||||
if (url.pathname.startsWith('/jose/')) {
|
||||
const relative = url.pathname.slice('/jose/'.length);
|
||||
const path = resolve(joseRoot, relative);
|
||||
assert(path.startsWith(`${joseRoot}/`) || path === joseRoot, 'Invalid jose module path');
|
||||
response.setHeader('Content-Type', 'text/javascript; charset=utf-8');
|
||||
response.end(await readFile(path));
|
||||
return;
|
||||
}
|
||||
if (url.pathname === '/g4-submit') {
|
||||
capturedRequest = {
|
||||
method: request.method,
|
||||
signature: String(request.headers['x-signature'] || ''),
|
||||
body: JSON.parse(await readBody(request)),
|
||||
};
|
||||
response.setHeader('Content-Type', 'application/json');
|
||||
response.end(JSON.stringify({ ok: true }));
|
||||
return;
|
||||
}
|
||||
response.statusCode = 404;
|
||||
response.end('not found');
|
||||
} catch (error) {
|
||||
response.statusCode = 500;
|
||||
response.end(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
});
|
||||
|
||||
let browser;
|
||||
try {
|
||||
const address = await listen(server);
|
||||
const origin = `http://127.0.0.1:${address.port}`;
|
||||
const keypair = KEYUTIL.generateKeypair('RSA', 1024);
|
||||
const privateKey = KEYUTIL.getPEM(keypair.prvKeyObj, 'PKCS8PRV');
|
||||
const publicKey = KEYUTIL.getPEM(keypair.pubKeyObj);
|
||||
const secret = crypto.getRandomValues(new Uint8Array(32));
|
||||
const secretBase64 = Buffer.from(secret).toString('base64');
|
||||
|
||||
browser = await chromium.launch({ executablePath, headless: true, args: ['--no-sandbox', '--disable-gpu'] });
|
||||
const page = await browser.newPage();
|
||||
await page.goto(origin, { waitUntil: 'domcontentloaded' });
|
||||
await page.waitForFunction(() => window.__g4Ready === true);
|
||||
await page.evaluate(({ privateKey, secretBase64 }) => {
|
||||
const bytes = Uint8Array.from(atob(secretBase64), (character) => character.charCodeAt(0));
|
||||
class Axios {
|
||||
async request(config) {
|
||||
const canonical = JSON.stringify(config.data);
|
||||
const signer = new window.KJUR.crypto.Signature({ alg: 'SHA256withRSA' });
|
||||
signer.init(privateKey);
|
||||
signer.updateString(canonical);
|
||||
const signature = signer.sign();
|
||||
const jwt = await new window.jose.SignJWT({ account: config.data.account })
|
||||
.setProtectedHeader({ alg: 'HS256' })
|
||||
.sign(bytes);
|
||||
const jwe = await new window.jose.CompactEncrypt(new TextEncoder().encode(canonical))
|
||||
.setProtectedHeader({ alg: 'dir', enc: 'A256GCM' })
|
||||
.encrypt(bytes);
|
||||
const response = await fetch('/g4-submit', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'X-Signature': signature },
|
||||
body: JSON.stringify({ canonical, jwt, jwe }),
|
||||
});
|
||||
return await response.json();
|
||||
}
|
||||
}
|
||||
window.axios = { Axios };
|
||||
window.__g4Fixture = { privateKey, bytes };
|
||||
window.__g4Originals = {
|
||||
stringify: JSON.stringify,
|
||||
axiosRequest: Axios.prototype.request,
|
||||
signature: window.KJUR.crypto.Signature,
|
||||
signJwt: window.jose.SignJWT,
|
||||
compactEncrypt: window.jose.CompactEncrypt,
|
||||
};
|
||||
}, { privateKey, secretBase64 });
|
||||
await page.addScriptTag({ path: recorderPath });
|
||||
await page.evaluate(() => {
|
||||
window.__YAKIT_PAGE_RECORDER_V9__.command('start', {
|
||||
captureValues: false,
|
||||
maxEntries: 200,
|
||||
maxValueBytes: 2_048,
|
||||
});
|
||||
});
|
||||
await page.click('#run');
|
||||
const result = await page.evaluate(async () => {
|
||||
const client = new window.axios.Axios();
|
||||
return await client.request({ data: { account: 'admin', nonce: '1700000000' } });
|
||||
});
|
||||
assert(result?.ok === true, 'Browser G4 request did not complete');
|
||||
await page.waitForTimeout(50);
|
||||
|
||||
const snapshot = await page.evaluate(() => window.__YAKIT_PAGE_RECORDER_V9__.command('get', { limit: 200 }));
|
||||
const events = snapshot.events || [];
|
||||
const jsrsasignEvents = events.filter((event) => event.crypto?.adapterId === 'jsrsasign');
|
||||
const joseEvents = events.filter((event) => event.crypto?.adapterId === 'jose');
|
||||
const transformOperations = new Set(events.filter((event) => event.kind === 'transform').map((event) => event.operation));
|
||||
const requestEvent = events.find((event) => event.kind === 'fetch' && event.url?.includes('/g4-submit'));
|
||||
|
||||
for (const phase of ['create', 'init', 'update', 'final']) {
|
||||
assert(jsrsasignEvents.some((event) => event.crypto?.state?.phase === phase), `Browser jsrsasign missed ${phase}`);
|
||||
}
|
||||
const jsrsasignCorrelation = new Set(jsrsasignEvents.map((event) => event.crypto?.state?.correlationId).filter(Boolean));
|
||||
assert(jsrsasignCorrelation.size === 1, 'Browser jsrsasign stages did not share one correlation ID');
|
||||
for (const operation of ['SignJWT.create', 'SignJWT.sign', 'CompactEncrypt.create', 'CompactEncrypt.encrypt']) {
|
||||
assert(joseEvents.some((event) => event.crypto?.operation === operation), `Browser jose missed ${operation}`);
|
||||
}
|
||||
assert(joseEvents.filter((event) => ['SignJWT.sign', 'CompactEncrypt.encrypt'].includes(event.crypto?.operation)).every((event) => event.durationMs >= 0), 'Browser jose Promise results did not settle');
|
||||
assert(transformOperations.has('JSON.stringify'), 'Browser fixture missed JSON serialization evidence');
|
||||
assert(transformOperations.has('axios.request'), 'Browser fixture missed Axios request-builder evidence');
|
||||
assert(requestEvent?.inputs?.some((item) => item.path === '$headers.x-signature'), 'Browser fixture missed Header signature evidence');
|
||||
const metadata = JSON.stringify(snapshot);
|
||||
assert(!metadata.includes(privateKey), 'Recorder metadata leaked the private key');
|
||||
assert(!metadata.includes(capturedRequest.body.canonical), 'Metadata-only recording leaked the canonical plaintext');
|
||||
|
||||
const verifier = new KJUR.crypto.Signature({ alg: 'SHA256withRSA' });
|
||||
verifier.init(publicKey);
|
||||
verifier.updateString(capturedRequest.body.canonical);
|
||||
assert(verifier.verify(capturedRequest.signature), 'Independent jsrsasign verifier rejected the browser signature');
|
||||
const jwt = await jwtVerify(capturedRequest.body.jwt, secret, { algorithms: ['HS256'] });
|
||||
assert(jwt.payload.account === 'admin', 'Independent jose verifier rejected the browser JWT');
|
||||
const decrypted = await compactDecrypt(capturedRequest.body.jwe, secret, {
|
||||
keyManagementAlgorithms: ['dir'],
|
||||
contentEncryptionAlgorithms: ['A256GCM'],
|
||||
});
|
||||
assert(new TextDecoder().decode(decrypted.plaintext) === capturedRequest.body.canonical, 'Independent jose decrypt did not recover the canonical request');
|
||||
|
||||
const restored = await page.evaluate(() => {
|
||||
window.__YAKIT_PAGE_RECORDER_V9__.command('stop');
|
||||
return {
|
||||
stringify: JSON.stringify === window.__g4Originals.stringify,
|
||||
axiosRequest: window.axios.Axios.prototype.request === window.__g4Originals.axiosRequest,
|
||||
signature: window.KJUR.crypto.Signature === window.__g4Originals.signature,
|
||||
signJwt: window.jose.SignJWT === window.__g4Originals.signJwt,
|
||||
compactEncrypt: window.jose.CompactEncrypt === window.__g4Originals.compactEncrypt,
|
||||
};
|
||||
});
|
||||
assert(Object.values(restored).every(Boolean), `G4 runtime did not restore page methods: ${JSON.stringify(restored)}`);
|
||||
|
||||
console.log(JSON.stringify({
|
||||
jsrsasignEvents: jsrsasignEvents.length,
|
||||
joseEvents: joseEvents.length,
|
||||
transforms: [...transformOperations],
|
||||
requestHeaderLinked: true,
|
||||
independentVerification: true,
|
||||
restored: true,
|
||||
}, null, 2));
|
||||
} finally {
|
||||
await browser?.close();
|
||||
await close(server);
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { randomBytes, webcrypto } from 'node:crypto';
|
||||
import { cp, mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
||||
import { createServer } from 'node:http';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import { chromium } from 'playwright-core';
|
||||
import { WebSocketServer } from 'ws';
|
||||
import { resolveChromiumPath } from './resolve-chromium.mjs';
|
||||
|
||||
const root = resolve(import.meta.dirname, '..');
|
||||
const yakRoot = resolve(process.env.YAK_REPO || root, process.env.YAK_REPO ? '.' : '../../go/yaklang');
|
||||
const extensionPath = resolve(root, process.env.EXTENSION_PATH || '.output/chrome-mv3-store');
|
||||
const executablePath = await resolveChromiumPath();
|
||||
const temporary = await mkdtemp(join(tmpdir(), 'yakit-native-host-e2e-'));
|
||||
const home = join(temporary, 'home');
|
||||
const profile = join(temporary, 'profile');
|
||||
const hostBinary = join(temporary, 'yakit-browser-agent-host');
|
||||
const testExtensionPath = join(temporary, 'extension');
|
||||
const hostName = 'com.yaklang.browser_agent';
|
||||
|
||||
const packagedManifest = JSON.parse(await readFile(join(extensionPath, 'manifest.json'), 'utf8'));
|
||||
if (!packagedManifest.optional_permissions?.includes('nativeMessaging') || packagedManifest.permissions?.includes('nativeMessaging')) {
|
||||
throw new Error('Native Messaging is not packaged as an optional permission');
|
||||
}
|
||||
// Chrome's optional-permission prompt is browser chrome and cannot be accepted by
|
||||
// Playwright. Pre-grant it only in a disposable copy so the native transport itself
|
||||
// can still be exercised through the real extension and browser APIs.
|
||||
await cp(extensionPath, testExtensionPath, { recursive: true });
|
||||
const testManifest = structuredClone(packagedManifest);
|
||||
testManifest.permissions = [...new Set([...(testManifest.permissions || []), 'nativeMessaging'])];
|
||||
testManifest.optional_permissions = (testManifest.optional_permissions || []).filter((value) => value !== 'nativeMessaging');
|
||||
await writeFile(join(testExtensionPath, 'manifest.json'), JSON.stringify(testManifest, null, 2));
|
||||
|
||||
const build = spawnSync('go', ['build', '-o', hostBinary, './common/browser/nativehostcmd'], {
|
||||
cwd: yakRoot, encoding: 'utf8', env: process.env,
|
||||
});
|
||||
if (build.status !== 0) throw new Error(`Native Host build failed:\n${build.stderr || build.stdout}`);
|
||||
|
||||
const bridgeHTTPServer = createServer();
|
||||
const pairingServer = new WebSocketServer({ noServer: true });
|
||||
const bridgeServer = new WebSocketServer({ noServer: true });
|
||||
bridgeHTTPServer.on('upgrade', (request, socket, head) => {
|
||||
const pathname = new URL(request.url || '/', 'http://127.0.0.1').pathname;
|
||||
const target = pathname === '/pairing' ? pairingServer : pathname === '/extension' ? bridgeServer : undefined;
|
||||
if (!target) return socket.destroy();
|
||||
target.handleUpgrade(request, socket, head, (webSocket) => target.emit('connection', webSocket, request));
|
||||
});
|
||||
await new Promise((resolveListen) => bridgeHTTPServer.listen(0, '127.0.0.1', resolveListen));
|
||||
const address = bridgeHTTPServer.address();
|
||||
const endpoint = `ws://127.0.0.1:${address.port}/extension`;
|
||||
const protocolVersion = 3;
|
||||
const engineIdentityId = 'native-e2e-engine-identity';
|
||||
const engineInstanceId = 'native-e2e-engine-instance';
|
||||
const engineKeys = await webcrypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, ['sign', 'verify']);
|
||||
const rawEngineJWK = await webcrypto.subtle.exportKey('jwk', engineKeys.publicKey);
|
||||
const enginePublicKey = { kty: 'EC', crv: 'P-256', x: rawEngineJWK.x, y: rawEngineJWK.y };
|
||||
let pairedClient;
|
||||
let authenticatedConnections = 0;
|
||||
let resolveHello;
|
||||
const helloReceived = new Promise((resolveMessage) => { resolveHello = resolveMessage; });
|
||||
|
||||
const toBase64URL = (value) => Buffer.from(value).toString('base64url');
|
||||
const engineChallengePayload = (challenge, timestamp) => ['yak-browser-bridge-v3', 'engine-challenge', engineIdentityId, engineInstanceId, challenge, String(timestamp)].join('\n');
|
||||
const clientAuthPayload = (origin, challenge, auth) => [
|
||||
'yak-browser-bridge-v3', 'client-auth', origin, engineIdentityId, engineInstanceId, challenge,
|
||||
auth.installationId || '', auth.client || '', auth.version || '', [...(auth.capabilities || [])].sort().join(','),
|
||||
auth.taskId || '', auth.grantId || '', auth.resumeSessionId || '',
|
||||
].join('\n');
|
||||
|
||||
pairingServer.on('connection', (socket, request) => socket.once('message', async (raw) => {
|
||||
const pairing = JSON.parse(raw.toString());
|
||||
if (pairing.type !== 'pair_request' || pairing.protocolVersion !== protocolVersion) return socket.close(1008, 'invalid pairing request');
|
||||
const requestId = 'native-e2e-pairing';
|
||||
const serverNonce = toBase64URL(randomBytes(32));
|
||||
const transcript = [
|
||||
'yak-browser-pairing-v1', engineIdentityId, requestId, request.headers.origin, pairing.installationId,
|
||||
pairing.nonce, serverNonce, pairing.publicKey.kty, pairing.publicKey.crv, pairing.publicKey.x, pairing.publicKey.y,
|
||||
].join('\n');
|
||||
const digest = Buffer.from(await webcrypto.subtle.digest('SHA-256', Buffer.from(transcript)));
|
||||
const code = String(digest.readBigUInt64BE() % 1_000_000n).padStart(6, '0');
|
||||
pairedClient = { installationId: pairing.installationId, publicKey: pairing.publicKey };
|
||||
socket.send(JSON.stringify({
|
||||
type: 'pair_pending', protocolVersion, requestId, serverNonce, engineIdentityId, code,
|
||||
expiresAt: Date.now() + 60_000, publicKey: enginePublicKey,
|
||||
}));
|
||||
setTimeout(() => socket.send(JSON.stringify({
|
||||
type: 'pair_approved', requestId, deviceId: 'native-e2e-device', engineIdentityId, publicKey: enginePublicKey,
|
||||
})), 50);
|
||||
}));
|
||||
|
||||
bridgeServer.on('connection', async (socket, request) => {
|
||||
const challenge = toBase64URL(randomBytes(32));
|
||||
const timestamp = Date.now();
|
||||
socket.send(JSON.stringify({
|
||||
type: 'challenge', protocolVersion, challenge, timestamp, engineIdentityId, engineInstanceId, publicKey: enginePublicKey,
|
||||
signature: toBase64URL(await webcrypto.subtle.sign(
|
||||
{ name: 'ECDSA', hash: 'SHA-256' }, engineKeys.privateKey, Buffer.from(engineChallengePayload(challenge, timestamp)),
|
||||
)),
|
||||
}));
|
||||
socket.once('message', (raw) => void (async () => {
|
||||
const hello = JSON.parse(raw.toString());
|
||||
if (!request.headers.origin?.startsWith('chrome-extension://') || hello.type !== 'auth' || hello.protocolVersion !== protocolVersion || !hello.installationId || hello.challenge !== challenge || !pairedClient) {
|
||||
socket.close(1008, 'invalid native e2e handshake');
|
||||
return;
|
||||
}
|
||||
const clientKey = await webcrypto.subtle.importKey('jwk', pairedClient.publicKey, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['verify']);
|
||||
const verified = await webcrypto.subtle.verify(
|
||||
{ name: 'ECDSA', hash: 'SHA-256' }, clientKey, Buffer.from(hello.signature, 'base64url'),
|
||||
Buffer.from(clientAuthPayload(request.headers.origin, challenge, hello)),
|
||||
);
|
||||
if (!verified || pairedClient.installationId !== hello.installationId) return socket.close(1008, 'invalid native e2e signature');
|
||||
socket.send(JSON.stringify({
|
||||
type: 'hello_ack', protocolVersion, version: 'native-e2e-engine', capabilities: [],
|
||||
sessionId: 'native-e2e-session', engineIdentityId, engineInstanceId,
|
||||
connectionId: 'native-e2e-connection', resumed: false,
|
||||
}));
|
||||
socket.on('message', (payload) => {
|
||||
const message = JSON.parse(payload.toString());
|
||||
if (message.type === 'ping') socket.send(JSON.stringify({
|
||||
type: 'pong', id: message.id, sequence: message.sequence, timestamp: message.timestamp, replyTimestamp: Date.now(),
|
||||
}));
|
||||
});
|
||||
authenticatedConnections += 1;
|
||||
if (authenticatedConnections >= 2) resolveHello({ hello, origin: request.headers.origin });
|
||||
})());
|
||||
});
|
||||
|
||||
await mkdir(join(home, '.config', 'yakit'), { recursive: true });
|
||||
await writeFile(join(home, '.config', 'yakit', 'browser-agent-native-host.json'), JSON.stringify({ endpoint }));
|
||||
|
||||
let context;
|
||||
try {
|
||||
const launch = () => chromium.launchPersistentContext(profile, {
|
||||
executablePath,
|
||||
headless: true,
|
||||
env: { ...process.env, HOME: home },
|
||||
args: [`--disable-extensions-except=${testExtensionPath}`, `--load-extension=${testExtensionPath}`, '--no-first-run'],
|
||||
});
|
||||
context = await launch();
|
||||
let worker = context.serviceWorkers()[0];
|
||||
if (!worker) worker = await context.waitForEvent('serviceworker', { timeout: 15_000 });
|
||||
const extensionId = new URL(worker.url()).host;
|
||||
const manifest = {
|
||||
name: hostName,
|
||||
description: 'Yakit Browser Agent Native Host E2E',
|
||||
path: hostBinary,
|
||||
type: 'stdio',
|
||||
allowed_origins: [`chrome-extension://${extensionId}/`],
|
||||
};
|
||||
const manifestDirectories = [
|
||||
...['google-chrome', 'google-chrome-for-testing', 'chromium'].map((product) => join(home, '.config', product, 'NativeMessagingHosts')),
|
||||
join(profile, 'NativeMessagingHosts'),
|
||||
];
|
||||
for (const directory of manifestDirectories) {
|
||||
const path = join(directory, `${hostName}.json`);
|
||||
await mkdir(dirname(path), { recursive: true });
|
||||
await writeFile(path, JSON.stringify(manifest));
|
||||
}
|
||||
|
||||
// Chromium caches native-host registrations at process startup.
|
||||
await context.close();
|
||||
context = await launch();
|
||||
worker = context.serviceWorkers()[0];
|
||||
if (!worker) worker = await context.waitForEvent('serviceworker', { timeout: 15_000 });
|
||||
const restartedExtensionId = new URL(worker.url()).host;
|
||||
if (restartedExtensionId !== extensionId) throw new Error('Extension ID changed after Native Host registration');
|
||||
|
||||
const options = await context.newPage();
|
||||
await options.goto(`chrome-extension://${extensionId}/options.html#engine`);
|
||||
try {
|
||||
await options.evaluate(async ({ bridgeEndpoint }) => {
|
||||
const send = async (action, payload) => {
|
||||
const response = await chrome.runtime.sendMessage({ action, payload });
|
||||
if (!response?.ok) throw new Error(response?.error || action);
|
||||
return response.data;
|
||||
};
|
||||
const state = await send('state.get');
|
||||
await send('bridge.config.save', {
|
||||
transport: 'websocket', nativeHost: 'com.yaklang.browser_agent', endpoint: bridgeEndpoint,
|
||||
autoConnect: false, installationId: state.bridge.installationId,
|
||||
});
|
||||
await send('bridge.pair');
|
||||
for (let attempt = 0; attempt < 50; attempt += 1) {
|
||||
const [next, status] = await Promise.all([send('state.get'), send('bridge.status')]);
|
||||
if (next.bridge.pairedEngine && status.state === 'connected') {
|
||||
await send('bridge.disconnect');
|
||||
await send('bridge.config.save', { ...next.bridge, transport: 'native', autoConnect: false });
|
||||
await send('bridge.connect');
|
||||
return;
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
}
|
||||
throw new Error('Browser extension pairing did not complete');
|
||||
}, { bridgeEndpoint: endpoint });
|
||||
} catch (error) {
|
||||
const diagnostics = await options.evaluate(async () => ({
|
||||
body: document.body.innerText,
|
||||
permissions: await chrome.permissions.getAll(),
|
||||
bridge: await chrome.runtime.sendMessage({ action: 'bridge.status' }),
|
||||
}));
|
||||
throw new Error(`Native Host pairing and settings failed: ${JSON.stringify(diagnostics)}`, { cause: error });
|
||||
}
|
||||
let connection;
|
||||
try {
|
||||
connection = await Promise.race([
|
||||
helloReceived,
|
||||
new Promise((_, reject) => setTimeout(() => reject(new Error('Native Host did not reach Yak Bridge')), 15_000)),
|
||||
]);
|
||||
} catch (error) {
|
||||
const diagnostics = await options.evaluate(async () => ({
|
||||
body: document.body.innerText,
|
||||
permissions: await chrome.permissions.getAll(),
|
||||
bridge: await chrome.runtime.sendMessage({ action: 'bridge.status' }),
|
||||
}));
|
||||
throw new Error(`Native Host transport failed: ${JSON.stringify(diagnostics)}`, { cause: error });
|
||||
}
|
||||
const status = await options.evaluate(async () => {
|
||||
const response = await chrome.runtime.sendMessage({ action: 'bridge.status' });
|
||||
if (!response?.ok) throw new Error(response?.error || 'bridge.status');
|
||||
return response.data;
|
||||
});
|
||||
if (status.state !== 'connected' || status.engineInstanceId !== 'native-e2e-engine-instance' || status.connectionId !== 'native-e2e-connection') {
|
||||
throw new Error(`Native Host identity did not reach the extension: ${JSON.stringify(status)}`);
|
||||
}
|
||||
console.log(JSON.stringify({
|
||||
extensionId,
|
||||
endpoint,
|
||||
permissionFixture: 'pre-granted only in temporary E2E copy; production package remains optional',
|
||||
connection,
|
||||
status,
|
||||
}, null, 2));
|
||||
} finally {
|
||||
await context?.close();
|
||||
for (const client of bridgeServer.clients) client.terminate();
|
||||
for (const client of pairingServer.clients) client.terminate();
|
||||
bridgeServer.close();
|
||||
pairingServer.close();
|
||||
bridgeHTTPServer.close();
|
||||
await rm(temporary, { recursive: true, force: true });
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Verifies a freshly published release from the public endpoint: artifact
|
||||
* bytes and checksum files, cache headers, manifest consistency, and zip
|
||||
* layout (manifest.json at the zip root with the expected version).
|
||||
*
|
||||
* Usage:
|
||||
* node scripts/verify-public.mjs --public-base-url=https://aliyun-oss.yaklang.com/chrome-extension \
|
||||
* --release-entry=dist/release-entry.json
|
||||
*/
|
||||
import { createHash } from 'node:crypto';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { resolve } from 'node:path';
|
||||
import AdmZip from 'adm-zip';
|
||||
const root = resolve(import.meta.dirname, '..');
|
||||
|
||||
function parseArgs(argv) {
|
||||
const out = {};
|
||||
for (const arg of argv) {
|
||||
if (!arg.startsWith('--')) throw new Error(`unexpected argument: ${arg}`);
|
||||
const eq = arg.indexOf('=');
|
||||
const key = eq === -1 ? arg.slice(2) : arg.slice(2, eq);
|
||||
out[key] = eq === -1 ? true : arg.slice(eq + 1);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function assert(condition, message) {
|
||||
if (!condition) throw new Error(message);
|
||||
}
|
||||
|
||||
const sha256 = (buffer) => createHash('sha256').update(buffer).digest('hex');
|
||||
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
if (!args['public-base-url']) throw new Error('--public-base-url is required');
|
||||
if (!args['release-entry']) throw new Error('--release-entry is required');
|
||||
const baseUrl = String(args['public-base-url']).replace(/\/+$/, '');
|
||||
|
||||
// Cache-busting query parameter: the manifest may be served from a 5-minute
|
||||
// CDN cache, and we must observe the state right after this publish.
|
||||
const bust = `verify=${Date.now()}`;
|
||||
|
||||
async function fetchOk(url) {
|
||||
const res = await fetch(`${url}?${bust}`);
|
||||
if (!res.ok) throw new Error(`GET ${url} -> ${res.status}`);
|
||||
return res;
|
||||
}
|
||||
|
||||
const entry = JSON.parse(await readFile(resolve(root, String(args['release-entry'])), 'utf8'));
|
||||
|
||||
for (const artifact of entry.artifacts) {
|
||||
const res = await fetchOk(artifact.url);
|
||||
const contentType = res.headers.get('content-type') ?? '';
|
||||
const cacheControl = res.headers.get('cache-control') ?? '';
|
||||
assert(contentType.startsWith('application/'), `${artifact.filename}: unexpected content-type "${contentType}"`);
|
||||
assert(cacheControl.includes('max-age=31536000') && cacheControl.includes('immutable'),
|
||||
`${artifact.filename}: unexpected cache-control "${cacheControl}" for an immutable artifact`);
|
||||
const body = Buffer.from(await res.arrayBuffer());
|
||||
assert(body.length === artifact.size, `${artifact.filename}: content-length ${body.length} != expected ${artifact.size}`);
|
||||
assert(sha256(body) === artifact.sha256, `${artifact.filename}: sha256 mismatch`);
|
||||
|
||||
const checksumRes = await fetchOk(artifact.checksum_url);
|
||||
assert((await checksumRes.text()) === `${artifact.sha256} ${artifact.filename}\n`,
|
||||
`${artifact.filename}: checksum file content mismatch`);
|
||||
|
||||
const zip = new AdmZip(body);
|
||||
const innerEntry = zip.getEntry('manifest.json');
|
||||
assert(innerEntry, `${artifact.filename}: manifest.json missing at zip root`);
|
||||
const innerManifest = JSON.parse(zip.readAsText(innerEntry));
|
||||
assert(innerManifest.version === entry.version,
|
||||
`${artifact.filename}: zip manifest version ${innerManifest.version} != ${entry.version}`);
|
||||
const backgroundEntry = zip.getEntry('background.js');
|
||||
assert(backgroundEntry && backgroundEntry.getData().length > 0,
|
||||
`${artifact.filename}: background.js missing or empty in zip`);
|
||||
|
||||
console.log(`verified ${artifact.filename} (${artifact.size} bytes)`);
|
||||
}
|
||||
|
||||
const manifestRes = await fetchOk(`${baseUrl}/manifest.json`);
|
||||
const manifestBytes = Buffer.from(await manifestRes.arrayBuffer());
|
||||
const manifestCache = manifestRes.headers.get('cache-control') ?? '';
|
||||
// The CDN in front of aliyun-oss.yaklang.com rewrites JSON cache-control to
|
||||
// max-age=60 (the browser mirror gets the same treatment), so assert the
|
||||
// effective freshness window is short instead of matching our upload value.
|
||||
const manifestMaxAge = Number(/max-age=(\d+)/.exec(manifestCache)?.[1] ?? 0);
|
||||
assert(manifestMaxAge > 0 && manifestMaxAge <= 300,
|
||||
`manifest.json: unexpected cache-control "${manifestCache}"`);
|
||||
const manifest = JSON.parse(manifestBytes.toString('utf8'));
|
||||
assert(manifest.latest === entry.version, `manifest.latest ${manifest.latest} != ${entry.version}`);
|
||||
const versionEntry = manifest.versions.find((v) => v.version === entry.version);
|
||||
assert(versionEntry, `manifest has no entry for version ${entry.version}`);
|
||||
assert(versionEntry.artifacts.length === entry.artifacts.length,
|
||||
`manifest artifacts count ${versionEntry.artifacts.length} != ${entry.artifacts.length}`);
|
||||
for (const artifact of entry.artifacts) {
|
||||
const remote = versionEntry.artifacts.find((a) => a.variant === artifact.variant);
|
||||
assert(remote, `manifest missing variant ${artifact.variant} for version ${entry.version}`);
|
||||
assert(remote.sha256 === artifact.sha256, `manifest sha256 mismatch for variant ${artifact.variant}`);
|
||||
assert(remote.url === artifact.url, `manifest url mismatch for variant ${artifact.variant}`);
|
||||
}
|
||||
|
||||
const checksumRes = await fetchOk(`${baseUrl}/manifest.json.sha256.txt`);
|
||||
assert((await checksumRes.text()) === `${sha256(manifestBytes)} manifest.json\n`,
|
||||
'manifest.json.sha256.txt does not match the served manifest');
|
||||
|
||||
console.log(`manifest verified: latest=${manifest.latest}, ${manifest.versions.length} version(s) in history`);
|
||||
@@ -1,44 +0,0 @@
|
||||
.App {
|
||||
width: 420px;
|
||||
border-radius: 0px 0px 4px 4px;
|
||||
border-right: 1px solid #EAECF3;
|
||||
border-bottom: 1px solid #EAECF3;
|
||||
border-left: 1px solid #EAECF3;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.App-logo {
|
||||
height: 40vmin;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.App-logo {
|
||||
animation: App-logo-spin infinite 20s linear;
|
||||
}
|
||||
}
|
||||
|
||||
.App-header {
|
||||
background-color: #282c34;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: calc(10px + 2vmin);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.App-link {
|
||||
color: #61dafb;
|
||||
}
|
||||
|
||||
@keyframes App-logo-spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
import React from "react";
|
||||
import "./App.css";
|
||||
import {ConfigProvider} from "antd";
|
||||
import {Contro} from "@components/Contro";
|
||||
import {Proxifier} from "@components/Proxifier";
|
||||
import {EvalInTab} from "@components/EvalInTab";
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<ConfigProvider
|
||||
theme={{
|
||||
token: {
|
||||
colorPrimary: "#F28B44",
|
||||
},
|
||||
}}
|
||||
>
|
||||
<div className="App">
|
||||
{/*<Contro/>*/}
|
||||
<Proxifier/>
|
||||
|
||||
<EvalInTab/>
|
||||
</div>
|
||||
</ConfigProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
@@ -0,0 +1,59 @@
|
||||
import type { BackgroundRequestHandler } from '../router';
|
||||
import { ok } from '../response';
|
||||
import { targetTabId } from '../request-context';
|
||||
import { listCookies, removeCookie, setCookie } from '@/features/cookies/service';
|
||||
import { exportCookies, importCookies } from '@/features/cookies/transfer';
|
||||
import { resolveTabCookieStoreId } from '@/platform/browser/isolation';
|
||||
import { ExtensionError } from '@/shared/errors';
|
||||
|
||||
async function requestCookieStoreId(
|
||||
tabId: number | undefined,
|
||||
sender: Parameters<BackgroundRequestHandler>[1],
|
||||
): Promise<string> {
|
||||
const target = targetTabId(tabId, sender);
|
||||
if (!target) {
|
||||
throw new ExtensionError('target_unavailable', '请选择一个可访问的 HTTP(S) 标签页');
|
||||
}
|
||||
return resolveTabCookieStoreId(target);
|
||||
}
|
||||
|
||||
export const handleCookieRequest: BackgroundRequestHandler = async (request, sender) => {
|
||||
switch (request.action) {
|
||||
case 'cookie.list': return ok(await listCookies(
|
||||
request.payload.url,
|
||||
await requestCookieStoreId(request.payload.tabId, sender),
|
||||
));
|
||||
case 'cookie.set': {
|
||||
const { tabId, ...input } = request.payload;
|
||||
return ok(await setCookie({
|
||||
...input,
|
||||
storeId: await requestCookieStoreId(tabId, sender),
|
||||
}));
|
||||
}
|
||||
case 'cookie.remove':
|
||||
await removeCookie(request.payload);
|
||||
return ok();
|
||||
case 'cookie.removeMany': {
|
||||
const results = await Promise.allSettled(
|
||||
request.payload.cookies.map((cookie) => removeCookie(cookie)),
|
||||
);
|
||||
const removed = results.filter((result) => result.status === 'fulfilled').length;
|
||||
return ok({ removed, failed: results.length - removed });
|
||||
}
|
||||
case 'cookie.import': return ok(await importCookies(
|
||||
request.payload.url,
|
||||
request.payload.format,
|
||||
request.payload.text,
|
||||
await requestCookieStoreId(request.payload.tabId, sender),
|
||||
));
|
||||
case 'cookie.export': return ok(exportCookies(
|
||||
await listCookies(
|
||||
request.payload.url,
|
||||
await requestCookieStoreId(request.payload.tabId, sender),
|
||||
),
|
||||
request.payload.format,
|
||||
request.payload.includeValues,
|
||||
));
|
||||
default: return undefined;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,116 @@
|
||||
import type { BackgroundRequestHandler } from '../router';
|
||||
import { ok } from '../response';
|
||||
import {
|
||||
applyProxyRules,
|
||||
clearCurrentSiteRoute,
|
||||
compileCurrentProxyRules,
|
||||
dirtyProxyState,
|
||||
exportProxyConfiguration,
|
||||
getProxyRuleSourcePage,
|
||||
hasProxyAuthPassword,
|
||||
importProxyConfiguration,
|
||||
previewCurrentProxyRules,
|
||||
refreshProxyRuleSource,
|
||||
removeProxyProfile,
|
||||
removeProxyRuleSource,
|
||||
routeCurrentSite,
|
||||
saveProxyProfile,
|
||||
saveProxyRuleSource,
|
||||
setProxyAuthPassword,
|
||||
switchProxy,
|
||||
} from '@/features/proxy/service';
|
||||
import { updateState } from '@/platform/storage/state';
|
||||
|
||||
export const handleProxyRequest: BackgroundRequestHandler = async (request) => {
|
||||
switch (request.action) {
|
||||
case 'proxy.save': return ok(await saveProxyProfile(request.payload));
|
||||
case 'proxy.delete': return ok(await removeProxyProfile(request.payload.id));
|
||||
case 'proxy.switch': return ok(await switchProxy(request.payload.id));
|
||||
case 'proxy.rule.save': {
|
||||
const rule = request.payload;
|
||||
return ok(await updateState((state) => {
|
||||
if (!state.proxyProfiles.some((profile) => profile.id === rule.proxyProfileId
|
||||
&& ['direct', 'fixed_servers'].includes(profile.kind))) {
|
||||
throw new Error('规则 PAC 只能使用直接连接或固定代理出口');
|
||||
}
|
||||
return dirtyProxyState({
|
||||
...state,
|
||||
proxyRules: [...state.proxyRules.filter((item) => item.id !== rule.id), rule],
|
||||
});
|
||||
}));
|
||||
}
|
||||
case 'proxy.rule.delete': {
|
||||
const { id } = request.payload;
|
||||
return ok(await updateState((state) => dirtyProxyState({
|
||||
...state,
|
||||
proxyRules: state.proxyRules.filter((item) => item.id !== id),
|
||||
})));
|
||||
}
|
||||
case 'proxy.auto.apply': return ok(await applyProxyRules());
|
||||
case 'proxy.rules.preview': return ok(await previewCurrentProxyRules(request.payload.url));
|
||||
case 'proxy.rules.compile': return ok(await compileCurrentProxyRules());
|
||||
case 'proxy.rules.reorder': {
|
||||
const ids = request.payload.ids;
|
||||
return ok(await updateState((current) => {
|
||||
if (ids.length !== current.proxyRules.length || new Set(ids).size !== ids.length
|
||||
|| ids.some((id) => !current.proxyRules.some((rule) => rule.id === id))) {
|
||||
throw new Error('规则排序必须包含当前全部规则且不能重复');
|
||||
}
|
||||
const byId = new Map(current.proxyRules.map((rule) => [rule.id, rule]));
|
||||
return dirtyProxyState({
|
||||
...current,
|
||||
proxyRules: ids.map((id, order) => ({
|
||||
...byId.get(id)!, order, updatedAt: Date.now(),
|
||||
})),
|
||||
});
|
||||
}));
|
||||
}
|
||||
case 'proxy.rules.settings': {
|
||||
const input = request.payload;
|
||||
return ok(await updateState((current) => {
|
||||
if (!current.proxyProfiles.some((profile) => profile.id === input.defaultProfileId
|
||||
&& ['direct', 'fixed_servers'].includes(profile.kind))) {
|
||||
throw new Error('默认出口必须是直接连接或固定代理');
|
||||
}
|
||||
return dirtyProxyState({ ...current, proxyRouting: input });
|
||||
}));
|
||||
}
|
||||
case 'proxy.source.save': return ok(await saveProxyRuleSource(request.payload));
|
||||
case 'proxy.source.refresh': return ok(await refreshProxyRuleSource(request.payload.id));
|
||||
case 'proxy.source.delete': return ok(await removeProxyRuleSource(request.payload.id));
|
||||
case 'proxy.sources.reorder': {
|
||||
const ids = request.payload.ids;
|
||||
return ok(await updateState((current) => {
|
||||
if (ids.length !== current.proxyRuleSources.length || new Set(ids).size !== ids.length
|
||||
|| ids.some((id) => !current.proxyRuleSources.some((source) => source.id === id))) {
|
||||
throw new Error('规则源排序必须包含当前全部订阅且不能重复');
|
||||
}
|
||||
const byId = new Map(current.proxyRuleSources.map((source) => [source.id, source]));
|
||||
return dirtyProxyState({
|
||||
...current,
|
||||
proxyRuleSources: ids.map((id, order) => ({ ...byId.get(id)!, order })),
|
||||
});
|
||||
}));
|
||||
}
|
||||
case 'proxy.source.rules': return ok(await getProxyRuleSourcePage(
|
||||
request.payload.id,
|
||||
request.payload.offset,
|
||||
request.payload.limit,
|
||||
request.payload.query,
|
||||
));
|
||||
case 'proxy.site.route': return ok(await routeCurrentSite(
|
||||
request.payload.url,
|
||||
request.payload.profileId,
|
||||
));
|
||||
case 'proxy.site.route.clear': return ok(await clearCurrentSiteRoute(request.payload.url));
|
||||
case 'proxy.auth.set':
|
||||
await setProxyAuthPassword(request.payload.profileId, request.payload.password);
|
||||
return ok({ configured: hasProxyAuthPassword(request.payload.profileId) });
|
||||
case 'proxy.auth.status': return ok({
|
||||
configured: hasProxyAuthPassword(request.payload.profileId),
|
||||
});
|
||||
case 'proxy.config.export': return ok(await exportProxyConfiguration());
|
||||
case 'proxy.config.import': return ok(await importProxyConfiguration(request.payload.configuration));
|
||||
default: return undefined;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,178 @@
|
||||
import type { BackgroundRequestHandler } from '../router';
|
||||
import { ok } from '../response';
|
||||
import { requiredDebuggerTarget, requiredRequestTarget } from '../request-context';
|
||||
import {
|
||||
browserRecordingStatus,
|
||||
clearBrowserRecording,
|
||||
createRecordedPageCallable,
|
||||
getBrowserRecording,
|
||||
startBrowserRecording,
|
||||
stopBrowserRecording,
|
||||
} from '@/features/browser-recording/service';
|
||||
import {
|
||||
createCapturedPageCallable,
|
||||
deepCaptureStatus,
|
||||
detachDeepCapture,
|
||||
keepDeepCaptureAlive,
|
||||
resumeDeepCapture,
|
||||
startDeepCapture,
|
||||
} from '@/features/deep-capture/service';
|
||||
import {
|
||||
deletePageCallable,
|
||||
executePageCallable,
|
||||
listPageCallables,
|
||||
} from '@/features/page-callable/service';
|
||||
import { invalidateBrowserTransformProfilesForCallable } from '@/features/browser-transform/service';
|
||||
import { appendAuditEvent } from '@/features/diagnostics/audit';
|
||||
import {
|
||||
resolveBrowserProfileCallableAnalysis,
|
||||
resolveBrowserProfileCaptureContext,
|
||||
stageBrowserProfileEvidence,
|
||||
} from '@/features/browser-analysis/service';
|
||||
|
||||
export const handleRecordingRequest: BackgroundRequestHandler = async (request, sender) => {
|
||||
switch (request.action) {
|
||||
case 'recording.start': {
|
||||
const input = request.payload;
|
||||
const target = await requiredRequestTarget(input, sender);
|
||||
const snapshot = await startBrowserRecording(target, input);
|
||||
void appendAuditEvent({
|
||||
category: 'capability',
|
||||
action: 'recording.start',
|
||||
outcome: 'success',
|
||||
targetTabId: target.tabId,
|
||||
summary: input.captureValues ? '包含用户明确启用的短时值预览' : '仅元数据',
|
||||
});
|
||||
return ok(snapshot);
|
||||
}
|
||||
case 'recording.status': return ok(await browserRecordingStatus(
|
||||
await requiredRequestTarget(request.payload, sender),
|
||||
));
|
||||
case 'recording.get': {
|
||||
const target = await requiredRequestTarget(request.payload, sender);
|
||||
const snapshot = await getBrowserRecording(target, request.payload.limit, true);
|
||||
await stageBrowserProfileEvidence(snapshot);
|
||||
return ok(snapshot);
|
||||
}
|
||||
case 'recording.clear': {
|
||||
const target = await requiredRequestTarget(request.payload, sender);
|
||||
const snapshot = await clearBrowserRecording(target, true);
|
||||
void appendAuditEvent({
|
||||
category: 'capability',
|
||||
action: 'recording.clear',
|
||||
outcome: 'success',
|
||||
targetTabId: target.tabId,
|
||||
});
|
||||
return ok(snapshot);
|
||||
}
|
||||
case 'recording.stop': {
|
||||
const target = await requiredRequestTarget(request.payload, sender);
|
||||
const snapshot = await stopBrowserRecording(target, true);
|
||||
await stageBrowserProfileEvidence(snapshot);
|
||||
void appendAuditEvent({
|
||||
category: 'capability',
|
||||
action: 'recording.stop',
|
||||
outcome: 'success',
|
||||
targetTabId: target.tabId,
|
||||
});
|
||||
return ok(snapshot);
|
||||
}
|
||||
case 'callable.create': {
|
||||
const payload = request.payload;
|
||||
const target = payload.source === 'deep-capture'
|
||||
? await requiredDebuggerTarget(payload, sender)
|
||||
: await requiredRequestTarget(payload, sender);
|
||||
let callable;
|
||||
if (payload.source !== 'deep-capture') {
|
||||
callable = await createRecordedPageCallable(target, payload);
|
||||
} else if (payload.strategy === 'request-transaction') {
|
||||
const capture = await resolveBrowserProfileCaptureContext(target, payload.candidateId);
|
||||
callable = await createCapturedPageCallable(target, payload.callFrameId, {
|
||||
strategy: 'request-transaction',
|
||||
name: payload.name,
|
||||
transaction: capture.transaction,
|
||||
analysis: capture.analysis,
|
||||
});
|
||||
} else if (payload.strategy === 'selected-frame') {
|
||||
const analysis = payload.candidateId
|
||||
? await resolveBrowserProfileCallableAnalysis(target, payload.candidateId)
|
||||
: undefined;
|
||||
callable = await createCapturedPageCallable(target, payload.callFrameId, {
|
||||
strategy: 'selected-frame',
|
||||
name: payload.name,
|
||||
analysis,
|
||||
});
|
||||
} else {
|
||||
callable = await createCapturedPageCallable(target, payload.callFrameId, payload);
|
||||
}
|
||||
void appendAuditEvent({
|
||||
category: 'capability',
|
||||
action: 'callable.create',
|
||||
outcome: 'success',
|
||||
targetTabId: target.tabId,
|
||||
summary: callable.name,
|
||||
});
|
||||
return ok(callable);
|
||||
}
|
||||
case 'callable.list': return ok(await listPageCallables(
|
||||
await requiredRequestTarget(request.payload, sender),
|
||||
));
|
||||
case 'callable.execute': {
|
||||
const target = await requiredRequestTarget(request.payload, sender);
|
||||
const result = await executePageCallable(
|
||||
target,
|
||||
request.payload.callableId,
|
||||
request.payload.args,
|
||||
);
|
||||
void appendAuditEvent({
|
||||
category: 'capability',
|
||||
action: 'callable.execute',
|
||||
outcome: 'success',
|
||||
targetTabId: target.tabId,
|
||||
summary: `${result.durationMs.toFixed(1)} ms`,
|
||||
});
|
||||
return ok(result);
|
||||
}
|
||||
case 'callable.delete': {
|
||||
const target = await requiredRequestTarget(request.payload, sender);
|
||||
const callables = await deletePageCallable(target, request.payload.callableId);
|
||||
await invalidateBrowserTransformProfilesForCallable(target, request.payload.callableId);
|
||||
return ok(callables);
|
||||
}
|
||||
case 'deep.capture.start': {
|
||||
const target = await requiredRequestTarget(request.payload, sender);
|
||||
const status = await startDeepCapture(target, request.payload.matcher);
|
||||
void appendAuditEvent({
|
||||
category: 'capability',
|
||||
action: 'deep.capture.start',
|
||||
outcome: 'success',
|
||||
targetTabId: target.tabId,
|
||||
summary: request.payload.matcher.kind === 'request'
|
||||
? request.payload.matcher.urlPattern
|
||||
: request.payload.matcher.operation,
|
||||
});
|
||||
return ok(status);
|
||||
}
|
||||
case 'deep.capture.status': return ok(await deepCaptureStatus(
|
||||
await requiredDebuggerTarget(request.payload, sender),
|
||||
));
|
||||
case 'deep.capture.keepalive': return ok(await keepDeepCaptureAlive(
|
||||
await requiredDebuggerTarget(request.payload, sender),
|
||||
));
|
||||
case 'deep.capture.resume': return ok(await resumeDeepCapture(
|
||||
await requiredDebuggerTarget(request.payload, sender),
|
||||
));
|
||||
case 'deep.capture.detach': {
|
||||
const target = await requiredDebuggerTarget(request.payload, sender);
|
||||
const status = await detachDeepCapture(target);
|
||||
void appendAuditEvent({
|
||||
category: 'capability',
|
||||
action: 'deep.capture.detach',
|
||||
outcome: 'success',
|
||||
targetTabId: target.tabId,
|
||||
});
|
||||
return ok(status);
|
||||
}
|
||||
default: return undefined;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,160 @@
|
||||
import type { BackgroundRequestHandler } from '../router';
|
||||
import { ok } from '../response';
|
||||
import { requiredDebuggerTarget, requiredRequestTarget } from '../request-context';
|
||||
import {
|
||||
captureBrowserTransformRecovery,
|
||||
confirmBrowserTransformRecovery,
|
||||
deleteBrowserTransformProfile,
|
||||
executeBrowserTransform,
|
||||
getBrowserTransformRecovery,
|
||||
listBrowserTransformProfiles,
|
||||
resetBrowserTransformRecovery,
|
||||
saveBrowserTransformProfile,
|
||||
startBrowserTransformRecovery,
|
||||
validateBrowserTransformRecovery,
|
||||
} from '@/features/browser-transform/service';
|
||||
import {
|
||||
latestBrowserTransformValidation,
|
||||
proposeBrowserTransformProfile,
|
||||
validateInferredBrowserTransformProfile,
|
||||
} from '@/features/browser-analysis/service';
|
||||
import { appendAuditEvent } from '@/features/diagnostics/audit';
|
||||
|
||||
export const handleTransformRequest: BackgroundRequestHandler = async (request, sender) => {
|
||||
switch (request.action) {
|
||||
case 'analysis.profile.propose': {
|
||||
const input = request.payload;
|
||||
const target = await requiredRequestTarget(input, sender);
|
||||
return ok(await proposeBrowserTransformProfile(
|
||||
target,
|
||||
input.candidateId,
|
||||
input.callableId,
|
||||
input.inputPaths,
|
||||
input.name,
|
||||
));
|
||||
}
|
||||
case 'analysis.profile.validate': {
|
||||
const input = request.payload;
|
||||
const target = await requiredRequestTarget(input, sender);
|
||||
const result = await validateInferredBrowserTransformProfile(
|
||||
target,
|
||||
input.candidateId,
|
||||
input.callableId,
|
||||
input.packet,
|
||||
input.inputPaths,
|
||||
input.name,
|
||||
input.observed,
|
||||
input.comparisonMode,
|
||||
);
|
||||
void appendAuditEvent({
|
||||
category: 'capability',
|
||||
action: 'analysis.profile.validate',
|
||||
outcome: result.valid ? 'success' : 'denied',
|
||||
targetTabId: target.tabId,
|
||||
summary: result.proofLevel,
|
||||
});
|
||||
return ok(result);
|
||||
}
|
||||
case 'analysis.profile.validation.latest': return ok(
|
||||
await latestBrowserTransformValidation(
|
||||
await requiredRequestTarget(request.payload, sender),
|
||||
),
|
||||
);
|
||||
case 'transform.profile.list': {
|
||||
const input = request.payload;
|
||||
const target = input.tabId ? await requiredRequestTarget(input, sender) : undefined;
|
||||
return ok(await listBrowserTransformProfiles(
|
||||
target ? { tabId: target.tabId, frameId: target.frameId } : undefined,
|
||||
));
|
||||
}
|
||||
case 'transform.profile.save': {
|
||||
const profile = await saveBrowserTransformProfile(request.payload);
|
||||
void appendAuditEvent({
|
||||
category: 'capability',
|
||||
action: 'transform.profile.save',
|
||||
outcome: 'success',
|
||||
targetTabId: profile.target.tabId,
|
||||
summary: profile.name,
|
||||
});
|
||||
return ok(profile);
|
||||
}
|
||||
case 'transform.profile.delete': return ok(
|
||||
await deleteBrowserTransformProfile(request.payload.id),
|
||||
);
|
||||
case 'transform.recovery.get': return ok(
|
||||
await getBrowserTransformRecovery(request.payload.id),
|
||||
);
|
||||
case 'transform.recovery.start': {
|
||||
const status = await startBrowserTransformRecovery(request.payload.id);
|
||||
void appendAuditEvent({
|
||||
category: 'capability',
|
||||
action: 'transform.recovery.start',
|
||||
outcome: 'success',
|
||||
targetTabId: status.target.tabId,
|
||||
summary: '等待一次真实业务操作',
|
||||
});
|
||||
return ok(status);
|
||||
}
|
||||
case 'transform.recovery.capture': {
|
||||
const input = request.payload;
|
||||
const target = await requiredDebuggerTarget(input, sender);
|
||||
const recovery = await captureBrowserTransformRecovery(
|
||||
input.id,
|
||||
target,
|
||||
input.callFrameId,
|
||||
input.strategy,
|
||||
);
|
||||
void appendAuditEvent({
|
||||
category: 'capability',
|
||||
action: 'transform.recovery.capture',
|
||||
outcome: 'success',
|
||||
targetTabId: target.tabId,
|
||||
summary: recovery.binding.name,
|
||||
});
|
||||
return ok(recovery);
|
||||
}
|
||||
case 'transform.recovery.validate': {
|
||||
const result = await validateBrowserTransformRecovery(
|
||||
request.payload.id,
|
||||
request.payload.packet,
|
||||
);
|
||||
void appendAuditEvent({
|
||||
category: 'capability',
|
||||
action: 'transform.recovery.validate',
|
||||
outcome: 'success',
|
||||
durationMs: result.execution.durationMs,
|
||||
summary: result.recovery.validation?.proofLevel,
|
||||
});
|
||||
return ok(result);
|
||||
}
|
||||
case 'transform.recovery.confirm': {
|
||||
const profile = await confirmBrowserTransformRecovery(
|
||||
request.payload.id,
|
||||
request.payload.validationId,
|
||||
);
|
||||
void appendAuditEvent({
|
||||
category: 'capability',
|
||||
action: 'transform.recovery.confirm',
|
||||
outcome: 'success',
|
||||
targetTabId: profile.target.tabId,
|
||||
summary: profile.name,
|
||||
});
|
||||
return ok(profile);
|
||||
}
|
||||
case 'transform.recovery.reset': return ok(
|
||||
await resetBrowserTransformRecovery(request.payload.id),
|
||||
);
|
||||
case 'transform.execute': {
|
||||
const result = await executeBrowserTransform(request.payload);
|
||||
void appendAuditEvent({
|
||||
category: 'capability',
|
||||
action: `transform.${result.direction}`,
|
||||
outcome: 'success',
|
||||
durationMs: result.durationMs,
|
||||
summary: `${result.nodeDurations.length} 个 Pipeline 节点`,
|
||||
});
|
||||
return ok(result);
|
||||
}
|
||||
default: return undefined;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { BackgroundRequestHandler } from '../router';
|
||||
import { ok } from '../response';
|
||||
import { getState } from '@/platform/storage/state';
|
||||
import { resolveUserAgent, userAgentHostname } from '@/features/identity/user-agent';
|
||||
import {
|
||||
applyUserAgentToSite,
|
||||
deleteUserAgentProfile,
|
||||
resetUserAgentForSite,
|
||||
saveUserAgentProfile,
|
||||
} from '@/features/identity/user-agent-service';
|
||||
import { getUserAgentProfiles } from '@/features/identity/user-agent-profiles';
|
||||
import { appendAuditEvent } from '@/features/diagnostics/audit';
|
||||
|
||||
export const handleUserAgentRequest: BackgroundRequestHandler = async (request) => {
|
||||
switch (request.action) {
|
||||
case 'ua.catalog': {
|
||||
const state = await getState();
|
||||
return ok(getUserAgentProfiles(state.customUserAgentProfiles));
|
||||
}
|
||||
case 'ua.resolve': {
|
||||
const state = await getState();
|
||||
return ok(resolveUserAgent(
|
||||
request.payload.url,
|
||||
state.userAgentAssignments,
|
||||
state.customUserAgentProfiles,
|
||||
));
|
||||
}
|
||||
case 'ua.profile.save': {
|
||||
const { profile } = await saveUserAgentProfile(request.payload);
|
||||
void appendAuditEvent({
|
||||
category: 'settings',
|
||||
action: 'ua.profile.save',
|
||||
outcome: 'success',
|
||||
summary: profile.name,
|
||||
});
|
||||
return ok(profile);
|
||||
}
|
||||
case 'ua.profile.delete': {
|
||||
const state = await deleteUserAgentProfile(request.payload.id);
|
||||
void appendAuditEvent({
|
||||
category: 'settings', action: 'ua.profile.delete', outcome: 'success',
|
||||
});
|
||||
return ok(state);
|
||||
}
|
||||
case 'ua.site.apply': {
|
||||
const input = request.payload;
|
||||
const hostname = userAgentHostname(input.url);
|
||||
const state = await applyUserAgentToSite(input.url, input.profileId);
|
||||
const profile = getUserAgentProfiles(state.customUserAgentProfiles)
|
||||
.find((item) => item.id === input.profileId)!;
|
||||
void appendAuditEvent({
|
||||
category: 'settings',
|
||||
action: 'ua.site.apply',
|
||||
outcome: 'success',
|
||||
summary: `${hostname} · ${profile.name}`,
|
||||
});
|
||||
return ok(state);
|
||||
}
|
||||
case 'ua.site.reset': {
|
||||
const hostname = userAgentHostname(request.payload.url);
|
||||
const state = await resetUserAgentForSite(request.payload.url);
|
||||
void appendAuditEvent({
|
||||
category: 'settings',
|
||||
action: 'ua.site.reset',
|
||||
outcome: 'success',
|
||||
summary: hostname,
|
||||
});
|
||||
return ok(state);
|
||||
}
|
||||
default: return undefined;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,560 @@
|
||||
import { browser, type Browser } from 'wxt/browser';
|
||||
import {
|
||||
clearNetworkRequests, exportNetworkRequest, listNetworkRequests, networkCaptureStatus,
|
||||
rebindNetworkCapturesForGrant, startNetworkCapture, stopNetworkCapture, stopNetworkCapturesForGrant,
|
||||
} from '@/features/network-capture/service';
|
||||
import { capturedRequestEnginePayload } from '@/features/network-capture/workflows';
|
||||
import { initializeBrowserRecordingService, stopBrowserRecordingsForGrant } from '@/features/browser-recording/service';
|
||||
import { initializeDeepCaptureService, stopDeepCapturesForGrant } from '@/features/deep-capture/service';
|
||||
import { initializeBrowserTransformService } from '@/features/browser-transform/service';
|
||||
import { initializeFloatingPanelLifecycle } from '@/features/floating-panel/lifecycle';
|
||||
import type { ExtensionRequest, ExtensionResponse } from '@/types/messages';
|
||||
import { parseExtensionRequest } from '@/protocol/extension';
|
||||
import type {
|
||||
BridgeGrantTarget, BrowserRequestAnalysisBundle, BrowserTarget, YakPocGenerateResult, YakitFuzzerOpenResult,
|
||||
} from '@/types/models';
|
||||
import { engineBridge } from '@/features/engine-bridge/service';
|
||||
import { getFrameInventory } from '@/features/page-context/frames';
|
||||
import { getActiveTab, getTab } from '@/platform/browser/targets';
|
||||
import {
|
||||
actOnPageNode, capturePageContext, evalInPage, inspectPageNode, invokePageFunction,
|
||||
} from '@/features/page-context/service';
|
||||
import { getState, updateState } from '@/platform/storage/state';
|
||||
import {
|
||||
reconcileUserAgentRuntime,
|
||||
} from '@/features/identity/user-agent-service';
|
||||
import { errorCode, ExtensionError } from '@/shared/errors';
|
||||
import { appendAuditEvent, clearAuditEvents, listAuditEvents } from '@/features/diagnostics/audit';
|
||||
import {
|
||||
clearAgentActions, getAgentRuntime, setAgentRuntimeState,
|
||||
} from '@/features/agent-runtime/service';
|
||||
import {
|
||||
configureGrantLifecycleHooks, currentActiveGrant, rebindGrantTargets,
|
||||
registerGrantLifecycleListeners, replaceActiveGrant, requireActiveGrant,
|
||||
restoreGrantLifecycle, revokeActiveGrant,
|
||||
} from '@/features/grants/lifecycle';
|
||||
import {
|
||||
applyPolicyToBridge, applyPolicyToState, assertGrantPolicy, getEnterprisePolicy,
|
||||
} from '@/platform/policy/managed';
|
||||
import {
|
||||
browserInstanceAccess, PAIRED_BROWSER_INSTANCE_ACCESS_ID,
|
||||
} from '@/features/grants/capability-context';
|
||||
import { createDiagnosticsBundle } from '@/features/diagnostics/export';
|
||||
import { getRuntimeMetrics, recordServiceWorkerStart, resetRuntimeMetrics } from '@/features/diagnostics/metrics';
|
||||
import {
|
||||
configureAuthorizationPageContextCapture,
|
||||
createBrowserIsolationProof,
|
||||
deleteFirefoxContainerIdentity,
|
||||
inspectBrowserIsolation,
|
||||
listFirefoxContainerIdentities,
|
||||
openFirefoxContainerIdentity,
|
||||
openIncognitoIdentity,
|
||||
resolveTabCookieStoreId,
|
||||
} from '@/features/authorization-testing/isolation';
|
||||
import { ok, fail } from './response';
|
||||
import {
|
||||
requestTarget,
|
||||
requiredRequestTarget,
|
||||
senderBoundTabId,
|
||||
targetTabId,
|
||||
} from './request-context';
|
||||
import { dispatchBackgroundHandlers, type BackgroundRequestHandler } from './router';
|
||||
import { handleProxyRequest } from './handlers/proxy';
|
||||
import { handleCookieRequest } from './handlers/cookies';
|
||||
import { handleUserAgentRequest } from './handlers/user-agent';
|
||||
import { handleRecordingRequest } from './handlers/recording';
|
||||
import { handleTransformRequest } from './handlers/transform';
|
||||
|
||||
function originOf(url: string): string {
|
||||
const parsed = new URL(url);
|
||||
if (!['http:', 'https:'].includes(parsed.protocol)) throw new Error('只能授权 HTTP(S) 标签页');
|
||||
return parsed.origin;
|
||||
}
|
||||
|
||||
async function syncManagedInstanceBadge(managedInstance?: { badge: string }): Promise<void> {
|
||||
const badge = managedInstance?.badge || '';
|
||||
await browser.action.setBadgeText({ text: badge });
|
||||
if (badge) {
|
||||
const color = badge === 'A' ? '#F26215' : badge === 'B' ? '#2563EB' : badge === 'C' ? '#16A34A' : '#7C3AED';
|
||||
await browser.action.setBadgeBackgroundColor({ color });
|
||||
}
|
||||
await browser.action.setTitle({ title: badge ? `Yakit Browser Agent · 实例 ${badge}` : 'Yakit Browser Agent' });
|
||||
}
|
||||
|
||||
async function createGrantTargets(inputs: Array<{ tabId: number; frameId: number }>): Promise<BridgeGrantTarget[]> {
|
||||
const unique = [...new Map(inputs.map((target) => [`${target.tabId}:${target.frameId}`, target])).values()];
|
||||
const tabIds = [...new Set(unique.map((target) => target.tabId))];
|
||||
const inventories = new Map(await Promise.all(tabIds.map(async (tabId) => [tabId, await getFrameInventory(tabId)] as const)));
|
||||
return Promise.all(unique.map(async (input) => {
|
||||
const tab = await getTab(input.tabId);
|
||||
if (!tab.isolationContextId) {
|
||||
throw new ExtensionError(
|
||||
'isolation_unavailable',
|
||||
`标签页 ${input.tabId} 无法确认身份隔离上下文,不能加入共享会话`,
|
||||
);
|
||||
}
|
||||
const frame = inventories.get(input.tabId)?.find((item) => item.frameId === input.frameId);
|
||||
if (!frame?.accessible || !frame.documentId || !frame.origin) {
|
||||
throw new ExtensionError('target_unavailable', `Frame ${input.frameId} 当前不可访问,不能加入共享会话`);
|
||||
}
|
||||
originOf(`${frame.origin}/`);
|
||||
return {
|
||||
tabId: input.tabId,
|
||||
frameId: frame.frameId,
|
||||
documentId: frame.documentId,
|
||||
isolationContextId: tab.isolationContextId,
|
||||
cookieStoreId: tab.cookieStoreId,
|
||||
origin: frame.origin,
|
||||
grantedUrl: frame.url,
|
||||
title: frame.isTop ? tab.title : `${tab.title} · ${frame.title || frame.name || `Frame ${frame.frameId}`}`,
|
||||
};
|
||||
}));
|
||||
}
|
||||
|
||||
const domainHandlers: readonly BackgroundRequestHandler[] = [
|
||||
handleProxyRequest,
|
||||
handleCookieRequest,
|
||||
handleUserAgentRequest,
|
||||
handleRecordingRequest,
|
||||
handleTransformRequest,
|
||||
];
|
||||
|
||||
const stopPairedBrowserTasks = () => Promise.all([
|
||||
stopNetworkCapturesForGrant(PAIRED_BROWSER_INSTANCE_ACCESS_ID),
|
||||
stopBrowserRecordingsForGrant(PAIRED_BROWSER_INSTANCE_ACCESS_ID),
|
||||
stopDeepCapturesForGrant(PAIRED_BROWSER_INSTANCE_ACCESS_ID),
|
||||
]);
|
||||
|
||||
async function handleRequest(request: ExtensionRequest, sender: Browser.runtime.MessageSender): Promise<ExtensionResponse> {
|
||||
const domainResponse = await dispatchBackgroundHandlers(request, sender, domainHandlers);
|
||||
if (domainResponse !== undefined) return domainResponse;
|
||||
|
||||
switch (request.action) {
|
||||
case 'state.get': {
|
||||
await currentActiveGrant();
|
||||
return ok(await getState());
|
||||
}
|
||||
case 'tab.active': {
|
||||
const boundTabId = senderBoundTabId(sender);
|
||||
return ok(boundTabId ? await getTab(boundTabId) : await getActiveTab());
|
||||
}
|
||||
case 'tab.get': return ok(await getTab(targetTabId(request.payload.tabId, sender)));
|
||||
case 'tab.list': return ok((await inspectBrowserIsolation()).tabs);
|
||||
case 'frame.list': return ok(await getFrameInventory(targetTabId(request.payload.tabId, sender)!));
|
||||
case 'isolation.inspect': return ok(await inspectBrowserIsolation(request.payload.tabIds));
|
||||
case 'isolation.proof.create': return ok(await createBrowserIsolationProof(
|
||||
request.payload.leftTabId,
|
||||
request.payload.rightTabId,
|
||||
));
|
||||
case 'isolation.incognito.open': return ok(await openIncognitoIdentity(request.payload.url));
|
||||
case 'isolation.container.open': return ok(await openFirefoxContainerIdentity(request.payload));
|
||||
case 'isolation.container.list': return ok(await listFirefoxContainerIdentities());
|
||||
case 'isolation.container.remove': return ok(await deleteFirefoxContainerIdentity(
|
||||
request.payload.cookieStoreId,
|
||||
));
|
||||
case 'authorization.engine.task': {
|
||||
const encodedBytes = new TextEncoder().encode(JSON.stringify(request.payload.payload)).byteLength;
|
||||
if (encodedBytes > 256 * 1024) {
|
||||
throw new ExtensionError('payload_too_large', '授权测试任务参数不能超过 256 KiB');
|
||||
}
|
||||
return ok(await engineBridge.requestEngine(
|
||||
'yakit.browser_authorization.task',
|
||||
{ schema: request.payload.schema, payload: request.payload.payload },
|
||||
request.payload.timeoutMs,
|
||||
));
|
||||
}
|
||||
case 'authorization.yakit.open':
|
||||
return ok(await engineBridge.requestEngine(
|
||||
'yakit.browser_authorization.open',
|
||||
{ workspaceId: request.payload.workspaceId },
|
||||
));
|
||||
case 'context.capture': {
|
||||
const { tabId, frameId, documentId, ...options } = request.payload;
|
||||
const target = await requiredRequestTarget({ tabId, frameId, documentId }, sender);
|
||||
const context = await capturePageContext(options, target);
|
||||
void appendAuditEvent({
|
||||
category: 'capability', action: 'context.capture', outcome: 'success', targetTabId: target.tabId,
|
||||
summary: `${context.document.interactive.length} 个节点,${context.diff.kind}`,
|
||||
});
|
||||
return ok(context);
|
||||
}
|
||||
case 'context.node.inspect': {
|
||||
const input = request.payload;
|
||||
const target = await requiredRequestTarget(input, sender);
|
||||
return ok(await inspectPageNode(input.captureId, input.nodeId, target));
|
||||
}
|
||||
case 'context.node.action': {
|
||||
const input = request.payload;
|
||||
const target = await requiredRequestTarget(input, sender);
|
||||
const result = await actOnPageNode(input.captureId, input.nodeId, input.action, target, input.value);
|
||||
void appendAuditEvent({
|
||||
category: 'capability', action: `context.node.${input.action}`, outcome: 'success', targetTabId: target.tabId,
|
||||
summary: input.nodeId,
|
||||
});
|
||||
return ok(result);
|
||||
}
|
||||
case 'context.invoke': {
|
||||
const input = request.payload;
|
||||
return ok(await invokePageFunction(input.path, input.args, await requestTarget(input, sender), input.timeoutMs));
|
||||
}
|
||||
case 'context.eval': {
|
||||
const input = request.payload;
|
||||
return ok(await evalInPage(input.code, input.mode, await requestTarget(input, sender), input.timeoutMs));
|
||||
}
|
||||
case 'panel.update': {
|
||||
const input = request.payload;
|
||||
const policy = (await getEnterprisePolicy()).policy;
|
||||
return ok(await updateState((current) => applyPolicyToState({
|
||||
...current, floatingPanel: {
|
||||
enabled: input.enabled ?? current.floatingPanel.enabled,
|
||||
side: input.side ?? current.floatingPanel.side,
|
||||
y: typeof input.y === 'number' ? Math.min(Math.max(input.y, 0.08), 0.92) : current.floatingPanel.y,
|
||||
displayMode: input.displayMode ?? current.floatingPanel.displayMode,
|
||||
siteMode: input.siteMode ?? current.floatingPanel.siteMode,
|
||||
siteOrigins: input.siteOrigins
|
||||
? [...new Set(input.siteOrigins.map((origin) => new URL(origin).origin))]
|
||||
: current.floatingPanel.siteOrigins,
|
||||
shortcutEnabled: input.shortcutEnabled ?? current.floatingPanel.shortcutEnabled,
|
||||
autoCollapseFullscreen: input.autoCollapseFullscreen ?? current.floatingPanel.autoCollapseFullscreen,
|
||||
},
|
||||
}, policy)));
|
||||
}
|
||||
case 'grant.create': {
|
||||
const input = request.payload;
|
||||
const boundTabId = senderBoundTabId(sender);
|
||||
if (boundTabId && input.targets.some((target) => target.tabId !== boundTabId)) {
|
||||
throw new Error('页面内请求只能授权当前标签页');
|
||||
}
|
||||
const now = Date.now();
|
||||
const targets = await createGrantTargets(input.targets);
|
||||
const policy = (await getEnterprisePolicy()).policy;
|
||||
const durationMinutes = assertGrantPolicy(policy, {
|
||||
durationMinutes: input.durationMinutes,
|
||||
origins: targets.map((target) => target.origin),
|
||||
programEval: input.scopes.includes('browser.page.eval.program'),
|
||||
});
|
||||
const { state } = await replaceActiveGrant({
|
||||
id: crypto.randomUUID(),
|
||||
taskId: input.taskId || `manual-${crypto.randomUUID()}`,
|
||||
targets,
|
||||
scopes: [...new Set(input.scopes)],
|
||||
createdAt: now,
|
||||
expiresAt: now + durationMinutes * 60_000,
|
||||
});
|
||||
void appendAuditEvent({
|
||||
category: 'grant', action: 'grant.create', outcome: 'success', taskId: state.activeGrant?.taskId,
|
||||
targetTabId: state.activeGrant?.targets[0]?.tabId,
|
||||
summary: `${state.activeGrant?.targets.length || 0} 个标签页,${state.activeGrant?.scopes.length || 0} 项能力`,
|
||||
});
|
||||
return ok(state);
|
||||
}
|
||||
case 'grant.refresh': {
|
||||
if (senderBoundTabId(sender) !== undefined) {
|
||||
throw new ExtensionError('permission_denied', '只有扩展工作区可以续接共享会话');
|
||||
}
|
||||
const grant = await requireActiveGrant();
|
||||
const targets = await createGrantTargets(
|
||||
grant.targets.map((target) => ({ tabId: target.tabId, frameId: target.frameId })),
|
||||
);
|
||||
for (const target of targets) {
|
||||
const previous = grant.targets.find((item) => (
|
||||
item.tabId === target.tabId && item.frameId === target.frameId
|
||||
));
|
||||
if (!previous) {
|
||||
throw new ExtensionError('target_denied', '续接结果包含未授权的页面');
|
||||
}
|
||||
if (
|
||||
previous.isolationContextId !== target.isolationContextId
|
||||
|| previous.cookieStoreId !== target.cookieStoreId
|
||||
) {
|
||||
throw new ExtensionError('isolation_stale', '页面的身份隔离上下文已经变化,请重新选择身份');
|
||||
}
|
||||
if (previous.origin !== target.origin) {
|
||||
throw new ExtensionError('origin_changed', '页面已经跨来源导航,请重新选择身份');
|
||||
}
|
||||
}
|
||||
const state = await rebindGrantTargets(grant.id, targets);
|
||||
await rebindNetworkCapturesForGrant(grant.id, targets);
|
||||
const refreshedDocuments = targets.filter((target) => {
|
||||
const previous = grant.targets.find((item) => (
|
||||
item.tabId === target.tabId && item.frameId === target.frameId
|
||||
));
|
||||
return previous?.documentId !== target.documentId;
|
||||
}).length;
|
||||
void appendAuditEvent({
|
||||
category: 'grant',
|
||||
action: 'grant.refresh',
|
||||
outcome: 'success',
|
||||
taskId: grant.taskId,
|
||||
targetTabId: targets[0]?.tabId,
|
||||
summary: refreshedDocuments > 0
|
||||
? `已受控续接 ${refreshedDocuments} 个同源页面文档`
|
||||
: '共享会话文档仍然有效',
|
||||
});
|
||||
return ok(state);
|
||||
}
|
||||
case 'grant.revoke': {
|
||||
const { state } = await revokeActiveGrant();
|
||||
return ok(state);
|
||||
}
|
||||
case 'handoff.resolve': {
|
||||
const input = request.payload;
|
||||
const state = await updateState((current) => {
|
||||
if (!current.handoff || current.handoff.id !== input.id || current.handoff.state !== 'waiting_for_user') {
|
||||
throw new ExtensionError('handoff_not_waiting', '人工接管请求不存在或已经结束');
|
||||
}
|
||||
return {
|
||||
...current,
|
||||
handoff: { ...current.handoff, state: input.outcome, resolvedAt: Date.now() },
|
||||
};
|
||||
});
|
||||
const handoff = state.handoff!;
|
||||
await setAgentRuntimeState(
|
||||
input.outcome === 'completed' ? 'running' : 'paused',
|
||||
await browserInstanceAccess('browser.tabs.read'),
|
||||
);
|
||||
await browser.action.setBadgeText({ text: '', tabId: handoff.target.tabId });
|
||||
engineBridge.emitEvent('browser.handoff.changed', handoff);
|
||||
void appendAuditEvent({
|
||||
category: 'handoff', action: `handoff.${input.outcome}`, outcome: input.outcome === 'completed' ? 'success' : 'cancelled',
|
||||
taskId: handoff.taskId, targetTabId: handoff.target.tabId,
|
||||
});
|
||||
return ok(state);
|
||||
}
|
||||
case 'network.capture.start': {
|
||||
const input = request.payload;
|
||||
const target = await requiredRequestTarget(input, sender);
|
||||
const grant = (await getState()).activeGrant;
|
||||
const grantTarget = grant?.targets.find((item) => (
|
||||
item.tabId === target.tabId
|
||||
&& item.frameId === target.frameId
|
||||
&& (!item.documentId || !target.documentId || item.documentId === target.documentId)
|
||||
));
|
||||
const owner: Parameters<typeof startNetworkCapture>[2] = grant && grantTarget
|
||||
? { kind: 'grant', grantId: grant.id, expiresAt: grant.expiresAt }
|
||||
: undefined;
|
||||
const status = await startNetworkCapture(target, input, owner);
|
||||
void appendAuditEvent({
|
||||
category: 'capability', action: 'network.capture.start', outcome: 'success', targetTabId: target.tabId,
|
||||
summary: input.captureHeaders || input.captureBody ? '包含用户明确启用的敏感字段' : '仅元数据',
|
||||
});
|
||||
return ok(status);
|
||||
}
|
||||
case 'network.capture.status': return ok(await networkCaptureStatus(await requiredRequestTarget(request.payload, sender)));
|
||||
case 'network.capture.list': {
|
||||
const target = await requiredRequestTarget(request.payload, sender);
|
||||
return ok(await listNetworkRequests(target, request.payload.limit));
|
||||
}
|
||||
case 'network.capture.clear': {
|
||||
const target = await requiredRequestTarget(request.payload, sender);
|
||||
const status = await clearNetworkRequests(target);
|
||||
void appendAuditEvent({ category: 'capability', action: 'network.capture.clear', outcome: 'success', targetTabId: target.tabId });
|
||||
return ok(status);
|
||||
}
|
||||
case 'network.capture.stop': {
|
||||
const target = await requiredRequestTarget(request.payload, sender);
|
||||
const status = await stopNetworkCapture(target);
|
||||
void appendAuditEvent({ category: 'capability', action: 'network.capture.stop', outcome: 'success', targetTabId: target.tabId });
|
||||
return ok(status);
|
||||
}
|
||||
case 'network.capture.export': {
|
||||
const target = await requiredRequestTarget(request.payload, sender);
|
||||
const exported = await exportNetworkRequest(target, request.payload.id);
|
||||
void appendAuditEvent({ category: 'capability', action: 'network.capture.export', outcome: 'success', targetTabId: target.tabId });
|
||||
return ok(exported);
|
||||
}
|
||||
case 'network.capture.send': {
|
||||
const target = await requiredRequestTarget(request.payload, sender);
|
||||
try {
|
||||
const exported = await exportNetworkRequest(target, request.payload.id);
|
||||
const result = await engineBridge.requestEngine<YakitFuzzerOpenResult>('yakit.web_fuzzer.open', {
|
||||
rawRequestBase64: exported.rawRequestBase64,
|
||||
isHttps: exported.isHttps,
|
||||
tabName: `Browser · ${new URL(exported.url).hostname}`,
|
||||
});
|
||||
void appendAuditEvent({
|
||||
category: 'capability', action: 'network.capture.send_to_fuzzer', outcome: 'success', targetTabId: target.tabId,
|
||||
summary: `Web Fuzzer ${result.pageId}`,
|
||||
});
|
||||
return ok(result);
|
||||
} catch (error) {
|
||||
void appendAuditEvent({
|
||||
category: 'capability', action: 'network.capture.send_to_fuzzer', outcome: 'error',
|
||||
targetTabId: target.tabId, errorCode: errorCode(error),
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
case 'network.capture.poc': {
|
||||
const target = await requiredRequestTarget(request.payload, sender);
|
||||
const result = await engineBridge.requestEngine<YakPocGenerateResult>(
|
||||
'yakit.poc.generate',
|
||||
await capturedRequestEnginePayload(target, request.payload.id, false),
|
||||
);
|
||||
void appendAuditEvent({ category: 'capability', action: 'network.capture.generate_poc', outcome: 'success', targetTabId: target.tabId });
|
||||
return ok(result);
|
||||
}
|
||||
case 'network.capture.analysis': {
|
||||
const target = await requiredRequestTarget(request.payload, sender);
|
||||
const result = await engineBridge.requestEngine<BrowserRequestAnalysisBundle>(
|
||||
'yakit.browser_request.prepare_analysis',
|
||||
await capturedRequestEnginePayload(target, request.payload.id, true),
|
||||
);
|
||||
void appendAuditEvent({ category: 'capability', action: 'network.capture.prepare_analysis', outcome: 'success', targetTabId: target.tabId });
|
||||
return ok(result);
|
||||
}
|
||||
case 'audit.list': return ok(await listAuditEvents(request.payload.limit));
|
||||
case 'audit.clear': {
|
||||
await clearAuditEvents();
|
||||
return ok();
|
||||
}
|
||||
case 'agent.runtime.get': return ok(await getAgentRuntime());
|
||||
case 'agent.pause': {
|
||||
const grant = await browserInstanceAccess('browser.tabs.read');
|
||||
engineBridge.cancelActiveRequests();
|
||||
await stopPairedBrowserTasks();
|
||||
const runtime = await setAgentRuntimeState('paused', grant);
|
||||
void appendAuditEvent({ category: 'grant', action: 'agent.pause', outcome: 'success', taskId: grant.taskId });
|
||||
return ok(runtime);
|
||||
}
|
||||
case 'agent.resume': {
|
||||
const grant = await browserInstanceAccess('browser.tabs.read');
|
||||
const runtime = await setAgentRuntimeState('running', grant);
|
||||
void appendAuditEvent({ category: 'grant', action: 'agent.resume', outcome: 'success', taskId: grant.taskId });
|
||||
return ok(runtime);
|
||||
}
|
||||
case 'agent.actions.clear': return ok(await clearAgentActions());
|
||||
case 'policy.status': return ok(await getEnterprisePolicy());
|
||||
case 'diagnostics.export': return ok(await createDiagnosticsBundle(engineBridge.getStatus()));
|
||||
case 'metrics.get': return ok(await getRuntimeMetrics());
|
||||
case 'metrics.reset': return ok(await resetRuntimeMetrics());
|
||||
case 'bridge.config.save': {
|
||||
const config = applyPolicyToBridge(request.payload, (await getEnterprisePolicy()).policy);
|
||||
const state = await updateState((current) => ({ ...current, bridge: config }));
|
||||
await syncManagedInstanceBadge(state.bridge.managedInstance);
|
||||
if (config.autoConnect && config.pairedEngine) await engineBridge.connect(config);
|
||||
else engineBridge.disconnect();
|
||||
return ok(state);
|
||||
}
|
||||
case 'bridge.managed-instance.bind': {
|
||||
const senderURL = sender.url ? new URL(sender.url) : undefined;
|
||||
const bootstrapURL = new URL(browser.runtime.getURL('/ytray-bootstrap.html'));
|
||||
if (senderURL?.origin !== bootstrapURL.origin || senderURL.pathname !== bootstrapURL.pathname) {
|
||||
throw new ExtensionError('forbidden', '浏览器实例身份只能由受管启动页设置');
|
||||
}
|
||||
const state = await updateState((current) => ({
|
||||
...current,
|
||||
bridge: { ...current.bridge, managedInstance: request.payload },
|
||||
}));
|
||||
await syncManagedInstanceBadge(state.bridge.managedInstance);
|
||||
if (state.bridge.autoConnect && state.bridge.pairedEngine) {
|
||||
engineBridge.disconnect();
|
||||
await stopPairedBrowserTasks();
|
||||
await engineBridge.connect(state.bridge);
|
||||
}
|
||||
return ok(engineBridge.getStatus());
|
||||
}
|
||||
case 'bridge.pair': {
|
||||
const status = await engineBridge.startPairing();
|
||||
void appendAuditEvent({ category: 'bridge', action: 'bridge.pair', outcome: 'success' });
|
||||
return ok(status);
|
||||
}
|
||||
case 'bridge.pair.cancel': return ok(engineBridge.cancelPairing());
|
||||
case 'bridge.pair.status': return ok(engineBridge.getPairingStatus());
|
||||
case 'bridge.unpair': {
|
||||
await engineBridge.unpair();
|
||||
await stopPairedBrowserTasks();
|
||||
void appendAuditEvent({ category: 'bridge', action: 'bridge.unpair', outcome: 'success' });
|
||||
return ok(await getState());
|
||||
}
|
||||
case 'bridge.connect': {
|
||||
await engineBridge.connect();
|
||||
void appendAuditEvent({ category: 'bridge', action: 'bridge.connect', outcome: 'success' });
|
||||
return ok(engineBridge.getStatus());
|
||||
}
|
||||
case 'bridge.disconnect': {
|
||||
engineBridge.disconnect();
|
||||
await stopPairedBrowserTasks();
|
||||
void appendAuditEvent({ category: 'bridge', action: 'bridge.disconnect', outcome: 'success' });
|
||||
return ok(engineBridge.getStatus());
|
||||
}
|
||||
case 'bridge.status': return ok(engineBridge.getStatus());
|
||||
default: return fail('未知扩展操作');
|
||||
}
|
||||
}
|
||||
|
||||
let backgroundStarted = false;
|
||||
|
||||
async function restoreBackgroundState(): Promise<void> {
|
||||
const storedState = await restoreGrantLifecycle();
|
||||
const policy = (await getEnterprisePolicy()).policy;
|
||||
const state = applyPolicyToState(storedState, policy);
|
||||
if (JSON.stringify(state.bridge) !== JSON.stringify(storedState.bridge)
|
||||
|| JSON.stringify(state.floatingPanel) !== JSON.stringify(storedState.floatingPanel)) {
|
||||
await updateState((current) => applyPolicyToState(current, policy));
|
||||
}
|
||||
try {
|
||||
await reconcileUserAgentRuntime();
|
||||
} catch (error) {
|
||||
console.error('User-Agent runtime restoration failed', error);
|
||||
void appendAuditEvent({
|
||||
category: 'settings',
|
||||
action: 'ua.runtime.restore',
|
||||
outcome: 'error',
|
||||
errorCode: errorCode(error),
|
||||
summary: (error instanceof Error ? error.message : String(error)).slice(0, 512),
|
||||
});
|
||||
}
|
||||
const currentState = await getState();
|
||||
await syncManagedInstanceBadge(currentState.bridge.managedInstance);
|
||||
if (currentState.bridge.autoConnect && currentState.bridge.pairedEngine) {
|
||||
await engineBridge.connect(currentState.bridge).catch(console.error);
|
||||
}
|
||||
}
|
||||
|
||||
export function runBackground(): void {
|
||||
if (backgroundStarted) return;
|
||||
backgroundStarted = true;
|
||||
|
||||
configureGrantLifecycleHooks({
|
||||
emitHandoffChanged: (handoff) => engineBridge.emitEvent('browser.handoff.changed', handoff),
|
||||
});
|
||||
registerGrantLifecycleListeners();
|
||||
|
||||
browser.runtime.onMessage.addListener((
|
||||
input: unknown,
|
||||
sender: Browser.runtime.MessageSender,
|
||||
sendResponse,
|
||||
) => {
|
||||
if ([
|
||||
'bridge.status.changed',
|
||||
'bridge.pairing.status.changed',
|
||||
'network.capture.changed',
|
||||
'deep.capture.changed',
|
||||
].includes((input as { action?: string })?.action || '')) return undefined;
|
||||
void Promise.resolve()
|
||||
.then(() => parseExtensionRequest(input))
|
||||
.then((request) => handleRequest(request, sender))
|
||||
.then(sendResponse)
|
||||
.catch((error) => sendResponse(fail(error)));
|
||||
return true;
|
||||
});
|
||||
|
||||
configureAuthorizationPageContextCapture(capturePageContext);
|
||||
recordServiceWorkerStart();
|
||||
initializeBrowserRecordingService();
|
||||
initializeFloatingPanelLifecycle();
|
||||
try {
|
||||
initializeDeepCaptureService();
|
||||
} catch (error) {
|
||||
console.error('Deep Capture initialization failed', error);
|
||||
}
|
||||
try {
|
||||
initializeBrowserTransformService();
|
||||
} catch (error) {
|
||||
console.error('Browser Transform initialization failed', error);
|
||||
}
|
||||
void restoreBackgroundState().catch((error) => {
|
||||
console.error('Background state restoration failed', error);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { browser, type Browser } from 'wxt/browser';
|
||||
import type { BrowserTarget } from '@/types/models';
|
||||
import { ExtensionError } from '@/shared/errors';
|
||||
import { resolveDocumentTarget } from '@/platform/browser/targets';
|
||||
|
||||
export function isFloatingSender(sender: Browser.runtime.MessageSender): boolean {
|
||||
try {
|
||||
const parsed = new URL(sender.url || '');
|
||||
return parsed.origin === new URL(browser.runtime.getURL('/')).origin
|
||||
&& parsed.pathname === '/floating.html';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function senderBoundTabId(sender: Browser.runtime.MessageSender): number | undefined {
|
||||
const extensionOrigin = new URL(browser.runtime.getURL('/')).origin;
|
||||
const senderUrl = sender.url || '';
|
||||
try {
|
||||
const parsed = new URL(senderUrl);
|
||||
if (parsed.origin === extensionOrigin && parsed.pathname !== '/floating.html') return undefined;
|
||||
} catch {
|
||||
// Non-URL senders remain bound to their browser tab below.
|
||||
}
|
||||
return sender.tab?.id;
|
||||
}
|
||||
|
||||
export function targetTabId(
|
||||
requested: number | undefined,
|
||||
sender: Browser.runtime.MessageSender,
|
||||
): number | undefined {
|
||||
const senderTabId = senderBoundTabId(sender);
|
||||
if (senderTabId && requested && senderTabId !== requested) {
|
||||
throw new ExtensionError('target_denied', '页面内请求不能操作其他标签页');
|
||||
}
|
||||
return senderTabId || requested;
|
||||
}
|
||||
|
||||
export async function requestTarget(
|
||||
input: { tabId?: number; frameId?: number; documentId?: string },
|
||||
sender: Browser.runtime.MessageSender,
|
||||
): Promise<BrowserTarget | undefined> {
|
||||
const boundTabId = senderBoundTabId(sender);
|
||||
if (boundTabId && input.tabId && boundTabId !== input.tabId) {
|
||||
throw new ExtensionError('target_denied', '页面内请求不能操作其他标签页');
|
||||
}
|
||||
if (boundTabId && !isFloatingSender(sender)) {
|
||||
const frameId = sender.frameId ?? 0;
|
||||
if (input.frameId !== undefined && input.frameId !== frameId) {
|
||||
throw new ExtensionError('target_denied', '页面内请求不能操作其他 frame');
|
||||
}
|
||||
if (input.documentId && sender.documentId && input.documentId !== sender.documentId) {
|
||||
throw new ExtensionError('stale_document', '目标页面已经刷新或导航,请重新选择');
|
||||
}
|
||||
return { tabId: boundTabId, frameId, documentId: sender.documentId };
|
||||
}
|
||||
const tabId = boundTabId || input.tabId;
|
||||
if (!tabId) return undefined;
|
||||
return resolveDocumentTarget({
|
||||
tabId,
|
||||
frameId: input.frameId ?? 0,
|
||||
documentId: input.documentId,
|
||||
});
|
||||
}
|
||||
|
||||
export async function requiredRequestTarget(
|
||||
input: { tabId?: number; frameId?: number; documentId?: string },
|
||||
sender: Browser.runtime.MessageSender,
|
||||
): Promise<BrowserTarget> {
|
||||
const target = await requestTarget(input, sender);
|
||||
if (!target) {
|
||||
throw new ExtensionError('target_unavailable', '请选择一个可访问的 HTTP(S) 标签页');
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
export async function requiredDebuggerTarget(
|
||||
input: { tabId?: number; frameId?: number; documentId?: string },
|
||||
sender: Browser.runtime.MessageSender,
|
||||
): Promise<BrowserTarget> {
|
||||
const boundTabId = senderBoundTabId(sender);
|
||||
if (boundTabId && input.tabId && boundTabId !== input.tabId) {
|
||||
throw new ExtensionError('target_denied', '页面内请求不能操作其他标签页');
|
||||
}
|
||||
const tabId = boundTabId || input.tabId;
|
||||
if (!tabId) {
|
||||
throw new ExtensionError('target_unavailable', '请选择一个可访问的 HTTP(S) 标签页');
|
||||
}
|
||||
const frameId = boundTabId && !isFloatingSender(sender)
|
||||
? sender.frameId ?? 0
|
||||
: input.frameId ?? 0;
|
||||
if (boundTabId && !isFloatingSender(sender)
|
||||
&& input.frameId !== undefined && input.frameId !== frameId) {
|
||||
throw new ExtensionError('target_denied', '页面内请求不能操作其他 frame');
|
||||
}
|
||||
const frame = await browser.webNavigation.getFrame({ tabId, frameId });
|
||||
if (!frame) throw new ExtensionError('target_unavailable', '目标 frame 已不存在');
|
||||
if (input.documentId && frame.documentId && input.documentId !== frame.documentId) {
|
||||
throw new ExtensionError('stale_document', '目标页面已经刷新或导航');
|
||||
}
|
||||
return { tabId, frameId, documentId: frame.documentId || input.documentId };
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { ExtensionResponse } from '@/types/messages';
|
||||
import { errorCode, ExtensionError } from '@/shared/errors';
|
||||
|
||||
export function ok<T>(data?: T): ExtensionResponse<T> {
|
||||
return { ok: true, data };
|
||||
}
|
||||
|
||||
export function fail(error: unknown): ExtensionResponse {
|
||||
return {
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
errorCode: errorCode(error),
|
||||
errorData: error instanceof ExtensionError ? error.details : undefined,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import type { Browser } from 'wxt/browser';
|
||||
import type { BackgroundRequestHandler } from './router';
|
||||
import { dispatchBackgroundHandlers } from './router';
|
||||
|
||||
describe('background domain router', () => {
|
||||
it('stops at the first domain that owns an action', async () => {
|
||||
const first: BackgroundRequestHandler = vi.fn(async () => undefined);
|
||||
const second: BackgroundRequestHandler = vi.fn(async () => ({ ok: true, data: 'handled' }));
|
||||
const third: BackgroundRequestHandler = vi.fn(async () => ({ ok: true, data: 'wrong' }));
|
||||
const request = { action: 'state.get' as const };
|
||||
const sender = {} as Browser.runtime.MessageSender;
|
||||
|
||||
await expect(dispatchBackgroundHandlers(request, sender, [first, second, third]))
|
||||
.resolves.toEqual({ ok: true, data: 'handled' });
|
||||
expect(first).toHaveBeenCalledOnce();
|
||||
expect(second).toHaveBeenCalledOnce();
|
||||
expect(third).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns undefined when no domain owns the action', async () => {
|
||||
const handler: BackgroundRequestHandler = vi.fn(async () => undefined);
|
||||
await expect(dispatchBackgroundHandlers(
|
||||
{ action: 'state.get' },
|
||||
{} as Browser.runtime.MessageSender,
|
||||
[handler],
|
||||
)).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { Browser } from 'wxt/browser';
|
||||
import type { ExtensionRequest, ExtensionResponse } from '@/types/messages';
|
||||
|
||||
export type BackgroundRequestHandler = (
|
||||
request: ExtensionRequest,
|
||||
sender: Browser.runtime.MessageSender,
|
||||
) => Promise<ExtensionResponse | undefined>;
|
||||
|
||||
export async function dispatchBackgroundHandlers(
|
||||
request: ExtensionRequest,
|
||||
sender: Browser.runtime.MessageSender,
|
||||
handlers: readonly BackgroundRequestHandler[],
|
||||
): Promise<ExtensionResponse | undefined> {
|
||||
for (const handler of handlers) {
|
||||
const response = await handler(request, sender);
|
||||
if (response !== undefined) return response;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@@ -1,168 +0,0 @@
|
||||
import Icon from "@ant-design/icons";
|
||||
import { CustomIconComponentProps } from "@ant-design/icons/lib/components/Icon";
|
||||
import React from "react";
|
||||
|
||||
interface IconProps extends CustomIconComponentProps {
|
||||
onClick: (e: React.MouseEvent) => void;
|
||||
ref?: any;
|
||||
}
|
||||
|
||||
const X = () => (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 16 16"
|
||||
fill="none"
|
||||
>
|
||||
<path
|
||||
d="M4 12L12 4M4 4L12 12"
|
||||
stroke="currentColor"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
/**
|
||||
* @description Icon/Outline/x
|
||||
*/
|
||||
export const XIcon = (props: Partial<IconProps>) => {
|
||||
return <Icon component={X} {...props} />;
|
||||
};
|
||||
|
||||
const Check = () => (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 16 16"
|
||||
fill="none"
|
||||
>
|
||||
<path
|
||||
d="M3.33337 8.66669L6.00004 11.3334L12.6667 4.66669"
|
||||
stroke="#56C991"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
/**
|
||||
* @description Icon/Outline/check
|
||||
*/
|
||||
export const CheckIcon = (props: Partial<IconProps>) => {
|
||||
return <Icon component={Check} {...props} />;
|
||||
};
|
||||
|
||||
const PencilAlt = () => (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 16 16"
|
||||
fill="none"
|
||||
>
|
||||
<path
|
||||
d="M7.33329 3.33334H3.99996C3.26358 3.33334 2.66663 3.93029 2.66663 4.66667V12C2.66663 12.7364 3.26358 13.3333 3.99996 13.3333H11.3333C12.0697 13.3333 12.6666 12.7364 12.6666 12V8.66667M11.7238 2.39052C12.2445 1.86983 13.0887 1.86983 13.6094 2.39052C14.1301 2.91122 14.1301 3.75544 13.6094 4.27614L7.88557 10H5.99996L5.99996 8.11438L11.7238 2.39052Z"
|
||||
stroke="currentColor"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
/**
|
||||
* @description Icon/Outline/pencil-alt
|
||||
*/
|
||||
export const PencilAltIcon = (props: Partial<IconProps>) => {
|
||||
return <Icon component={PencilAlt} {...props} />;
|
||||
};
|
||||
|
||||
const Refresh = () => (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 16 16"
|
||||
fill="none"
|
||||
>
|
||||
<path
|
||||
d="M2.66663 2.66669V6.00002H3.0543M13.292 7.33335C12.964 4.70248 10.7197 2.66669 7.99996 2.66669C5.76171 2.66669 3.84549 4.04547 3.0543 6.00002M3.0543 6.00002H5.99996M13.3333 13.3334V10H12.9456M12.9456 10C12.1544 11.9546 10.2382 13.3334 7.99996 13.3334C5.28021 13.3334 3.03595 11.2976 2.70789 8.66669M12.9456 10H9.99996"
|
||||
stroke="currentColor"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
/**
|
||||
* @description Icon/Outline/refresh
|
||||
*/
|
||||
export const RefreshIcon = (props: Partial<IconProps>) => {
|
||||
return <Icon component={Refresh} {...props} />;
|
||||
};
|
||||
|
||||
const Exit = () => (
|
||||
<svg
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
d="M9.33333 6.66668C9.10226 6.78107 8.87965 6.90988 8.66667 7.0519C7.05869 8.12418 6 9.95027 6 12.0227C6 15.3239 8.68629 18 12 18C15.3137 18 18 15.3239 18 12.0227C18 9.95027 16.9413 8.12418 15.3333 7.0519C15.1204 6.90988 14.8977 6.78107 14.6667 6.66668M12 5.33334V10.6667"
|
||||
stroke="#F7544A"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
/**
|
||||
* @description 退出
|
||||
*/
|
||||
export const ExitIcon = (props: Partial<IconProps>) => {
|
||||
return <Icon component={Exit} {...props} />;
|
||||
};
|
||||
|
||||
const PlusSm = () => (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 16 16"
|
||||
fill="none"
|
||||
>
|
||||
<path
|
||||
d="M8 4V8M8 8V12M8 8H12M8 8L4 8"
|
||||
stroke="currentColor"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
/**
|
||||
* @description Icon/Outline/plus-sm
|
||||
*/
|
||||
export const PlusSmIcon = (props: Partial<IconProps>) => {
|
||||
return <Icon component={PlusSm} {...props} />;
|
||||
};
|
||||
|
||||
const Trash = () => (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 16 16"
|
||||
fill="none"
|
||||
>
|
||||
<path
|
||||
d="M12.6666 4.66667L12.0884 12.7617C12.0386 13.4594 11.458 14 10.7585 14H5.24145C4.54193 14 3.96135 13.4594 3.91151 12.7617L3.33329 4.66667M6.66663 7.33333V11.3333M9.33329 7.33333V11.3333M9.99996 4.66667V2.66667C9.99996 2.29848 9.70148 2 9.33329 2H6.66663C6.29844 2 5.99996 2.29848 5.99996 2.66667V4.66667M2.66663 4.66667H13.3333"
|
||||
stroke="#F7544A"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
/**
|
||||
* @description Icon/Outline/trash
|
||||
*/
|
||||
export const TrashIcon = (props: Partial<IconProps>) => {
|
||||
return <Icon component={Trash} {...props} />;
|
||||
};
|
||||
@@ -1,73 +0,0 @@
|
||||
.Contro {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
height: 40px;
|
||||
padding: 8px 16px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.Contro-error-bg {
|
||||
background-color: rgba(244, 115, 107, .10);
|
||||
}
|
||||
|
||||
.Contro-success-bg {
|
||||
background-color: rgba(86, 201, 145, .10);
|
||||
}
|
||||
|
||||
.Contro-cont-input {
|
||||
height: 24px;
|
||||
margin-right: 8px;
|
||||
}
|
||||
|
||||
.Contro-lable {
|
||||
color: #85899E;
|
||||
}
|
||||
|
||||
.Contro-cont {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.Contro-cont-text-error {
|
||||
color: #F6544A;
|
||||
}
|
||||
|
||||
.Contro-cont-text-success {
|
||||
color: #56C991;
|
||||
}
|
||||
|
||||
.Contro-handle-icon {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.Contro-handle-icon svg {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.contro-handle-icon-check {
|
||||
margin-left: 8px;
|
||||
}
|
||||
|
||||
.icon-p {
|
||||
display: inline-block;
|
||||
padding: 4px;
|
||||
}
|
||||
|
||||
.icon-p svg {
|
||||
color: #85899E;
|
||||
}
|
||||
|
||||
.Contro-cont span.anticon:hover {
|
||||
background: #F0F1F3;
|
||||
}
|
||||
|
||||
.grey-icon svg {
|
||||
color: #85899E;
|
||||
}
|
||||
|
||||
.icon-active:active svg {
|
||||
color: #F28B44;
|
||||
}
|
||||
@@ -1,191 +0,0 @@
|
||||
import React, {useEffect, useMemo, useRef, useState} from "react";
|
||||
import {Divider, Tooltip, Input} from "antd";
|
||||
import classNames from "classnames";
|
||||
import {
|
||||
CheckIcon,
|
||||
ExitIcon,
|
||||
PencilAltIcon,
|
||||
RefreshIcon,
|
||||
XIcon,
|
||||
} from "@assets/icon/icon";
|
||||
import {wsc} from "@network/chrome";
|
||||
import "./Contro.css";
|
||||
|
||||
interface ControProps {
|
||||
}
|
||||
|
||||
export const Contro: React.FC<ControProps> = () => {
|
||||
const [isEdit, setIsEdit] = useState<boolean>(false);
|
||||
const [connected, setConnected] = useState(false);
|
||||
const [autoFindFailedReason, setAutoFindFailedReason] = useState<string>("");
|
||||
const [enginePort, setEnginePort] = useState<string>("");
|
||||
const [enginePortTemp, setEnginePortTemp] = useState<string>(enginePort);
|
||||
const enginePortRef = useRef<string>(enginePort);
|
||||
|
||||
useEffect(() => {
|
||||
enginePortRef.current = enginePort;
|
||||
}, [enginePort]);
|
||||
|
||||
useEffect(() => {
|
||||
const yakitConnectInfo = localStorage.getItem("yakit-connect");
|
||||
if (!yakitConnectInfo) {
|
||||
findPort(11212, 11222);
|
||||
} else {
|
||||
const {port, connected} = JSON.parse(yakitConnectInfo);
|
||||
setConnected(connected);
|
||||
setEnginePort(port + "");
|
||||
setAutoFindFailedReason("");
|
||||
}
|
||||
|
||||
wsc.onWSCMessage((message) => {
|
||||
if (message.action === wsc.ActionType.STATUS) {
|
||||
if (message.connected === false) {
|
||||
handleConnectFail();
|
||||
} else {
|
||||
localStorage.setItem(
|
||||
"yakit-connect",
|
||||
JSON.stringify({connected: true, port: message.port})
|
||||
);
|
||||
setEnginePort(message.port + "");
|
||||
setConnected(true);
|
||||
setAutoFindFailedReason("");
|
||||
}
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
|
||||
const findPort = (port: number, max: number) => {
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${port}`);
|
||||
ws.onclose = (e: CloseEvent) => {
|
||||
if (enginePortRef.current) {
|
||||
handleConnectFail();
|
||||
return;
|
||||
}
|
||||
if (e.reason !== `FoundYakitWebSocketController` && port + 1 <= max) {
|
||||
setTimeout(() => findPort(port + 1, max), 200);
|
||||
}
|
||||
|
||||
if (port + 1 > max) {
|
||||
setConnected(false);
|
||||
setEnginePort("");
|
||||
setAutoFindFailedReason("Cannot found Yakit");
|
||||
localStorage.setItem("yakit-connect", "");
|
||||
}
|
||||
};
|
||||
ws.onopen = () => {
|
||||
setConnected(true);
|
||||
setEnginePort(port + "");
|
||||
ws.close(1000, "FoundYakitWebSocketController");
|
||||
connectPort(port);
|
||||
};
|
||||
};
|
||||
|
||||
const handleConnectFail = () => {
|
||||
setConnected(false);
|
||||
setAutoFindFailedReason("Yakit WebSocket Controller Connect Fail");
|
||||
localStorage.setItem("yakit-connect", "");
|
||||
};
|
||||
|
||||
const connectPort = (port: number) => {
|
||||
setAutoFindFailedReason("");
|
||||
wsc.connect(port);
|
||||
};
|
||||
|
||||
const safeConnected = useMemo(() => {
|
||||
return connected && enginePort;
|
||||
}, [connected, enginePort]);
|
||||
|
||||
const failConnected = useMemo(() => {
|
||||
return !connected && autoFindFailedReason;
|
||||
}, [connected, autoFindFailedReason]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{safeConnected || failConnected ? (
|
||||
<div
|
||||
className={classNames("Contro", {
|
||||
["Contro-success-bg"]: safeConnected,
|
||||
["Contro-error-bg"]: failConnected,
|
||||
})}
|
||||
>
|
||||
<div className="Contro-lable">Yakit 引擎连接状态:</div>
|
||||
<div className="Contro-cont">
|
||||
{isEdit ? (
|
||||
<>
|
||||
<Input
|
||||
rootClassName="Contro-cont-input"
|
||||
value={enginePortTemp}
|
||||
placeholder="输入范围 11212 - 11222"
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
setEnginePortTemp(value);
|
||||
}}
|
||||
/>
|
||||
<div className="Contro-handle-icon">
|
||||
<XIcon
|
||||
className="grey-icon icon-p icon-active"
|
||||
onClick={() => {
|
||||
setIsEdit(false);
|
||||
}}
|
||||
/>
|
||||
<CheckIcon
|
||||
className="contro-handle-icon-check icon-p"
|
||||
onClick={() => {
|
||||
if (enginePortTemp) {
|
||||
setIsEdit(false);
|
||||
setEnginePort(enginePortTemp);
|
||||
connectPort(Number(enginePortTemp));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div
|
||||
className={classNames("Contro-cont-text", {
|
||||
["Contro-cont-text-success"]: safeConnected,
|
||||
["Contro-cont-text-error"]: failConnected,
|
||||
})}
|
||||
>
|
||||
{safeConnected && "已连接(" + enginePort + ")"}
|
||||
{failConnected &&
|
||||
(enginePort
|
||||
? autoFindFailedReason + "(" + enginePort + ")"
|
||||
: autoFindFailedReason)}
|
||||
</div>
|
||||
<div className="Contro-handle-icon">
|
||||
<Tooltip title="修改监听端口">
|
||||
<PencilAltIcon
|
||||
className="grey-icon icon-p icon-active"
|
||||
onClick={() => {
|
||||
setIsEdit(true);
|
||||
setEnginePortTemp(enginePort);
|
||||
}}
|
||||
/>
|
||||
</Tooltip>
|
||||
<Divider type="vertical" style={{height: 16}}/>
|
||||
{safeConnected && (
|
||||
<ExitIcon onClick={() => wsc.disconnect()}/>
|
||||
)}
|
||||
{failConnected && (
|
||||
<RefreshIcon
|
||||
className="grey-icon icon-active"
|
||||
onClick={() => {
|
||||
if (enginePort) {
|
||||
connectPort(Number(enginePort));
|
||||
} else {
|
||||
findPort(11212, 11222);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
};
|
||||
@@ -1,77 +0,0 @@
|
||||
import React, {useEffect, useState} from "react";
|
||||
import {Button, Input} from "antd";
|
||||
import TextArea from "antd/lib/input/TextArea";
|
||||
import {wsc} from "@network/chrome";
|
||||
|
||||
interface EvalInTabProps {
|
||||
}
|
||||
|
||||
export const EvalInTab: React.FC<EvalInTabProps> = () => {
|
||||
const [funcName, setFuncName] = useState("");
|
||||
const [inputArgsData, setInputArgsData] = useState("");
|
||||
const [code, setCode] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
wsc.onWSCMessage((message) => {
|
||||
if (message.action === wsc.ActionType.TO_EXTENSION_PAGE) {
|
||||
console.log("res:", message.result);
|
||||
alert("from content script: " + JSON.stringify(message.result));
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleClick = async () => {
|
||||
try {
|
||||
const [tab] = await wsc.getTab();
|
||||
await chrome.runtime.sendMessage({
|
||||
action: wsc.ActionType.INJECT_SCRIPT,
|
||||
tabId: tab.id,
|
||||
value: {mode: "CONTENT_CALL_FUNCTION", fn_name: funcName, args: inputArgsData},
|
||||
});
|
||||
} catch (error) {
|
||||
}
|
||||
};
|
||||
|
||||
const handleInputChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||
setInputArgsData(event.target.value);
|
||||
};
|
||||
|
||||
|
||||
const handleEvalCodeClick = async () => {
|
||||
try {
|
||||
const [tab] = await wsc.getTab();
|
||||
await chrome.runtime.sendMessage({
|
||||
action: wsc.ActionType.INJECT_SCRIPT,
|
||||
tabId: tab.id,
|
||||
value: {
|
||||
mode: "CONTENT_EVAL_CODE",
|
||||
code: code,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Input
|
||||
value={funcName}
|
||||
onChange={(e) => setFuncName(e.target.value)}
|
||||
placeholder="Enter function name"
|
||||
></Input>
|
||||
<TextArea
|
||||
value={inputArgsData}
|
||||
onChange={handleInputChange}
|
||||
placeholder="Enter function args"
|
||||
/>
|
||||
<Button onClick={handleClick}>eval func in tab</Button>
|
||||
|
||||
<TextArea
|
||||
value={code}
|
||||
onChange={(e) => setCode(e.target.value)}
|
||||
placeholder="Enter your expression (e.g., 22 * 33)"
|
||||
/>
|
||||
<Button onClick={handleEvalCodeClick}>eval code in tab</Button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,113 +0,0 @@
|
||||
.Prox-title-wrap {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 12px 24px 8px;
|
||||
}
|
||||
|
||||
.Prox-title-wrap-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.Prox-title-wrap-left .prox-title {
|
||||
margin-right: 4px;
|
||||
color: #31343F;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.Prox-title-wrap-left .prox-number {
|
||||
display: inline-block;
|
||||
width: 18px;
|
||||
height: 16px;
|
||||
text-align: center;
|
||||
color: #85899E;
|
||||
border-radius: 8px;
|
||||
background: #F0F1F3;
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
.Prox-title-wrap-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.Prox-title-wrap-right .Prox-add-text {
|
||||
margin-right: 4px;
|
||||
color: var(--yakit-primary);
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.Prox-title-wrap-right .Prox-add-icon svg {
|
||||
color: var(--yakit-primary);
|
||||
}
|
||||
|
||||
.Prox-list-wrap {
|
||||
overflow-y: auto;
|
||||
max-height: 305px;
|
||||
padding: 16px;
|
||||
padding-top: 0;
|
||||
}
|
||||
|
||||
.add-list {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
height: 28px;
|
||||
cursor: pointer;
|
||||
border: 1px solid #EAECF3;
|
||||
border-radius: 4px;
|
||||
background-color: #FFFFFF;
|
||||
}
|
||||
|
||||
.add-list:hover {
|
||||
border: 1px solid var(--yakit-primary);
|
||||
}
|
||||
|
||||
.add-list .add-list-icon svg {
|
||||
color: #85899E;
|
||||
}
|
||||
|
||||
.Prox-list-wrap .add-list .add-list-text {
|
||||
margin-left: 4px;
|
||||
color: #31343F;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.Prox-list-wrap .Prox-list-item-wrap {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 10px 8px;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.Prox-list-wrap .Prox-list-item-wrap:hover {
|
||||
background-color: #F8F8F8;
|
||||
}
|
||||
|
||||
.Prox-list-item-space .ant-space-item .ant-space-compact {
|
||||
height: 28px;
|
||||
}
|
||||
|
||||
.Prox-list-item-space .ant-space-item .ant-space-compact .ant-select-single {
|
||||
height: 28px;
|
||||
}
|
||||
|
||||
.Prox-list-wrap .Prox-list-item-wrap:hover .proxy-list-del-icon {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.proxy-list-del-icon {
|
||||
display: none;
|
||||
cursor: pointer;
|
||||
padding: 4px;
|
||||
}
|
||||
|
||||
.proxy-list-del-icon:hover {
|
||||
background: #F0F1F3;
|
||||
}
|
||||
@@ -1,310 +0,0 @@
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { Space, Select, Input, Switch } from "antd";
|
||||
import { PlusSmIcon, TrashIcon } from "@assets/icon/icon";
|
||||
import { wsc } from "@network/chrome";
|
||||
import "./Proxifier.css";
|
||||
|
||||
type Scheme = "http" | "socks5";
|
||||
interface ProxyConfig {
|
||||
id: string;
|
||||
scheme: Scheme;
|
||||
host: string;
|
||||
port: string;
|
||||
hostStatus: "error" | "";
|
||||
portStatus: "error" | "";
|
||||
open: boolean;
|
||||
proxy: string;
|
||||
}
|
||||
|
||||
export interface ProxifierProps {}
|
||||
export const Proxifier: React.FC<ProxifierProps> = () => {
|
||||
const [proxyList, setProxyList] = useState<ProxyConfig[]>(() => {
|
||||
const storageProxyList = localStorage.getItem("yakit-proxy-list") || "[]";
|
||||
return JSON.parse(storageProxyList);
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
localStorage.setItem("yakit-proxy-list", JSON.stringify(proxyList));
|
||||
}, [proxyList]);
|
||||
|
||||
const addNewProxyListItem = (
|
||||
scheme: Scheme,
|
||||
host: string,
|
||||
port: string,
|
||||
open: boolean,
|
||||
proxy: string
|
||||
) => {
|
||||
const proxyItem: ProxyConfig = {
|
||||
id: Math.random() + "",
|
||||
scheme: scheme as Scheme,
|
||||
host: host,
|
||||
port: port,
|
||||
hostStatus: "",
|
||||
portStatus: "",
|
||||
open: open,
|
||||
proxy: proxy,
|
||||
};
|
||||
return proxyItem;
|
||||
};
|
||||
|
||||
const parseUrl = (url: string) => {
|
||||
const regex = /^(.*?):\/\/(.*?):(\d+)/;
|
||||
const match = url.match(regex);
|
||||
if (match) {
|
||||
const scheme = match[1];
|
||||
const host = match[2];
|
||||
const port = match[3];
|
||||
return {
|
||||
scheme,
|
||||
host,
|
||||
port,
|
||||
};
|
||||
} else {
|
||||
return null; // 不匹配格式
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
wsc.updateProxyStatus();
|
||||
|
||||
wsc.onProxyStatusMessage((msg) => {
|
||||
if (msg.proxy === undefined || msg.enable === undefined) {
|
||||
return;
|
||||
}
|
||||
if (msg.proxy === "" || msg.enable === false) {
|
||||
if (proxyList.some((i) => i.open)) {
|
||||
const copyProxyList = [...proxyList];
|
||||
copyProxyList.forEach((i) => {
|
||||
i.open = false;
|
||||
});
|
||||
setProxyList(copyProxyList);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg.proxy && msg.enable) {
|
||||
const copyProxyList = [...proxyList];
|
||||
let newProxyItem: ProxyConfig = undefined;
|
||||
if (!copyProxyList.length) {
|
||||
const urlObj = parseUrl(msg.proxy);
|
||||
if (urlObj) {
|
||||
newProxyItem = addNewProxyListItem(
|
||||
urlObj.scheme as Scheme,
|
||||
urlObj.host,
|
||||
urlObj.port,
|
||||
true,
|
||||
msg.proxy
|
||||
);
|
||||
}
|
||||
} else {
|
||||
const proxyExist = copyProxyList.some((i) => i.proxy === msg.proxy);
|
||||
if (proxyExist) {
|
||||
const proxyOpen = copyProxyList.some(
|
||||
(i) => i.open && i.proxy === msg.proxy
|
||||
);
|
||||
if (!proxyOpen) {
|
||||
copyProxyList.forEach((i) => {
|
||||
i.open = false;
|
||||
});
|
||||
for (let i = 0; i < copyProxyList.length; i++) {
|
||||
if (copyProxyList[i].proxy === msg.proxy) {
|
||||
copyProxyList[i].open = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
copyProxyList.forEach((i) => {
|
||||
i.open = false;
|
||||
});
|
||||
const urlObj = parseUrl(msg.proxy);
|
||||
if (urlObj) {
|
||||
newProxyItem = addNewProxyListItem(
|
||||
urlObj.scheme as Scheme,
|
||||
urlObj.host,
|
||||
urlObj.port,
|
||||
true,
|
||||
msg.proxy
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (newProxyItem) {
|
||||
copyProxyList.unshift(newProxyItem);
|
||||
}
|
||||
setProxyList(copyProxyList);
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
|
||||
const hostOnchange = (value: string, id: string) => {
|
||||
const ipPattern = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
|
||||
const domainPattern = /^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
|
||||
const copyProxyList = structuredClone(proxyList);
|
||||
if (value === "" || ipPattern.test(value) || domainPattern.test(value)) {
|
||||
copyProxyList.forEach((i) => {
|
||||
if (i.id === id) {
|
||||
i.hostStatus = "";
|
||||
i.host = value;
|
||||
i.proxy = i.scheme + "://" + value + ":" + i.port;
|
||||
}
|
||||
});
|
||||
} else {
|
||||
copyProxyList.forEach((i) => {
|
||||
if (i.id === id) {
|
||||
i.hostStatus = "error";
|
||||
i.host = value;
|
||||
i.proxy = i.scheme + "://" + value + ":" + i.port;
|
||||
}
|
||||
});
|
||||
}
|
||||
setProxyList(copyProxyList);
|
||||
};
|
||||
|
||||
const portOnchange = (value: string, id: string) => {
|
||||
const portNumber = parseInt(value, 10);
|
||||
const copyProxyList = structuredClone(proxyList);
|
||||
if (
|
||||
value === "" ||
|
||||
(/^\d+$/.test(value) && portNumber >= 0 && portNumber <= 65535)
|
||||
) {
|
||||
copyProxyList.forEach((i) => {
|
||||
if (i.id === id) {
|
||||
i.portStatus = "";
|
||||
const port = value === "" ? "" : portNumber + "";
|
||||
i.port = port;
|
||||
i.proxy = i.scheme + "://" + i.host + ":" + port;
|
||||
}
|
||||
});
|
||||
} else {
|
||||
copyProxyList.forEach((i) => {
|
||||
if (i.id === id) {
|
||||
i.portStatus = "error";
|
||||
i.port = value;
|
||||
i.proxy = i.scheme + "://" + i.host + ":" + value;
|
||||
}
|
||||
});
|
||||
}
|
||||
setProxyList(copyProxyList);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="Prox">
|
||||
<div className="Prox-title-wrap">
|
||||
<div className="Prox-title-wrap-left">
|
||||
<span className="prox-title">设置代理</span>
|
||||
<span className="prox-number">{proxyList.length}</span>
|
||||
</div>
|
||||
<div
|
||||
className="Prox-title-wrap-right"
|
||||
onClick={() => {
|
||||
setProxyList([
|
||||
...proxyList,
|
||||
addNewProxyListItem("http", "", "", false, "http://"),
|
||||
]);
|
||||
}}
|
||||
>
|
||||
<span className="Prox-add-text">添加</span>
|
||||
<PlusSmIcon className="Prox-add-icon" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="Prox-list-wrap">
|
||||
{proxyList.length ? (
|
||||
proxyList.map((item) => (
|
||||
<div className="Prox-list-item-wrap" key={item.id}>
|
||||
<Space className="Prox-list-item-space">
|
||||
<Space.Compact>
|
||||
<Select
|
||||
value={item.scheme}
|
||||
style={{ width: 88 }}
|
||||
disabled={item.open}
|
||||
onChange={(value, option) => {
|
||||
const copyProxyList = structuredClone(proxyList);
|
||||
copyProxyList.forEach((i) => {
|
||||
if (i.id === item.id) {
|
||||
i.scheme = value;
|
||||
i.proxy = value + "://" + i.host + ":" + i.port;
|
||||
}
|
||||
});
|
||||
setProxyList(copyProxyList);
|
||||
}}
|
||||
>
|
||||
<Select.Option value="http">HTTP</Select.Option>
|
||||
<Select.Option value="socks5">Socks5</Select.Option>
|
||||
</Select>
|
||||
<Input
|
||||
value={item.host}
|
||||
style={{ width: 136 }}
|
||||
disabled={item.open}
|
||||
status={item.hostStatus}
|
||||
onChange={(e) => hostOnchange(e.target.value, item.id)}
|
||||
/>
|
||||
<Input
|
||||
value={item.port}
|
||||
style={{ width: 64 }}
|
||||
disabled={item.open}
|
||||
status={item.portStatus}
|
||||
onChange={(e) => portOnchange(e.target.value, item.id)}
|
||||
/>
|
||||
</Space.Compact>
|
||||
</Space>
|
||||
{!item.open && (
|
||||
<TrashIcon
|
||||
className="proxy-list-del-icon"
|
||||
onClick={() => {
|
||||
setProxyList(proxyList.filter((i) => i.id !== item.id));
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<Switch
|
||||
checkedChildren="启"
|
||||
unCheckedChildren="停"
|
||||
value={item.open}
|
||||
disabled={
|
||||
item.hostStatus === "error" ||
|
||||
item.portStatus === "error" ||
|
||||
item.host === "" ||
|
||||
item.port === ""
|
||||
}
|
||||
onChange={(checked: boolean) => {
|
||||
wsc.clearProxy();
|
||||
const copyProxyList = structuredClone(proxyList);
|
||||
copyProxyList.forEach((i) => {
|
||||
if (i.id === item.id) {
|
||||
i.open = checked;
|
||||
if (checked) {
|
||||
wsc.setProxy(item.scheme, item.host, Number(item.port));
|
||||
}
|
||||
} else {
|
||||
i.open = false;
|
||||
}
|
||||
});
|
||||
setProxyList(copyProxyList);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<div
|
||||
className="add-list"
|
||||
onClick={() => {
|
||||
setProxyList([
|
||||
addNewProxyListItem(
|
||||
"http",
|
||||
"127.0.0.1",
|
||||
"8083",
|
||||
false,
|
||||
"http://127.0.0.1:8083"
|
||||
),
|
||||
]);
|
||||
}}
|
||||
>
|
||||
<PlusSmIcon className="add-list-icon" />
|
||||
<span className="add-list-text">添加</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,21 @@
|
||||
import { cn } from '@/lib/cn';
|
||||
|
||||
export function YakMark({ className, alt = 'Yak' }: { className?: string; alt?: string }) {
|
||||
return <img className={cn('yak-mark', className)} src="/yak.svg" alt={alt} />;
|
||||
}
|
||||
|
||||
export function YakitMark({ className }: { className?: string }) {
|
||||
return <img className={cn('yakit-mark', className)} src="/icon/yakitlogo.png" alt="Yakit" />;
|
||||
}
|
||||
|
||||
export function ProductBrand({ compact = false, className }: { compact?: boolean; className?: string }) {
|
||||
return (
|
||||
<div className={cn('product-brand', compact && 'product-brand--compact', className)}>
|
||||
<span className="product-brand__art"><YakMark /></span>
|
||||
<span className="product-brand__copy">
|
||||
<strong>Yakit Browser Agent</strong>
|
||||
{!compact && <small>Authenticated browser security workspace</small>}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { HTMLAttributes } from 'react';
|
||||
import { cn } from '@/lib/cn';
|
||||
|
||||
export function Badge({ className, ...props }: HTMLAttributes<HTMLSpanElement>) {
|
||||
return <span className={cn('ui-badge', className)} {...props} />;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { Slot } from '@radix-ui/react-slot';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
import type { ButtonHTMLAttributes } from 'react';
|
||||
import { cn } from '@/lib/cn';
|
||||
|
||||
const buttonVariants = cva('ui-button', {
|
||||
variants: {
|
||||
variant: {
|
||||
primary: 'ui-button--primary',
|
||||
secondary: 'ui-button--secondary',
|
||||
ghost: 'ui-button--ghost',
|
||||
danger: 'ui-button--danger',
|
||||
},
|
||||
size: {
|
||||
sm: 'ui-button--sm',
|
||||
md: 'ui-button--md',
|
||||
icon: 'ui-button--icon',
|
||||
},
|
||||
},
|
||||
defaultVariants: { variant: 'secondary', size: 'md' },
|
||||
});
|
||||
|
||||
export interface ButtonProps
|
||||
extends ButtonHTMLAttributes<HTMLButtonElement>, VariantProps<typeof buttonVariants> {
|
||||
asChild?: boolean;
|
||||
}
|
||||
|
||||
export function Button({ className, variant, size, asChild, ...props }: ButtonProps) {
|
||||
const Component = asChild ? Slot : 'button';
|
||||
return <Component className={cn(buttonVariants({ variant, size }), className)} {...props} />;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { LabelHTMLAttributes, ReactNode } from 'react';
|
||||
import { cn } from '@/lib/cn';
|
||||
|
||||
export function Field({ label, hint, children, className, ...props }: {
|
||||
label: string;
|
||||
hint?: string;
|
||||
children: ReactNode;
|
||||
} & Omit<LabelHTMLAttributes<HTMLLabelElement>, 'children'>) {
|
||||
return (
|
||||
<label className={cn('ui-field', className)} {...props}>
|
||||
<span className="ui-field__label">{label}</span>
|
||||
{children}
|
||||
{hint && <small className="ui-field__hint">{hint}</small>}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import * as SwitchPrimitive from '@radix-ui/react-switch';
|
||||
import type { ComponentProps } from 'react';
|
||||
import { cn } from '@/lib/cn';
|
||||
|
||||
export function Switch({ className, ...props }: ComponentProps<typeof SwitchPrimitive.Root>) {
|
||||
return (
|
||||
<SwitchPrimitive.Root className={cn('ui-switch', className)} {...props}>
|
||||
<SwitchPrimitive.Thumb className="ui-switch__thumb" />
|
||||
</SwitchPrimitive.Root>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import * as TabsPrimitive from '@radix-ui/react-tabs';
|
||||
import type { ComponentProps } from 'react';
|
||||
import { cn } from '@/lib/cn';
|
||||
|
||||
export const Tabs = TabsPrimitive.Root;
|
||||
|
||||
export function TabsList({ className, ...props }: ComponentProps<typeof TabsPrimitive.List>) {
|
||||
return <TabsPrimitive.List className={cn('ui-tabs-list', className)} {...props} />;
|
||||
}
|
||||
|
||||
export function TabsTrigger({ className, ...props }: ComponentProps<typeof TabsPrimitive.Trigger>) {
|
||||
return <TabsPrimitive.Trigger className={cn('ui-tabs-trigger', className)} {...props} />;
|
||||
}
|
||||
|
||||
export function TabsContent({ className, ...props }: ComponentProps<typeof TabsPrimitive.Content>) {
|
||||
return <TabsPrimitive.Content className={cn('ui-tabs-content', className)} {...props} />;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import * as TooltipPrimitive from '@radix-ui/react-tooltip';
|
||||
import type { ComponentProps, ReactNode } from 'react';
|
||||
import { cn } from '@/lib/cn';
|
||||
|
||||
export const TooltipProvider = TooltipPrimitive.Provider;
|
||||
|
||||
export function Tooltip({ label, children, side = 'top' }: {
|
||||
label: string;
|
||||
children: ReactNode;
|
||||
side?: ComponentProps<typeof TooltipPrimitive.Content>['side'];
|
||||
}) {
|
||||
return (
|
||||
<TooltipPrimitive.Root>
|
||||
<TooltipPrimitive.Trigger asChild>{children}</TooltipPrimitive.Trigger>
|
||||
<TooltipPrimitive.Portal>
|
||||
<TooltipPrimitive.Content side={side} sideOffset={6} className={cn('ui-tooltip')}>
|
||||
{label}
|
||||
<TooltipPrimitive.Arrow className="ui-tooltip__arrow" />
|
||||
</TooltipPrimitive.Content>
|
||||
</TooltipPrimitive.Portal>
|
||||
</TooltipPrimitive.Root>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
import { browser } from 'wxt/browser';
|
||||
import { installPageWorldBridge } from '@/features/page-context/content-bridge';
|
||||
import { installPageRecorderBridge } from '@/features/browser-recording/content-bridge';
|
||||
import { isStateStorageChange } from '@/protocol/storage';
|
||||
import type { ActiveTabInfo, BridgeStatus, ExtensionState } from '@/types/models';
|
||||
import {
|
||||
createLazyUnloadController,
|
||||
floatingPanelVisible,
|
||||
isFloatingPanelShortcut,
|
||||
mergeFloatingTabUpdate,
|
||||
resolvePanelPlacement,
|
||||
shouldCollapseForFullscreen,
|
||||
} from '@/features/floating-panel/host-controller';
|
||||
import { createOpaqueId } from '@/shared/id';
|
||||
|
||||
const PANEL_IDLE_UNLOAD_MS = 60_000;
|
||||
|
||||
const shellCss = `
|
||||
:host { all: initial; position: fixed !important; inset: 0 !important; z-index: 2147483646 !important; pointer-events: none !important; }
|
||||
.floating-panel { position: fixed; width: 46px; height: 46px; transform: translateY(-50%); pointer-events: auto; transition: width .16s ease; }
|
||||
.floating-panel--left { left: 0; }
|
||||
.floating-panel--right { right: 0; }
|
||||
.floating-panel.is-expanded { width: min(326px, calc(100vw - 8px)); }
|
||||
.floating-panel__header { position: absolute; top: 0; z-index: 2; width: 46px; height: 46px; display: flex; align-items: center; overflow: hidden; border: 1px solid #d7dce1; background: #fff; color: #1d232b; box-sizing: border-box; touch-action: none; user-select: none; transition: width .16s ease; }
|
||||
.floating-panel--left .floating-panel__header { left: 0; }
|
||||
.floating-panel--right .floating-panel__header { right: 0; }
|
||||
.floating-panel.is-expanded .floating-panel__header { width: 100%; border-radius: 8px 8px 0 0; box-shadow: 0 7px 20px rgba(20,24,28,.14); }
|
||||
.floating-panel--right.is-expanded .floating-panel__header { flex-direction: row-reverse; }
|
||||
.floating-panel__brand { position: relative; width: 44px; height: 44px; flex: 0 0 44px; padding: 0; display: grid; place-items: center; border: 0; background: transparent; cursor: pointer; box-shadow: 0 8px 20px rgba(20,24,28,.18); transition: background-color .16s ease, box-shadow .16s ease; }
|
||||
.floating-panel__brand:hover { background: #f1f3f5; }
|
||||
:host([data-theme='dark']) .floating-panel__header { border-color: #343a40; background: #1d232b; color: #f1f3f5; }
|
||||
:host([data-theme='dark']) .floating-panel__brand { background: #1d232b; }
|
||||
:host([data-theme='dark']) .floating-panel__brand:hover { background: #262d36; }
|
||||
.floating-panel--left:not(.is-expanded) .floating-panel__header { border-left: 0; border-radius: 0 23px 23px 0; }
|
||||
.floating-panel--right:not(.is-expanded) .floating-panel__header { border-right: 0; border-radius: 23px 0 0 23px; }
|
||||
.floating-panel--left:not(.is-expanded) .floating-panel__brand { border-radius: 0 23px 23px 0; }
|
||||
.floating-panel--right:not(.is-expanded) .floating-panel__brand { border-radius: 23px 0 0 23px; }
|
||||
.floating-panel.is-expanded .floating-panel__brand { box-shadow: none; }
|
||||
.floating-panel__brand:focus-visible { outline: 2px solid #ee7815; outline-offset: -3px; }
|
||||
.floating-panel__brand img { width: 42px; height: 42px; display: block; object-fit: contain; pointer-events: none; }
|
||||
.floating-panel__signal { position: absolute; right: 5px; bottom: 5px; width: 7px; height: 7px; border: 1px solid #fff; border-radius: 50%; background: #90979e; }
|
||||
:host([data-theme='dark']) .floating-panel__signal { border-color: #1d232b; }
|
||||
.floating-panel__signal.connected { background: #45b77d; }
|
||||
.floating-panel__signal.connecting, .floating-panel__signal.negotiating { background: #e3a632; }
|
||||
.floating-panel__signal.error { background: #dc5e5e; }
|
||||
.floating-panel__title { min-width: 0; flex: 1; padding: 0 9px; display: none; }
|
||||
.floating-panel.is-expanded .floating-panel__title { display: grid; gap: 1px; }
|
||||
.floating-panel__title strong, .floating-panel__title span { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; font-family: system-ui, sans-serif; }
|
||||
.floating-panel__title strong { font-size: 12px; line-height: 16px; font-weight: 650; }
|
||||
.floating-panel__title span { color: #697078; font-size: 10px; line-height: 14px; }
|
||||
:host([data-theme='dark']) .floating-panel__title span { color: #a7afb8; }
|
||||
.floating-panel__grip { width: 20px; flex: 0 0 20px; display: none; color: #90979e; font: 14px/1 system-ui, sans-serif; letter-spacing: -2px; }
|
||||
.floating-panel.is-expanded .floating-panel__grip { display: block; }
|
||||
iframe { width: 100%; height: 320px; margin-top: 46px; display: block; border: 0; border-radius: 0 0 8px 8px; box-shadow: 0 10px 28px rgba(22,28,33,.18); }
|
||||
.floating-panel:not(.is-expanded) iframe { visibility: hidden; pointer-events: none; }
|
||||
`;
|
||||
|
||||
async function send<T>(action: string, payload?: unknown): Promise<T> {
|
||||
const response = await browser.runtime.sendMessage({ action, payload }) as { ok?: boolean; data?: T; error?: string };
|
||||
if (!response?.ok) throw new Error(response?.error || action);
|
||||
return response.data as T;
|
||||
}
|
||||
|
||||
export default defineContentScript({
|
||||
matches: ['http://*/*', 'https://*/*'],
|
||||
runAt: 'document_start',
|
||||
|
||||
async main(ctx) {
|
||||
if (import.meta.env.FIREFOX) {
|
||||
await installPageRecorderBridge(ctx).catch((error) => {
|
||||
console.warn('[Yakit Browser Agent] Firefox page recorder bridge is unavailable.', error);
|
||||
});
|
||||
}
|
||||
if ((import.meta.env.FIREFOX && import.meta.env.MODE !== 'store')
|
||||
|| (!import.meta.env.FIREFOX && import.meta.env.MODE !== 'production' && import.meta.env.MODE !== 'store')) {
|
||||
await installPageWorldBridge(ctx).catch((error) => {
|
||||
console.warn('[Yakit Browser Agent] MAIN-world bridge is unavailable; continuing without page Eval/Invoke.', error);
|
||||
});
|
||||
}
|
||||
|
||||
const host = document.createElement('yakit-browser-agent');
|
||||
const shadow = host.attachShadow({ mode: 'open' });
|
||||
const style = document.createElement('style');
|
||||
style.textContent = shellCss;
|
||||
const panel = document.createElement('div');
|
||||
panel.className = 'floating-panel floating-panel--right';
|
||||
const header = document.createElement('div');
|
||||
header.className = 'floating-panel__header';
|
||||
const launcher = document.createElement('button');
|
||||
launcher.type = 'button';
|
||||
launcher.className = 'floating-panel__brand';
|
||||
launcher.setAttribute('aria-label', '展开 Yakit Browser Agent');
|
||||
const logo = document.createElement('img');
|
||||
logo.src = browser.runtime.getURL('/yak.svg');
|
||||
logo.alt = 'Yak';
|
||||
logo.draggable = false;
|
||||
const signal = document.createElement('span');
|
||||
signal.className = 'floating-panel__signal disconnected';
|
||||
launcher.append(logo, signal);
|
||||
const headerTitle = document.createElement('span');
|
||||
headerTitle.className = 'floating-panel__title';
|
||||
const headerPageTitle = document.createElement('strong');
|
||||
const headerPageUrl = document.createElement('span');
|
||||
headerTitle.append(headerPageTitle, headerPageUrl);
|
||||
const grip = document.createElement('span');
|
||||
grip.className = 'floating-panel__grip';
|
||||
grip.textContent = '⠿';
|
||||
grip.setAttribute('aria-hidden', 'true');
|
||||
header.append(launcher, headerTitle, grip);
|
||||
panel.append(header);
|
||||
shadow.append(style, panel);
|
||||
document.documentElement.append(host);
|
||||
|
||||
// Launcher theme follows the extension appearance setting (settings.appearance.v1), falling back to the OS scheme.
|
||||
const themeKey = 'settings.appearance.v1';
|
||||
const applyTheme = (theme?: string) => {
|
||||
host.dataset.theme = theme === 'light' || theme === 'dark'
|
||||
? theme
|
||||
: (globalThis.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
|
||||
};
|
||||
void browser.storage.local.get(themeKey).then((stored) => {
|
||||
applyTheme((stored[themeKey] as { theme?: string } | undefined)?.theme);
|
||||
});
|
||||
|
||||
let state: ExtensionState | undefined;
|
||||
let currentTab: ActiveTabInfo | undefined;
|
||||
let frame: HTMLIFrameElement | undefined;
|
||||
let expanded = false;
|
||||
let drag: { pointerId: number; startX: number; startY: number; moved: boolean } | undefined;
|
||||
const frameChannel = createOpaqueId('floating-channel');
|
||||
|
||||
const setBridgeStatus = (status: BridgeStatus) => {
|
||||
signal.className = `floating-panel__signal ${status.state}`;
|
||||
};
|
||||
const updateHeaderPage = () => {
|
||||
headerPageTitle.textContent = currentTab?.title || document.title || '当前页面';
|
||||
headerPageTitle.title = headerPageTitle.textContent;
|
||||
headerPageUrl.textContent = currentTab?.url || location.href;
|
||||
headerPageUrl.title = headerPageUrl.textContent;
|
||||
};
|
||||
const postTabToFrame = () => {
|
||||
if (!frame?.contentWindow || !currentTab) return;
|
||||
frame.contentWindow.postMessage({
|
||||
channel: 'yakit-floating-host', token: frameChannel, type: 'tab.changed',
|
||||
tab: { tabId: currentTab.id, title: currentTab.title, url: currentTab.url },
|
||||
}, '*');
|
||||
};
|
||||
const applyTabUpdate = (update: { tabId: number; title?: string; url?: string }) => {
|
||||
const next = mergeFloatingTabUpdate(currentTab, update);
|
||||
if (next === currentTab) return;
|
||||
currentTab = next;
|
||||
updateHeaderPage();
|
||||
postTabToFrame();
|
||||
if (state) applyState(state);
|
||||
};
|
||||
const adjustForEdgeConflict = () => {
|
||||
if (host.style.display === 'none') return;
|
||||
const x = state?.floatingPanel.side === 'left' ? 8 : innerWidth - 8;
|
||||
const desiredY = (state?.floatingPanel.y || 0.46) * innerHeight;
|
||||
const previous = host.style.visibility;
|
||||
host.style.visibility = 'hidden';
|
||||
const behind = document.elementFromPoint(x, desiredY);
|
||||
host.style.visibility = previous;
|
||||
if (!behind) return;
|
||||
const position = getComputedStyle(behind).position;
|
||||
const bounds = behind.getBoundingClientRect();
|
||||
if (!['fixed', 'sticky'].includes(position) || bounds.width < 32 || bounds.height < 32) return;
|
||||
const offset = desiredY < innerHeight / 2 ? bounds.bottom + 30 : bounds.top - 30;
|
||||
panel.style.top = `${Math.min(Math.max(offset / innerHeight, 0.08), 0.92) * 100}%`;
|
||||
};
|
||||
const applyState = (next: ExtensionState) => {
|
||||
const previousHandoffId = state?.handoff?.state === 'waiting_for_user' ? state.handoff.id : undefined;
|
||||
state = next;
|
||||
const visible = floatingPanelVisible(next, currentTab, location.origin);
|
||||
host.style.display = visible ? '' : 'none';
|
||||
panel.classList.toggle('floating-panel--left', next.floatingPanel.side === 'left');
|
||||
panel.classList.toggle('floating-panel--right', next.floatingPanel.side === 'right');
|
||||
panel.style.top = `${next.floatingPanel.y * 100}%`;
|
||||
if (!visible) collapse();
|
||||
const nextHandoff = next.handoff?.state === 'waiting_for_user' && next.handoff.target.tabId === currentTab?.id
|
||||
? next.handoff
|
||||
: undefined;
|
||||
if (nextHandoff && nextHandoff.id !== previousHandoffId) expand();
|
||||
requestAnimationFrame(adjustForEdgeConflict);
|
||||
};
|
||||
const ensureFrame = () => {
|
||||
if (frame) return;
|
||||
frame = document.createElement('iframe');
|
||||
frame.title = 'Yakit Browser Agent';
|
||||
frame.src = `${browser.runtime.getURL('/floating.html')}?tabId=${currentTab?.id || ''}&channel=${encodeURIComponent(frameChannel)}`;
|
||||
frame.addEventListener('load', postTabToFrame, { once: true });
|
||||
panel.prepend(frame);
|
||||
};
|
||||
const unloadFrame = () => {
|
||||
frame?.remove();
|
||||
frame = undefined;
|
||||
};
|
||||
const lazyUnload = createLazyUnloadController(PANEL_IDLE_UNLOAD_MS, unloadFrame);
|
||||
function collapse() {
|
||||
expanded = false;
|
||||
panel.classList.remove('is-expanded');
|
||||
launcher.setAttribute('aria-label', '展开 Yakit Browser Agent');
|
||||
lazyUnload.schedule();
|
||||
}
|
||||
const expand = () => {
|
||||
lazyUnload.cancel();
|
||||
ensureFrame();
|
||||
expanded = true;
|
||||
panel.classList.add('is-expanded');
|
||||
launcher.setAttribute('aria-label', '收起 Yakit Browser Agent');
|
||||
};
|
||||
|
||||
const [initialState, initialTab, initialBridge] = await Promise.all([
|
||||
send<ExtensionState>('state.get'),
|
||||
send<ActiveTabInfo>('tab.active').catch(() => undefined),
|
||||
send<BridgeStatus>('bridge.status'),
|
||||
]);
|
||||
currentTab = initialTab;
|
||||
updateHeaderPage();
|
||||
applyState(initialState);
|
||||
setBridgeStatus(initialBridge);
|
||||
|
||||
header.addEventListener('pointerdown', (event) => {
|
||||
if (event.button !== 0) return;
|
||||
drag = { pointerId: event.pointerId, startX: event.clientX, startY: event.clientY, moved: false };
|
||||
header.setPointerCapture(event.pointerId);
|
||||
});
|
||||
header.addEventListener('pointermove', (event) => {
|
||||
if (!drag || drag.pointerId !== event.pointerId) return;
|
||||
if (Math.hypot(event.clientX - drag.startX, event.clientY - drag.startY) > 4) drag.moved = true;
|
||||
if (!drag.moved) return;
|
||||
const { side, y } = resolvePanelPlacement(event.clientX, event.clientY, innerWidth, innerHeight);
|
||||
panel.classList.toggle('floating-panel--left', side === 'left');
|
||||
panel.classList.toggle('floating-panel--right', side === 'right');
|
||||
panel.style.top = `${y * 100}%`;
|
||||
});
|
||||
header.addEventListener('pointerup', (event) => {
|
||||
if (!drag || drag.pointerId !== event.pointerId) return;
|
||||
const moved = drag.moved;
|
||||
drag = undefined;
|
||||
if (moved) {
|
||||
const { side, y } = resolvePanelPlacement(event.clientX, event.clientY, innerWidth, innerHeight);
|
||||
void send<ExtensionState>('panel.update', { side, y }).then(applyState).catch(() => undefined);
|
||||
} else if (expanded) collapse(); else expand();
|
||||
});
|
||||
header.addEventListener('pointercancel', () => { drag = undefined; });
|
||||
|
||||
const onStorageChange = (changes: Record<string, unknown>) => {
|
||||
if (isStateStorageChange(changes)) void send<ExtensionState>('state.get').then(applyState).catch(() => undefined);
|
||||
if (themeKey in changes) applyTheme((changes[themeKey] as { newValue?: { theme?: string } } | undefined)?.newValue?.theme);
|
||||
};
|
||||
const onRuntimeMessage = (message: unknown) => {
|
||||
const input = message as { action?: string; payload?: unknown };
|
||||
if (input?.action === 'bridge.status.changed' && input.payload) setBridgeStatus(input.payload as BridgeStatus);
|
||||
if (input?.action === 'floating.tab.changed' && input.payload) {
|
||||
applyTabUpdate(input.payload as { tabId: number; title?: string; url?: string });
|
||||
}
|
||||
};
|
||||
const onFrameMessage = (event: MessageEvent) => {
|
||||
const data = event.data as { channel?: string; token?: string; type?: string; height?: number };
|
||||
if (event.source !== frame?.contentWindow || data?.channel !== 'yakit-floating-host' || data.token !== frameChannel) return;
|
||||
if (data.type === 'collapse') collapse();
|
||||
if (data.type === 'resize' && typeof data.height === 'number' && frame) {
|
||||
const availableHeight = Math.max(160, Math.min(480, innerHeight - 62));
|
||||
frame.style.height = `${Math.min(Math.max(Math.ceil(data.height), 160), availableHeight)}px`;
|
||||
}
|
||||
};
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (!state) return;
|
||||
const target = event.target as HTMLElement | null;
|
||||
const editable = Boolean(target?.isContentEditable || target?.closest('input, textarea, select, [contenteditable="true"]'));
|
||||
if (!isFloatingPanelShortcut(state.floatingPanel, event, editable)) return;
|
||||
if (host.style.display === 'none') return;
|
||||
event.preventDefault();
|
||||
if (expanded) collapse(); else expand();
|
||||
};
|
||||
const onFullscreenChange = () => {
|
||||
if (state && shouldCollapseForFullscreen(state.floatingPanel, Boolean(document.fullscreenElement))) collapse();
|
||||
};
|
||||
const onResize = () => requestAnimationFrame(adjustForEdgeConflict);
|
||||
const syncDocumentMetadata = () => {
|
||||
if (!currentTab) return;
|
||||
applyTabUpdate({ tabId: currentTab.id, title: document.title, url: location.href });
|
||||
};
|
||||
let titleObserver: MutationObserver | undefined;
|
||||
const installTitleObserver = () => {
|
||||
if (titleObserver || !document.head) return;
|
||||
titleObserver = new MutationObserver(syncDocumentMetadata);
|
||||
titleObserver.observe(document.head, { subtree: true, childList: true, characterData: true });
|
||||
syncDocumentMetadata();
|
||||
};
|
||||
if (document.head) installTitleObserver();
|
||||
else document.addEventListener('DOMContentLoaded', installTitleObserver, { once: true });
|
||||
browser.storage.onChanged.addListener(onStorageChange);
|
||||
browser.runtime.onMessage.addListener(onRuntimeMessage);
|
||||
globalThis.addEventListener('message', onFrameMessage);
|
||||
globalThis.addEventListener('keydown', onKeyDown, true);
|
||||
globalThis.addEventListener('popstate', syncDocumentMetadata);
|
||||
globalThis.addEventListener('hashchange', syncDocumentMetadata);
|
||||
document.addEventListener('fullscreenchange', onFullscreenChange);
|
||||
globalThis.addEventListener('resize', onResize);
|
||||
ctx.onInvalidated(() => {
|
||||
lazyUnload.dispose();
|
||||
titleObserver?.disconnect();
|
||||
document.removeEventListener('DOMContentLoaded', installTitleObserver);
|
||||
browser.storage.onChanged.removeListener(onStorageChange);
|
||||
browser.runtime.onMessage.removeListener(onRuntimeMessage);
|
||||
globalThis.removeEventListener('message', onFrameMessage);
|
||||
globalThis.removeEventListener('keydown', onKeyDown, true);
|
||||
globalThis.removeEventListener('popstate', syncDocumentMetadata);
|
||||
globalThis.removeEventListener('hashchange', syncDocumentMetadata);
|
||||
document.removeEventListener('fullscreenchange', onFullscreenChange);
|
||||
globalThis.removeEventListener('resize', onResize);
|
||||
host.remove();
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
html, body { width: 100%; height: 100%; margin: 0; pointer-events: none; }
|
||||
|
||||
.floating-panel {
|
||||
position: fixed;
|
||||
z-index: 2147483646;
|
||||
width: 46px;
|
||||
transform: translateY(-50%);
|
||||
color: var(--foreground);
|
||||
font-family: var(--font-sans);
|
||||
font-size: var(--text-md);
|
||||
letter-spacing: 0;
|
||||
filter: drop-shadow(0 9px 20px rgba(20, 24, 28, .2));
|
||||
transition: width .18s ease;
|
||||
pointer-events: auto;
|
||||
}
|
||||
.floating-panel--left { left: 0; }
|
||||
.floating-panel--right { right: 0; }
|
||||
.floating-panel.is-expanded { width: min(326px, calc(100vw - 8px)); }
|
||||
|
||||
.floating-panel__body {
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-top: 0;
|
||||
border-radius: 0 0 var(--radius-md) var(--radius-md);
|
||||
background: var(--surface);
|
||||
box-shadow: var(--shadow-md);
|
||||
}
|
||||
.floating-tabs { width: auto; height: 34px; margin: 8px 10px 0; padding: 3px; display: grid; grid-template-columns: repeat(3, 1fr); border: 0; border-radius: 10px; background: var(--surface-subtle); }
|
||||
.floating-tabs .ui-tabs-trigger { min-width: 0; height: 28px; display: flex; align-items: center; justify-content: center; gap: 5px; border-radius: 8px; font-size: var(--text-sm); }
|
||||
.floating-tab-content { min-height: 208px; padding: 10px; display: grid; align-content: start; gap: 10px; }
|
||||
.floating-section-heading { height: 28px; display: flex; align-items: center; justify-content: space-between; color: var(--muted); font-size: var(--text-xs); font-weight: 650; letter-spacing: .04em; text-transform: uppercase; }
|
||||
|
||||
.floating-option-list { max-height: 224px; overflow-y: auto; display: grid; gap: 4px; scrollbar-width: thin; scrollbar-color: var(--border-strong) transparent; }
|
||||
.floating-option-list::-webkit-scrollbar { width: 8px; }
|
||||
.floating-option-list::-webkit-scrollbar-track { background: transparent; }
|
||||
.floating-option-list::-webkit-scrollbar-thumb { border-radius: 4px; background: var(--border-strong); }
|
||||
.floating-option-list > button { width: 100%; min-height: 46px; padding: 6px 10px; display: flex; align-items: center; gap: 9px; border: 0; border-radius: var(--radius-md); background: transparent; color: var(--foreground); text-align: left; transition: background-color .13s ease; }
|
||||
.floating-option-list > button:hover { background: var(--surface-subtle); }
|
||||
.floating-option-list > button.is-active { background: var(--primary-soft); color: var(--primary-text); }
|
||||
.floating-radio { width: 15px; height: 15px; flex: 0 0 auto; padding: 2.5px; border: 1.5px solid var(--border-strong); border-radius: 50%; background-clip: content-box; transition: border-color .13s ease; }
|
||||
.floating-option-list > button.is-active .floating-radio { border-color: var(--primary); background-color: var(--primary); }
|
||||
.floating-option-list strong, .floating-option-list small { display: block; }
|
||||
.floating-option-list > button > span { min-width: 0; }
|
||||
.floating-option-list strong { font-size: var(--text-md); font-weight: 600; line-height: 17px; }
|
||||
.floating-option-list small { margin-top: 2px; color: var(--muted); font-size: var(--text-sm); line-height: 15px; }
|
||||
|
||||
.floating-page-meta { min-width: 0; padding: 9px 12px; display: grid; gap: 3px; border-radius: var(--radius-md); background: var(--surface-subtle); }
|
||||
.floating-page-meta strong, .floating-page-meta span { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.floating-page-meta strong { font-size: var(--text-md); font-weight: 600; }
|
||||
.floating-page-meta span { color: var(--muted); font-size: var(--text-sm); }
|
||||
|
||||
.floating-result { min-height: 34px; padding: 4px 6px 4px 12px; display: flex; align-items: center; justify-content: space-between; gap: 8px; border-radius: var(--radius-md); background: var(--success-soft); color: var(--success); font-size: var(--text-sm); }
|
||||
|
||||
.floating-status-row { min-height: 54px; padding: 8px 10px; display: grid; grid-template-columns: 8px 1fr auto; gap: 9px; align-items: center; border-radius: var(--radius-md); background: var(--surface-subtle); }
|
||||
.floating-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--border-strong); }
|
||||
.floating-dot.connected { background: var(--success); }
|
||||
.floating-dot.connecting { background: var(--warning); }
|
||||
.floating-dot.negotiating { background: var(--warning); }
|
||||
.floating-dot.error { background: var(--danger); }
|
||||
.floating-status-row strong, .floating-status-row small { display: block; }
|
||||
.floating-status-row strong { font-size: var(--text-md); font-weight: 600; }
|
||||
.floating-status-row small { margin-top: 2px; color: var(--muted); font-size: var(--text-sm); }
|
||||
|
||||
.floating-agent-task { min-height: 46px; padding: 8px 8px 8px 12px; display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 8px; align-items: center; border-radius: var(--radius-md); background: var(--success-soft); }
|
||||
.floating-agent-task.paused, .floating-agent-task.waiting_for_human { background: var(--warning-soft); }
|
||||
.floating-agent-task strong, .floating-agent-task small { display: block; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.floating-agent-task strong { color: var(--success); font-size: var(--text-md); font-weight: 600; }
|
||||
.floating-agent-task.paused strong, .floating-agent-task.waiting_for_human strong { color: var(--warning); }
|
||||
.floating-agent-task small { margin-top: 3px; color: var(--muted); font-size: var(--text-sm); }
|
||||
|
||||
.floating-share-row { min-height: 54px; padding: 8px 10px; display: flex; align-items: center; justify-content: space-between; gap: 10px; border-radius: var(--radius-md); background: var(--surface-subtle); }
|
||||
.floating-share-row strong, .floating-share-row small { display: block; }
|
||||
.floating-share-row strong { font-size: var(--text-md); font-weight: 600; }
|
||||
.floating-share-row small { margin-top: 3px; color: var(--muted); font-size: var(--text-sm); }
|
||||
|
||||
.floating-handoff { min-height: 112px; padding: 12px; display: grid; align-content: space-between; gap: 12px; border: 1px solid color-mix(in srgb, var(--warning) 30%, var(--surface)); border-radius: var(--radius-md); background: var(--warning-soft); }
|
||||
.floating-handoff__copy { min-width: 0; display: grid; grid-template-columns: 18px minmax(0, 1fr); gap: 8px; align-items: start; }
|
||||
.floating-handoff__copy > svg { margin-top: 1px; color: var(--warning); }
|
||||
.floating-handoff__copy strong, .floating-handoff__copy small { display: block; }
|
||||
.floating-handoff__copy strong { color: var(--warning); font-size: var(--text-md); font-weight: 600; line-height: 17px; }
|
||||
.floating-handoff__copy small { margin-top: 4px; color: var(--muted); font-size: var(--text-sm); line-height: 16px; overflow-wrap: anywhere; }
|
||||
.floating-handoff__actions { display: grid; grid-template-columns: 1fr auto; gap: 6px; }
|
||||
|
||||
.floating-notice { margin: 0 10px 10px; padding: 8px 12px; border-radius: var(--radius-md); background: var(--danger-soft); color: var(--danger); font-size: var(--text-sm); line-height: 1.45; }
|
||||
.spin { animation: floating-spin .8s linear infinite; }
|
||||
@keyframes floating-spin { to { transform: rotate(360deg); } }
|
||||
@@ -0,0 +1,6 @@
|
||||
import { runBackground } from '@/app/background';
|
||||
|
||||
export default defineBackground({
|
||||
type: 'module',
|
||||
main: runBackground,
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Yakit Browser Agent</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="./main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,45 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { TooltipProvider } from '@/components/ui/tooltip';
|
||||
import { FloatingPanel } from '@/features/floating-panel/FloatingPanel';
|
||||
import type { ActiveTabInfo, BridgeStatus, ExtensionState } from '@/types/models';
|
||||
import { request } from '@/platform/messaging/runtime';
|
||||
import { watchTheme } from '@/platform/storage/appearance';
|
||||
import '@/styles/global.css';
|
||||
import '../agent.content/style.css';
|
||||
import './style.css';
|
||||
|
||||
watchTheme();
|
||||
|
||||
function FloatingApp() {
|
||||
const [initial, setInitial] = useState<{ state: ExtensionState; tab?: ActiveTabInfo; bridge: BridgeStatus }>();
|
||||
const [error, setError] = useState('');
|
||||
const hostChannel = new URLSearchParams(location.search).get('channel') || '';
|
||||
|
||||
useEffect(() => {
|
||||
const tabId = Number(new URLSearchParams(location.search).get('tabId'));
|
||||
void Promise.all([
|
||||
request('state.get'),
|
||||
Number.isSafeInteger(tabId) && tabId > 0
|
||||
? request('tab.get', { tabId }).catch(() => undefined)
|
||||
: Promise.resolve(undefined),
|
||||
request('bridge.status'),
|
||||
]).then(([state, tab, bridge]) => setInitial({ state, tab, bridge }))
|
||||
.catch((reason) => setError(reason instanceof Error ? reason.message : String(reason)));
|
||||
}, []);
|
||||
|
||||
if (error) return <div className="floating-frame-error">{error}</div>;
|
||||
if (!initial) return <div className="floating-frame-loading">正在加载</div>;
|
||||
return (
|
||||
<FloatingPanel
|
||||
initialState={initial.state}
|
||||
initialTab={initial.tab}
|
||||
initialBridge={initial.bridge}
|
||||
hostChannel={hostChannel}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
createRoot(document.getElementById('app')!).render(
|
||||
<TooltipProvider delayDuration={350}><FloatingApp /></TooltipProvider>,
|
||||
);
|
||||
@@ -0,0 +1,6 @@
|
||||
html, body, #app { width: 100%; height: 100%; min-width: 0; min-height: 0; margin: 0; overflow: hidden; }
|
||||
body { background: transparent; }
|
||||
.floating-panel.floating-panel--embedded { position: relative; inset: auto; width: 100%; height: auto; transform: none; filter: none; }
|
||||
.floating-panel--embedded .floating-panel__body { max-height: 100%; overflow: auto; box-shadow: none; }
|
||||
.floating-frame-loading, .floating-frame-error { height: 100%; display: grid; place-items: center; padding: 16px; box-sizing: border-box; color: var(--muted); background: var(--surface); font: 13px var(--font-sans); }
|
||||
.floating-frame-error { color: var(--danger); }
|
||||
@@ -0,0 +1,818 @@
|
||||
/* Options 工作台 —— 基于 src/styles/tokens.css 令牌,暗色由 html[data-theme='dark'] 自动切换 */
|
||||
|
||||
code, pre { font-family: var(--font-mono); }
|
||||
pre { margin: 0; }
|
||||
|
||||
input[type='checkbox'] { width: 15px; height: 15px; flex: 0 0 auto; padding: 0; accent-color: var(--primary); }
|
||||
|
||||
/* ---------- 原生按钮(组件库之外的 <button>) ---------- */
|
||||
.primary-button, .danger-button, .icon-button,
|
||||
.page-heading > button:not(.ui-button),
|
||||
.editor-actions > button:not(.ui-button),
|
||||
.panel-title > button:not(.ui-button) {
|
||||
min-height: 36px;
|
||||
padding: 0 14px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 7px;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--surface);
|
||||
color: var(--foreground);
|
||||
font-size: var(--text-md);
|
||||
font-weight: 600;
|
||||
line-height: 1;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
transition: background-color .15s ease, border-color .15s ease, color .15s ease, box-shadow .15s ease;
|
||||
}
|
||||
.page-heading > button:not(.ui-button):hover,
|
||||
.editor-actions > button:not(.ui-button):hover,
|
||||
.panel-title > button:not(.ui-button):hover { border-color: var(--muted); background: var(--surface-subtle); }
|
||||
.primary-button { border-color: var(--primary-strong); background: var(--primary-strong); color: var(--primary-on-strong); }
|
||||
.primary-button:hover { border-color: var(--primary-strong-hover); background: var(--primary-strong-hover); }
|
||||
.danger-button { border-color: color-mix(in srgb, var(--danger) 35%, var(--surface)); color: var(--danger); }
|
||||
.danger-button:hover { background: var(--danger-soft); }
|
||||
.icon-button { width: 34px; height: 34px; min-height: 34px; padding: 0; }
|
||||
.icon-button:hover { background: var(--surface-subtle); }
|
||||
.icon-button.danger { color: var(--danger); }
|
||||
.icon-button.danger:hover { background: var(--danger-soft); }
|
||||
.primary-button:disabled, .danger-button:disabled, .icon-button:disabled,
|
||||
.page-heading > button:not(.ui-button):disabled,
|
||||
.editor-actions > button:not(.ui-button):disabled { border-color: var(--border); background: var(--surface-subtle); color: var(--muted); cursor: not-allowed; }
|
||||
.primary-button:focus-visible, .danger-button:focus-visible, .icon-button:focus-visible,
|
||||
.page-heading > button:not(.ui-button):focus-visible,
|
||||
.editor-actions > button:not(.ui-button):focus-visible,
|
||||
.panel-title > button:not(.ui-button):focus-visible,
|
||||
.data-row:focus-visible, .network-row:focus-visible, .recording-traces button:focus-visible,
|
||||
.recording-pipeline-step > button:focus-visible,
|
||||
.task-workflow-list button:focus-visible, .context-node-list button:focus-visible,
|
||||
.sidebar nav button:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 3px var(--focus);
|
||||
}
|
||||
|
||||
/* ---------- 布局骨架 ---------- */
|
||||
.app-shell { min-height: 100vh; display: grid; grid-template-columns: 238px minmax(0, 1fr); }
|
||||
/* 所有单列纵向 grid 容器必须显式 minmax(0,1fr),否则子元素 max-content 会撑破窄屏 */
|
||||
.content-area, .section-view, .settings-form, .list-pane, .editor-pane, .rule-editor,
|
||||
.pairing-workspace, .panel-policy-settings, .grant-editor, .protocol-panel,
|
||||
.recording-section, .network-inspector, .context-primary, .context-inspector,
|
||||
.context-inspector > section, .context-diff, .context-inventory, .context-node-browser,
|
||||
.context-mode, .context-json, .context-utility-panel, .tab-picker, .tab-picker-group, .data-list,
|
||||
.task-workflow-list, .cookie-transfer, .network-artifact { grid-template-columns: minmax(0, 1fr); }
|
||||
.workspace { min-width: 0; position: relative; }
|
||||
.content-area { max-width: 1440px; margin: 0 auto; padding: 22px 28px 36px; display: grid; gap: 16px; }
|
||||
.workspace-loading { min-height: 100vh; display: flex; align-items: center; justify-content: center; gap: 10px; color: var(--muted); font-size: var(--text-md); }
|
||||
.spin { animation: spin .8s linear infinite; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
@keyframes pulse { 50% { opacity: .35; } }
|
||||
|
||||
/* ---------- 侧栏(与全局表面一致,暗色主题随令牌切换) ---------- */
|
||||
.sidebar { position: sticky; top: 0; height: 100vh; display: flex; flex-direction: column; border-right: 1px solid var(--border); background: var(--surface); color: var(--foreground); }
|
||||
.sidebar-brand { height: 64px; padding: 0 14px; display: flex; align-items: center; border-bottom: 1px solid var(--border); }
|
||||
.sidebar-brand .product-brand { width: 100%; color: var(--foreground); }
|
||||
.sidebar nav { min-height: 0; padding: 10px 10px 16px; overflow-y: auto; display: grid; gap: 10px; scrollbar-width: thin; }
|
||||
.sidebar-group { display: grid; gap: 2px; }
|
||||
.sidebar-group__label { min-height: 24px; padding: 0 10px; display: flex; align-items: center; gap: 6px; color: var(--muted); font-size: var(--text-xs); font-weight: 650; letter-spacing: .04em; }
|
||||
.sidebar-group__label svg { color: var(--primary); }
|
||||
.sidebar nav button { width: 100%; height: 40px; padding: 0 10px; display: grid; grid-template-columns: 20px 1fr 14px; align-items: center; gap: 8px; border: 0; border-radius: var(--radius-md); background: transparent; color: var(--muted-strong); font-size: var(--text-md); font-weight: 500; text-align: left; cursor: pointer; transition: background-color .14s ease, color .14s ease; }
|
||||
.sidebar nav button:hover { background: var(--surface-subtle); color: var(--foreground); }
|
||||
.sidebar nav button.active { background: var(--surface-subtle); color: var(--foreground); box-shadow: inset 3px 0 0 var(--primary); }
|
||||
.sidebar nav button.active svg:first-child { color: var(--primary); }
|
||||
.sidebar nav button > svg:last-child { opacity: 0; }
|
||||
.sidebar nav button.active > svg:last-child { opacity: 1; }
|
||||
.sidebar-theme { margin-top: auto; padding: 12px 14px; display: grid; gap: 7px; border-top: 1px solid var(--border); }
|
||||
.sidebar-theme > span { color: var(--muted); font-size: var(--text-xs); font-weight: 650; letter-spacing: .05em; text-transform: uppercase; }
|
||||
.sidebar-theme select { height: 34px; }
|
||||
.sidebar-status { min-height: 64px; padding: 12px 14px; display: grid; grid-template-columns: 30px minmax(0, 1fr); gap: 10px; align-items: center; border-top: 1px solid var(--border); }
|
||||
.sidebar-yakit-mark { position: relative; width: 28px; height: 28px; }
|
||||
.sidebar-yakit-mark .yakit-mark { width: 28px; height: 28px; border-radius: 6px; }
|
||||
.sidebar-status strong, .sidebar-status span { display: block; }
|
||||
.sidebar-status strong { font-size: var(--text-sm); line-height: 17px; }
|
||||
.sidebar-status div > span { margin-top: 2px; overflow: hidden; color: var(--muted); font-size: var(--text-xs); line-height: 14px; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.connection-dot { position: absolute; right: -2px; bottom: -2px; width: 10px; height: 10px; border: 2px solid var(--surface); border-radius: 50%; background: var(--muted); }
|
||||
.connection-dot.connected { background: #45b981; }
|
||||
.connection-dot.connecting, .connection-dot.negotiating { background: #e3a632; animation: pulse 1.3s infinite; }
|
||||
.connection-dot.error { background: #e06e6e; }
|
||||
|
||||
/* ---------- 顶栏 ---------- */
|
||||
.topbar { position: sticky; top: 0; z-index: 5; height: 60px; padding: 0 max(28px, (100% - 1440px) / 2 + 28px); display: flex; align-items: center; justify-content: space-between; gap: 16px; border-bottom: 1px solid var(--border); background: var(--background); }
|
||||
.topbar-tab { min-width: 0; flex: 0 1 420px; height: 38px; padding: 0 6px 0 11px; display: flex; align-items: center; gap: 8px; border: 1px solid var(--border); border-radius: var(--radius-md); background: var(--surface); box-shadow: var(--shadow-sm); }
|
||||
.topbar-tab__favicon { width: 16px; height: 16px; flex: 0 0 auto; display: grid; place-items: center; color: var(--muted); }
|
||||
.topbar-tab__favicon img { width: 16px; height: 16px; object-fit: contain; }
|
||||
.topbar-workspace-context { min-width: 0; display: flex; align-items: center; gap: 9px; color: var(--muted-strong); }
|
||||
.topbar-workspace-context > svg { color: var(--primary); }
|
||||
.topbar-workspace-context strong, .topbar-workspace-context small { display: block; }
|
||||
.topbar-workspace-context strong { color: var(--foreground); font-size: var(--text-sm); line-height: 16px; }
|
||||
.topbar-workspace-context small { margin-top: 1px; color: var(--muted); font-size: var(--text-xs); line-height: 14px; }
|
||||
.target-tab-select { min-width: 0; flex: 1; height: 36px; padding: 0 4px; border: 0; background: transparent; font-size: var(--text-md); }
|
||||
.target-tab-select:focus-visible { box-shadow: none; }
|
||||
.topbar-actions { display: flex; align-items: center; gap: 8px; }
|
||||
|
||||
/* ---------- 状态徽章 ---------- */
|
||||
.permission-state, .large-status, .agent-runtime-state, .capture-state {
|
||||
min-height: 30px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
padding: 3px 12px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
background: var(--surface);
|
||||
color: var(--muted-strong);
|
||||
font-size: var(--text-sm);
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.permission-state.enabled, .large-status.connected, .agent-runtime-state.running {
|
||||
border-color: color-mix(in srgb, var(--success) 38%, var(--surface));
|
||||
background: var(--success-soft);
|
||||
color: var(--success);
|
||||
}
|
||||
.large-status.connecting, .large-status.negotiating, .agent-runtime-state.paused, .agent-runtime-state.waiting_for_human {
|
||||
border-color: color-mix(in srgb, var(--warning) 42%, var(--surface));
|
||||
background: var(--warning-soft);
|
||||
color: var(--warning);
|
||||
}
|
||||
.large-status.error, .agent-runtime-state.revoked, .agent-runtime-state.expired {
|
||||
border-color: color-mix(in srgb, var(--danger) 38%, var(--surface));
|
||||
background: var(--danger-soft);
|
||||
color: var(--danger);
|
||||
}
|
||||
.capture-state i { width: 7px; height: 7px; border-radius: 50%; background: var(--border-strong); }
|
||||
.capture-state.active { border-color: color-mix(in srgb, var(--success) 38%, var(--surface)); background: var(--success-soft); color: var(--success); }
|
||||
.capture-state.active i { background: var(--success); animation: pulse 1.4s infinite; }
|
||||
|
||||
/* ---------- 页面通用 ---------- */
|
||||
.section-view { display: grid; gap: 16px; align-content: start; }
|
||||
.page-heading { display: flex; align-items: flex-end; justify-content: space-between; gap: 16px; }
|
||||
.page-heading h1 { margin: 0; font-size: var(--text-2xl); font-weight: 700; line-height: 28px; }
|
||||
.page-heading p { margin: 5px 0 0; color: var(--muted); font-size: var(--text-sm); line-height: 17px; }
|
||||
.section-view h2 { margin: 0; font-size: var(--text-lg); font-weight: 650; }
|
||||
.page-eyebrow { display: block; margin-bottom: 4px; color: var(--primary); font-size: var(--text-xs); font-weight: 700; letter-spacing: .06em; text-transform: uppercase; }
|
||||
|
||||
/* User-Agent 常用工具 */
|
||||
.ua-current-site { min-height: 82px; padding: 14px 16px; display: grid; grid-template-columns: minmax(210px, .9fr) minmax(260px, 1fr) auto; align-items: center; gap: 16px; border-top: 1px solid var(--border); border-bottom: 1px solid var(--border); background: var(--surface); }
|
||||
.ua-current-site > div:first-child { min-width: 0; }
|
||||
.ua-current-site > div:first-child span, .ua-current-site > div:first-child strong, .ua-current-site > div:first-child small { display: block; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.ua-current-site > div:first-child span { color: var(--muted); font-size: var(--text-xs); }
|
||||
.ua-current-site > div:first-child strong { margin-top: 3px; font-size: var(--text-lg); }
|
||||
.ua-current-site > div:first-child small { margin-top: 3px; color: var(--muted-strong); font-size: var(--text-sm); }
|
||||
.ua-management { min-height: 420px; display: grid; grid-template-columns: minmax(420px, 1.35fr) minmax(320px, .8fr); border-top: 1px solid var(--border); border-bottom: 1px solid var(--border); background: var(--surface); }
|
||||
.ua-assignments { min-width: 0; padding: 16px; border-right: 1px solid var(--border); }
|
||||
.ua-profile-editor { min-width: 0; padding: 16px; display: grid; gap: 12px; align-content: start; }
|
||||
.ua-assignment-list { margin-top: 12px; display: grid; }
|
||||
.ua-assignment-list > div { min-height: 58px; display: grid; grid-template-columns: minmax(160px, .55fr) minmax(220px, 1fr) 34px; align-items: center; gap: 12px; border-top: 1px solid var(--border); }
|
||||
.ua-assignment-list > div:last-child { border-bottom: 1px solid var(--border); }
|
||||
.ua-assignment-list strong, .ua-assignment-list small { display: block; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.ua-assignment-list strong { font-size: var(--text-sm); }
|
||||
.ua-assignment-list small { margin-top: 3px; color: var(--muted); font-size: var(--text-xs); }
|
||||
.ua-assignment-list code { overflow: hidden; color: var(--muted-strong); font-size: 10px; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.custom-ua-list { display: grid; }
|
||||
.custom-ua-list > div { min-height: 48px; display: grid; grid-template-columns: minmax(0, 1fr) 34px; align-items: center; border-top: 1px solid var(--border); }
|
||||
.custom-ua-list > div:last-child { border-bottom: 1px solid var(--border); }
|
||||
.custom-ua-list > div > button:first-child { min-width: 0; padding: 7px 0; border: 0; background: transparent; color: var(--foreground); text-align: left; cursor: pointer; }
|
||||
.custom-ua-list strong, .custom-ua-list small { display: block; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.custom-ua-list strong { font-size: var(--text-sm); }
|
||||
.custom-ua-list small { margin-top: 2px; color: var(--muted); font-size: 9px; }
|
||||
.empty-state { min-height: 130px; padding: 20px; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 9px; border-radius: var(--radius-md); color: var(--muted); font-size: var(--text-md); text-align: center; }
|
||||
.status-good { color: var(--success); font-weight: 600; }
|
||||
.status-error { color: var(--danger); font-weight: 600; }
|
||||
.status-muted { color: var(--muted); }
|
||||
.active-label { padding: 2px 7px; border-radius: 999px; background: var(--primary-soft); color: var(--primary-text); font-size: var(--text-xs); font-weight: 600; white-space: nowrap; }
|
||||
|
||||
/* 代码/报文块 —— 浅色主题用浅灰嵌底,暗色主题用深面板 */
|
||||
.network-packet, .invoke-result, .network-artifact pre, .context-json pre,
|
||||
.proxy-tools pre, .recording-values pre, .recording-evidence pre, .recording-recipe-result pre {
|
||||
margin: 0;
|
||||
padding: 12px 13px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-md);
|
||||
background: var(--surface-subtle);
|
||||
color: var(--foreground);
|
||||
font-size: var(--text-sm);
|
||||
line-height: 1.55;
|
||||
overflow: auto;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
}
|
||||
[data-theme='dark'] .network-packet, [data-theme='dark'] .invoke-result, [data-theme='dark'] .network-artifact pre,
|
||||
[data-theme='dark'] .context-json pre, [data-theme='dark'] .proxy-tools pre,
|
||||
[data-theme='dark'] .recording-values pre, [data-theme='dark'] .recording-evidence pre,
|
||||
[data-theme='dark'] .recording-recipe-result pre {
|
||||
border-color: #262c33;
|
||||
background: #12161b;
|
||||
color: #d6dde4;
|
||||
}
|
||||
|
||||
/* Toast */
|
||||
.toast { position: fixed; right: 22px; bottom: 22px; z-index: 30; max-width: 420px; display: flex; align-items: center; gap: 8px; padding: 11px 15px; border-radius: var(--radius-md); box-shadow: var(--shadow-md); font-size: var(--text-md); font-weight: 500; }
|
||||
.toast.ok { border: 1px solid color-mix(in srgb, var(--success) 38%, var(--surface)); background: var(--success-soft); color: var(--success); }
|
||||
.toast.error { border: 1px solid color-mix(in srgb, var(--danger) 38%, var(--surface)); background: var(--danger-soft); color: var(--danger); }
|
||||
|
||||
/* 人工接管横幅 */
|
||||
.handoff-banner { padding: 14px 18px; display: flex; align-items: center; gap: 13px; border-left: 3px solid var(--warning); border-radius: var(--radius-lg); background: var(--warning-soft); box-shadow: var(--shadow-sm); }
|
||||
.handoff-banner > svg { flex: 0 0 auto; color: var(--warning); }
|
||||
.handoff-banner__copy { min-width: 0; flex: 1; }
|
||||
.handoff-banner__copy span, .handoff-banner__copy strong, .handoff-banner__copy small { display: block; }
|
||||
.handoff-banner__copy span { color: var(--warning); font-size: var(--text-sm); font-weight: 650; }
|
||||
.handoff-banner__copy strong { margin-top: 2px; font-size: var(--text-md); line-height: 18px; overflow-wrap: anywhere; }
|
||||
.handoff-banner__copy small { margin-top: 3px; overflow: hidden; color: var(--muted); font-size: var(--text-sm); white-space: nowrap; text-overflow: ellipsis; }
|
||||
.handoff-banner__actions { display: flex; gap: 8px; }
|
||||
|
||||
/* ---------- 运行概览 ---------- */
|
||||
.task-command-bar { padding: 15px 18px; display: flex; align-items: center; justify-content: space-between; gap: 16px; border-radius: var(--radius-lg); background: var(--surface); box-shadow: var(--shadow-sm); }
|
||||
.task-site-identity { min-width: 0; display: flex; align-items: center; gap: 11px; }
|
||||
.task-site-identity > svg { flex: 0 0 auto; color: var(--primary); }
|
||||
.task-site-identity strong, .task-site-identity small { display: block; }
|
||||
.task-site-identity strong { font-size: var(--text-md); font-weight: 650; line-height: 18px; }
|
||||
.task-site-identity small { margin-top: 2px; color: var(--muted); font-size: var(--text-sm); }
|
||||
.task-quick-actions { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.task-status-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; }
|
||||
.task-status-grid section { min-width: 0; padding: 15px 16px 12px; display: grid; gap: 3px; align-content: start; border-radius: var(--radius-lg); background: var(--surface); box-shadow: var(--shadow-sm); }
|
||||
.task-status-grid section.needs-attention { box-shadow: inset 3px 0 0 var(--warning), var(--shadow-sm); }
|
||||
.task-status-grid span { color: var(--muted); font-size: var(--text-xs); font-weight: 650; letter-spacing: .04em; text-transform: uppercase; }
|
||||
.task-status-grid strong { margin-top: 4px; overflow: hidden; font-size: var(--text-lg); font-weight: 650; line-height: 19px; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.task-status-grid small { min-height: 32px; color: var(--muted); font-size: var(--text-sm); line-height: 16px; }
|
||||
.task-status-grid button { margin: 8px -6px 0; padding: 4px 6px; display: flex; align-items: center; justify-content: space-between; border: 0; border-radius: var(--radius-sm); background: transparent; color: var(--primary-text); font-size: var(--text-sm); font-weight: 600; cursor: pointer; }
|
||||
.task-status-grid button:hover { background: var(--primary-soft); }
|
||||
.task-workflow-list { display: grid; gap: 10px; }
|
||||
.task-workflow-list button { min-height: 62px; padding: 10px 16px; display: grid; grid-template-columns: 22px minmax(0, 1fr) 16px; gap: 13px; align-items: center; border: 0; border-radius: var(--radius-lg); background: var(--surface); box-shadow: var(--shadow-sm); color: var(--foreground); text-align: left; cursor: pointer; transition: background-color .14s ease; }
|
||||
.task-workflow-list button:hover { background: var(--surface-subtle); }
|
||||
.task-workflow-list button > svg:first-child { color: var(--muted-strong); }
|
||||
.task-workflow-list button:hover > svg:first-child { color: var(--primary); }
|
||||
.task-workflow-list button > svg:last-child { color: var(--muted); }
|
||||
.task-workflow-list strong, .task-workflow-list small { display: block; }
|
||||
.task-workflow-list strong { font-size: var(--text-md); font-weight: 650; line-height: 18px; }
|
||||
.task-workflow-list small { margin-top: 2px; color: var(--muted); font-size: var(--text-sm); line-height: 16px; }
|
||||
|
||||
/* ---------- 操作记录 ---------- */
|
||||
.activity-view .activity-heading-actions, .network-heading-actions { display: flex; align-items: center; gap: 8px; }
|
||||
.agent-runtime-band { padding: 15px 18px; border-radius: var(--radius-lg); background: var(--surface); box-shadow: var(--shadow-sm); }
|
||||
.agent-runtime-summary { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto; gap: 18px; align-items: center; }
|
||||
.agent-runtime-summary span { color: var(--muted); font-size: var(--text-xs); font-weight: 650; letter-spacing: .04em; text-transform: uppercase; }
|
||||
.agent-runtime-summary strong, .agent-runtime-summary small { display: block; }
|
||||
.agent-runtime-summary strong { margin-top: 4px; overflow: hidden; font-size: var(--text-lg); font-weight: 650; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.agent-runtime-summary small { margin-top: 2px; color: var(--muted); font-size: var(--text-sm); }
|
||||
.agent-runtime-controls { display: flex; gap: 8px; }
|
||||
.agent-action-list { margin-top: 14px; display: grid; border-top: 1px solid var(--border); }
|
||||
.agent-action-row { padding: 8px 2px; display: grid; grid-template-columns: 12px 84px minmax(160px, 1.4fr) minmax(80px, .6fr) 110px 76px; gap: 10px; align-items: center; border-bottom: 1px solid var(--border); font-size: var(--text-sm); }
|
||||
.agent-action-row code { overflow: hidden; font-size: var(--text-sm); white-space: nowrap; text-overflow: ellipsis; }
|
||||
.agent-action-row strong { font-size: var(--text-sm); }
|
||||
.agent-action-row strong.success { color: var(--success); }
|
||||
.agent-action-row strong.error { color: var(--danger); }
|
||||
.agent-actions-empty { margin-top: 14px; padding: 14px 4px 2px; color: var(--muted); font-size: var(--text-sm); }
|
||||
.action-state { width: 8px; height: 8px; border-radius: 50%; background: var(--border-strong); }
|
||||
.action-state.success { background: var(--success); }
|
||||
.action-state.error { background: var(--danger); }
|
||||
.action-state.running { background: var(--primary); animation: pulse 1.2s infinite; }
|
||||
.activity-subheading { margin-top: 6px; display: flex; align-items: flex-end; justify-content: space-between; gap: 14px; }
|
||||
.activity-subheading p { margin: 4px 0 0; color: var(--muted); font-size: var(--text-sm); }
|
||||
.activity-loading { min-height: 120px; display: flex; align-items: center; justify-content: center; gap: 8px; color: var(--muted); font-size: var(--text-md); }
|
||||
.activity-loading.error { color: var(--danger); }
|
||||
.activity-table { border-radius: var(--radius-lg); background: var(--surface); box-shadow: var(--shadow-sm); overflow: hidden; }
|
||||
.activity-table__head, .activity-table__row { padding: 0 16px; display: grid; grid-template-columns: 150px 86px minmax(150px, 1.1fr) minmax(150px, 1.2fr) 88px 72px; gap: 12px; align-items: center; }
|
||||
.activity-table__head { min-height: 38px; border-bottom: 1px solid var(--border); color: var(--muted); font-size: var(--text-xs); font-weight: 650; letter-spacing: .04em; text-transform: uppercase; }
|
||||
.activity-table__row { min-height: 42px; border-bottom: 1px solid var(--border); font-size: var(--text-sm); }
|
||||
.activity-table__row:last-child { border-bottom: 0; }
|
||||
.activity-table__row > * { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.activity-table__row code { font-size: var(--text-sm); }
|
||||
.audit-outcome.success { color: var(--success); font-weight: 600; }
|
||||
.audit-outcome.error { color: var(--danger); font-weight: 600; }
|
||||
|
||||
/* ---------- 分栏编辑页(代理配置 / 代理规则 / UA / Cookie) ---------- */
|
||||
.split-view { grid-template-columns: minmax(280px, 360px) minmax(0, 1fr); gap: 16px; align-items: start; }
|
||||
.split-view, .rule-layout { display: grid; }
|
||||
.rule-layout { grid-template-columns: minmax(0, 1fr) minmax(320px, 380px); gap: 16px; align-items: start; }
|
||||
.list-pane, .editor-pane { min-width: 0; display: grid; gap: 14px; align-content: start; }
|
||||
.editor-pane { padding: 18px; border-radius: var(--radius-lg); background: var(--surface); box-shadow: var(--shadow-sm); }
|
||||
.editor-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
|
||||
.editor-heading p { margin: 4px 0 0; color: var(--muted); font-size: var(--text-sm); word-break: break-all; }
|
||||
.data-list { display: grid; gap: 8px; }
|
||||
.data-row { min-height: 58px; padding: 8px 12px; display: grid; grid-template-columns: 30px minmax(0, 1fr) auto auto 15px; gap: 10px; align-items: center; border: 0; border-radius: var(--radius-lg); background: var(--surface); box-shadow: var(--shadow-sm); color: var(--foreground); text-align: left; cursor: pointer; }
|
||||
.data-row:hover { background: var(--surface-subtle); }
|
||||
.data-row.selected { box-shadow: inset 3px 0 0 var(--primary), var(--shadow-sm); }
|
||||
.data-row > svg:last-child { color: var(--muted); }
|
||||
.data-row strong, .data-row small { display: block; }
|
||||
.data-row strong { font-size: var(--text-md); font-weight: 600; }
|
||||
.data-row small { margin-top: 2px; overflow: hidden; color: var(--muted); font-size: var(--text-sm); white-space: nowrap; text-overflow: ellipsis; }
|
||||
.row-icon { width: 30px; height: 30px; display: grid; place-items: center; border-radius: var(--radius-md); background: var(--surface-subtle); color: var(--muted-strong); }
|
||||
.form-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
|
||||
.form-grid .ui-field:has(textarea), .form-grid .check-row { grid-column: 1 / -1; }
|
||||
.check-row { display: flex; align-items: center; gap: 8px; font-size: var(--text-md); }
|
||||
.editor-actions { display: flex; gap: 8px; }
|
||||
.rule-editor { min-width: 0; padding: 18px; display: grid; gap: 13px; align-content: start; border-radius: var(--radius-lg); background: var(--surface); box-shadow: var(--shadow-sm); }
|
||||
.rule-editor > h2 { margin-bottom: 2px; }
|
||||
.rule-editor > p { margin: -4px 0 0; color: var(--muted); font-size: var(--text-sm); line-height: 1.5; }
|
||||
|
||||
.rule-table { border-radius: var(--radius-lg); background: var(--surface); box-shadow: var(--shadow-sm); overflow: hidden; }
|
||||
.table-head, .table-row { padding: 0 16px; display: grid; gap: 12px; align-items: center; }
|
||||
.table-head { min-height: 38px; border-bottom: 1px solid var(--border); color: var(--muted); font-size: var(--text-xs); font-weight: 650; letter-spacing: .04em; text-transform: uppercase; }
|
||||
.table-row { min-height: 46px; border-bottom: 1px solid var(--border); font-size: var(--text-md); }
|
||||
.table-row:last-child { border-bottom: 0; }
|
||||
.table-row > * { min-width: 0; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.table-row code { font-size: var(--text-sm); }
|
||||
.rule-table .table-head, .rule-table .table-row { grid-template-columns: minmax(110px, 1fr) minmax(180px, 2fr) minmax(110px, 1fr) 64px 34px; }
|
||||
|
||||
/* Cookie Editor */
|
||||
.url-bar { display: flex; align-items: center; gap: 12px; }
|
||||
.url-bar input { flex: 1; }
|
||||
.url-bar > span { flex: 0 0 auto; color: var(--muted); font-size: var(--text-sm); }
|
||||
.cookie-toolbar { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||
.cookie-toolbar select { width: auto; min-width: 108px; }
|
||||
.cookie-toolbar .ui-button { margin-left: auto; }
|
||||
.network-search { position: relative; min-width: 200px; flex: 1; }
|
||||
.network-search > svg { position: absolute; left: 11px; top: 50%; transform: translateY(-50%); color: var(--muted); pointer-events: none; }
|
||||
.network-search input { padding-left: 31px; }
|
||||
.cookie-layout { display: grid; grid-template-columns: minmax(0, 1fr) minmax(320px, 380px); gap: 16px; align-items: start; }
|
||||
.cookie-table { border-radius: var(--radius-lg); background: var(--surface); box-shadow: var(--shadow-sm); overflow: hidden; }
|
||||
.cookie-columns { padding: 0 14px; display: grid; grid-template-columns: 24px minmax(120px, 1fr) minmax(150px, 1.2fr) minmax(120px, .9fr) minmax(110px, .8fr) 34px; gap: 10px; align-items: center; }
|
||||
.cookie-group__heading { padding: 8px 14px 5px; display: flex; align-items: baseline; gap: 8px; color: var(--muted); font-size: var(--text-xs); font-weight: 650; letter-spacing: .03em; text-transform: uppercase; }
|
||||
.cookie-group__heading span { font-weight: 500; text-transform: none; }
|
||||
.cookie-name-button { padding: 0; overflow: hidden; border: 0; background: transparent; color: var(--foreground); text-align: left; cursor: pointer; }
|
||||
.cookie-name-button strong { display: block; overflow: hidden; font-size: var(--text-md); font-weight: 600; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.cookie-name-button:hover strong { color: var(--primary-text); }
|
||||
.cookie-value { min-width: 0; padding: 3px 6px; overflow: hidden; color: var(--muted-strong); font-size: var(--text-sm); white-space: nowrap; text-overflow: ellipsis; }
|
||||
.cookie-columns > span > small { display: block; overflow: hidden; color: var(--muted); font-size: var(--text-sm); line-height: 15px; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.tag-list { display: flex; flex-wrap: wrap; gap: 4px; }
|
||||
.tag-list i { padding: 1px 6px; border-radius: 999px; background: var(--surface-subtle); color: var(--muted-strong); font-size: var(--text-xs); font-style: normal; font-weight: 600; }
|
||||
.cookie-editor-pane { position: sticky; top: 76px; }
|
||||
.cookie-transfer { display: grid; gap: 10px; }
|
||||
.cookie-transfer .segmented { justify-self: start; }
|
||||
.transfer-status { color: var(--muted); font-size: var(--text-sm); }
|
||||
|
||||
/* 分段选择器 */
|
||||
.segmented { display: inline-flex; gap: 2px; padding: 3px; border: 1px solid var(--border); border-radius: var(--radius-md); background: var(--surface-subtle); }
|
||||
.segmented button { min-width: 72px; height: 30px; padding: 0 12px; border: 0; border-radius: 6px; background: transparent; color: var(--muted); font-size: var(--text-sm); font-weight: 600; cursor: pointer; }
|
||||
.segmented button.active { background: var(--surface); color: var(--foreground); box-shadow: var(--shadow-sm); }
|
||||
.segmented button:disabled { opacity: .45; cursor: not-allowed; }
|
||||
|
||||
/* ---------- 网络活动 ---------- */
|
||||
.network-control-bar { padding: 10px 18px; display: flex; flex-wrap: wrap; gap: 12px; align-items: center; border-radius: var(--radius-lg); background: var(--surface); box-shadow: var(--shadow-sm); }
|
||||
.network-control-bar > label { display: flex; align-items: center; gap: 10px; cursor: pointer; }
|
||||
.network-control-bar > label > span { display: block; }
|
||||
.network-control-bar strong { font-size: var(--text-md); font-weight: 600; line-height: 17px; }
|
||||
.network-control-bar small { display: block; margin-top: 1px; color: var(--muted); font-size: var(--text-sm); }
|
||||
.network-control-bar .network-search { flex: 1; min-width: 180px; }
|
||||
.network-error { padding: 12px 16px; display: flex; align-items: center; gap: 9px; border-radius: var(--radius-lg); background: var(--danger-soft); color: var(--danger); font-size: var(--text-md); }
|
||||
.network-layout { display: grid; grid-template-columns: minmax(0, 1fr) minmax(360px, 440px); gap: 16px; align-items: start; }
|
||||
.network-timeline { border-radius: var(--radius-lg); background: var(--surface); box-shadow: var(--shadow-sm); overflow: hidden; }
|
||||
.network-table-head { padding: 0 16px; min-height: 38px; display: grid; grid-template-columns: 62px 58px minmax(0, 1fr) 88px 72px; gap: 10px; align-items: center; border-bottom: 1px solid var(--border); color: var(--muted); font-size: var(--text-xs); font-weight: 650; letter-spacing: .04em; text-transform: uppercase; }
|
||||
.network-row { width: 100%; padding: 9px 16px; display: grid; grid-template-columns: 62px 58px minmax(0, 1fr) 88px 72px; gap: 10px; align-items: center; border: 0; border-bottom: 1px solid var(--border); background: transparent; color: var(--foreground); font-size: var(--text-sm); text-align: left; cursor: pointer; }
|
||||
.network-row:last-child { border-bottom: 0; }
|
||||
.network-row:hover { background: var(--surface-subtle); }
|
||||
.network-row.selected { background: var(--primary-soft); box-shadow: inset 3px 0 0 var(--primary); }
|
||||
.network-row > span { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.method { font-size: var(--text-sm); font-weight: 700; }
|
||||
.method-get { color: var(--success); }
|
||||
.method-post { color: var(--primary-text); }
|
||||
.method-put, .method-patch { color: var(--warning); }
|
||||
.method-delete { color: var(--danger); }
|
||||
.network-target strong, .network-target small { display: block; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.network-target strong { font-size: var(--text-md); font-weight: 600; }
|
||||
.network-target small { margin-top: 1px; color: var(--muted); font-size: var(--text-sm); }
|
||||
.network-inspector { min-width: 0; padding: 16px; display: grid; gap: 14px; align-content: start; border-radius: var(--radius-lg); background: var(--surface); box-shadow: var(--shadow-sm); position: sticky; top: 76px; }
|
||||
.network-inspector__heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
|
||||
.network-inspector__heading > div { min-width: 0; }
|
||||
.network-inspector__heading > div > span { color: var(--muted); font-size: var(--text-xs); font-weight: 700; letter-spacing: .04em; text-transform: uppercase; }
|
||||
.network-inspector__heading strong, .network-inspector__heading small { display: block; overflow: hidden; text-overflow: ellipsis; }
|
||||
.network-inspector__heading strong { margin-top: 3px; font-size: var(--text-lg); font-weight: 650; word-break: break-all; }
|
||||
.network-inspector__heading small { margin-top: 3px; color: var(--muted); font-size: var(--text-sm); white-space: nowrap; }
|
||||
.network-meta { margin: 0; display: grid; grid-template-columns: 1fr 1fr; gap: 10px 14px; }
|
||||
.network-meta > div { min-width: 0; }
|
||||
.network-meta dt { color: var(--muted); font-size: var(--text-xs); font-weight: 650; letter-spacing: .04em; text-transform: uppercase; }
|
||||
.network-meta dd { margin: 3px 0 0; overflow: hidden; font-size: var(--text-md); white-space: nowrap; text-overflow: ellipsis; }
|
||||
.network-packet-heading { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
|
||||
.network-packet-heading > strong { font-size: var(--text-md); font-weight: 650; }
|
||||
.network-packet-heading > div { display: flex; gap: 6px; align-items: center; }
|
||||
.network-packet { max-height: 320px; white-space: pre; }
|
||||
.network-limitations { padding: 9px 12px; display: flex; gap: 8px; align-items: flex-start; border-radius: var(--radius-md); background: var(--warning-soft); color: var(--warning); font-size: var(--text-sm); line-height: 1.5; }
|
||||
.network-preview-empty { padding: 18px 14px; display: flex; align-items: flex-start; gap: 9px; border-radius: var(--radius-md); background: var(--surface-subtle); color: var(--muted); font-size: var(--text-sm); line-height: 1.55; }
|
||||
.network-preview-empty svg { flex: 0 0 auto; margin-top: 1px; }
|
||||
.network-artifact { display: grid; gap: 8px; }
|
||||
.network-artifact > div:first-child { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
|
||||
.network-artifact strong { font-size: var(--text-md); font-weight: 650; }
|
||||
.network-artifact pre { max-height: 260px; }
|
||||
|
||||
/* 浏览器现场录制:Trace -> Pipeline -> 证据与页面函数 */
|
||||
.recording-section { display: grid; gap: 12px; }
|
||||
.recording-heading { min-height: 54px; display: grid; grid-template-columns: minmax(180px, 1fr) auto minmax(230px, 1fr); align-items: end; gap: 16px; }
|
||||
.recording-heading__identity > span { display: block; margin-bottom: 3px; color: var(--primary); font-size: var(--text-xs); font-weight: 700; }
|
||||
.recording-heading__actions { min-width: 230px; display: flex; align-items: center; justify-content: flex-end; gap: 8px; }
|
||||
.recording-heading__actions.is-inactive { visibility: hidden; pointer-events: none; }
|
||||
.recording-mode-switch { height: 34px; padding: 3px; display: grid; grid-template-columns: repeat(3, auto); gap: 2px; border-radius: var(--radius-md); background: var(--surface-subtle); }
|
||||
.recording-mode-switch button { height: 28px; padding: 0 9px; display: inline-flex; align-items: center; justify-content: center; gap: 5px; border: 0; border-radius: var(--radius-sm); background: transparent; color: var(--muted-strong); font: inherit; font-size: var(--text-xs); font-weight: 600; cursor: pointer; }
|
||||
.recording-mode-switch button:disabled { cursor: not-allowed; opacity: .48; }
|
||||
.recording-mode-switch button.is-selected { background: var(--surface); color: var(--foreground); box-shadow: var(--shadow-sm); }
|
||||
.recording-mode-switch button.is-selected svg { color: var(--primary); }
|
||||
.recording-mode-panel[hidden] { display: none; }
|
||||
.recording-state { min-height: 30px; padding: 0 10px; display: inline-flex; align-items: center; gap: 7px; border: 1px solid var(--border); border-radius: 999px; color: var(--muted-strong); font-size: var(--text-sm); font-weight: 600; white-space: nowrap; }
|
||||
.recording-state i { width: 7px; height: 7px; border-radius: 50%; background: var(--border-strong); }
|
||||
.recording-state.is-active { border-color: color-mix(in srgb, var(--danger) 32%, var(--border)); background: var(--danger-soft); color: var(--danger); }
|
||||
.recording-state.is-active i { background: var(--danger); animation: pulse 1.2s infinite; }
|
||||
.recording-controls { min-height: 52px; padding: 8px 10px 8px 14px; display: flex; align-items: center; gap: 10px; border: 1px solid var(--border); border-radius: var(--radius-md); background: var(--surface); }
|
||||
.recording-controls > label { min-width: 220px; display: flex; align-items: center; gap: 9px; }
|
||||
.recording-controls > label span { min-width: 0; }
|
||||
.recording-controls > label strong, .recording-controls > label small { display: block; }
|
||||
.recording-controls > label strong { font-size: var(--text-sm); font-weight: 650; }
|
||||
.recording-controls > label small { margin-top: 1px; color: var(--muted); font-size: var(--text-xs); }
|
||||
.recording-summary { min-width: 0; margin-left: auto; overflow: hidden; color: var(--muted); font-size: var(--text-sm); white-space: nowrap; text-overflow: ellipsis; }
|
||||
.recording-navigation { min-height: 58px; padding: 9px 13px; display: grid; grid-template-columns: 22px minmax(0, 1fr); align-items: center; gap: 10px; border: 1px solid color-mix(in srgb, var(--warning) 32%, var(--border)); border-radius: var(--radius-md); background: var(--warning-soft); }
|
||||
.recording-navigation > svg { color: var(--warning); }
|
||||
.recording-navigation.is-restored { border-color: color-mix(in srgb, var(--success) 32%, var(--border)); background: var(--success-soft); }
|
||||
.recording-navigation.is-restored > svg { color: var(--success); }
|
||||
.recording-navigation.is-failed { border-color: color-mix(in srgb, var(--danger) 30%, var(--border)); background: var(--danger-soft); }
|
||||
.recording-navigation.is-failed > svg { color: var(--danger); }
|
||||
.recording-navigation > div { min-width: 0; }
|
||||
.recording-navigation strong,
|
||||
.recording-navigation span,
|
||||
.recording-navigation code { display: block; }
|
||||
.recording-navigation strong { font-size: var(--text-sm); }
|
||||
.recording-navigation span { margin-top: 2px; color: var(--muted-strong); font-size: var(--text-xs); line-height: 1.45; }
|
||||
.recording-navigation code { margin-top: 3px; overflow: hidden; color: var(--muted-strong); font-size: 10px; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.recording-error { min-height: 46px; padding: 8px 12px; display: flex; align-items: center; gap: 8px; border-left: 3px solid var(--danger); background: var(--danger-soft); color: var(--danger); font-size: var(--text-sm); }
|
||||
.recording-error .ui-button { margin-left: auto; }
|
||||
.recording-empty { min-height: 230px; padding: 30px; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px; border: 1px solid var(--border); border-radius: var(--radius-md); background: var(--surface); text-align: center; }
|
||||
.recording-empty svg { color: var(--border-strong); }
|
||||
.recording-empty strong { font-size: var(--text-lg); }
|
||||
.recording-empty span { max-width: 520px; color: var(--muted); font-size: var(--text-sm); line-height: 1.55; }
|
||||
.recording-workbench { min-height: 560px; display: grid; grid-template-columns: minmax(210px, 240px) minmax(340px, 1fr) minmax(310px, 380px); overflow: hidden; border: 1px solid var(--border); border-radius: var(--radius-md); background: var(--surface); }
|
||||
.recording-traces, .recording-pipeline, .recording-inspector { min-width: 0; min-height: 0; }
|
||||
.recording-traces { border-right: 1px solid var(--border); background: var(--surface-subtle); }
|
||||
.recording-traces > header, .recording-pipeline > header { min-height: 45px; padding: 0 13px; display: flex; align-items: center; justify-content: space-between; gap: 8px; border-bottom: 1px solid var(--border); }
|
||||
.recording-traces > header strong, .recording-pipeline > header strong { font-size: var(--text-sm); font-weight: 700; }
|
||||
.recording-traces > header > div strong, .recording-traces > header > div small { display: block; }
|
||||
.recording-traces > header > div small { margin-top: 1px; color: var(--muted); font-size: 10px; font-weight: 500; }
|
||||
.recording-traces > header > span { min-width: 22px; height: 20px; padding: 0 6px; display: inline-grid; place-items: center; border-radius: 999px; background: var(--surface); color: var(--muted); font-size: var(--text-xs); }
|
||||
.recording-traces > div { max-height: 700px; overflow: auto; }
|
||||
.recording-traces button { position: relative; width: 100%; min-height: 72px; padding: 10px 11px; display: grid; grid-template-columns: 31px minmax(0, 1fr); gap: 0 9px; align-items: start; border: 0; border-bottom: 1px solid var(--border); background: transparent; color: var(--foreground); text-align: left; cursor: pointer; }
|
||||
.recording-traces button:hover { background: var(--surface); }
|
||||
.recording-traces button.is-selected { background: var(--surface); box-shadow: inset 3px 0 0 var(--primary); }
|
||||
.recording-trace-index { width: 31px; height: 25px; display: grid; place-items: center; border: 1px solid var(--border); border-radius: 999px; background: var(--surface); color: var(--muted-strong); font: 700 10px/1 var(--font-mono); letter-spacing: .03em; }
|
||||
.recording-traces button.is-selected .recording-trace-index { border-color: color-mix(in srgb, var(--primary) 55%, var(--border)); background: var(--primary-soft); color: var(--primary-text); }
|
||||
.recording-traces button > span:nth-child(2) { min-width: 0; }
|
||||
.recording-traces button strong, .recording-traces button small { display: block; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.recording-traces button strong { font-size: var(--text-sm); font-weight: 650; }
|
||||
.recording-traces button small { margin-top: 3px; color: var(--muted); font-size: var(--text-xs); }
|
||||
.recording-traces button time { grid-column: 2; margin-top: 5px; display: flex; align-items: center; gap: 7px; color: var(--muted); font-size: 10px; }
|
||||
.recording-traces button time i { padding-left: 7px; border-left: 1px solid var(--border); color: var(--muted-strong); font-style: normal; }
|
||||
.recording-pipeline { border-right: 1px solid var(--border); }
|
||||
.recording-pipeline > header > div { min-width: 0; }
|
||||
.recording-pipeline > header > div strong, .recording-pipeline > header > div span { display: block; }
|
||||
.recording-pipeline > header > div span { margin-top: 1px; color: var(--muted); font-size: var(--text-xs); }
|
||||
.recording-pipeline > header > i { display: inline-flex; align-items: center; gap: 4px; color: var(--success); font-size: var(--text-xs); font-style: normal; white-space: nowrap; }
|
||||
.recording-pipeline__body { max-height: 700px; padding: 13px 13px 18px 10px; overflow: auto; }
|
||||
.recording-pipeline-step { position: relative; display: grid; grid-template-columns: 31px minmax(0, 1fr); align-items: stretch; }
|
||||
.recording-step-rail { min-height: 73px; display: grid; grid-template-rows: 30px minmax(0, 1fr); justify-items: center; color: var(--muted); }
|
||||
.recording-step-rail > i { position: relative; z-index: 1; width: 25px; height: 25px; display: grid; place-items: center; border: 1px solid var(--border); border-radius: 50%; background: var(--surface); color: var(--muted-strong); font: 700 9px/1 var(--font-mono); font-style: normal; }
|
||||
.recording-step-rail > span { width: 1px; min-height: 43px; display: grid; align-items: end; justify-items: center; background: var(--border); color: var(--muted); }
|
||||
.recording-step-rail > span svg { width: 11px; margin: 0 0 -5px; padding: 1px 0; background: var(--background); }
|
||||
.recording-pipeline-step.is-navigation .recording-step-rail > i { border-color: color-mix(in srgb, var(--warning) 55%, var(--border)); background: var(--warning-soft); color: var(--warning); }
|
||||
.recording-pipeline-step > button { width: 100%; min-height: 73px; padding: 10px; display: grid; grid-template-columns: 34px minmax(0, 1fr) auto; gap: 10px; align-items: center; border: 1px solid var(--border); border-radius: var(--radius-sm); background: var(--surface); color: var(--foreground); text-align: left; cursor: pointer; transition: border-color .14s ease, background-color .14s ease, box-shadow .14s ease; }
|
||||
.recording-pipeline-step > button:hover { border-color: var(--border-strong); background: var(--surface-subtle); }
|
||||
.recording-pipeline-step > button.is-linked { border-left: 3px solid var(--success); }
|
||||
.recording-pipeline-step > button.is-selected { border-color: var(--primary); box-shadow: 0 0 0 2px var(--focus); }
|
||||
.recording-pipeline-step.is-navigation > button { margin: 4px 0 9px; border-style: dashed; border-color: color-mix(in srgb, var(--warning) 42%, var(--border)); background: color-mix(in srgb, var(--warning-soft) 45%, var(--surface)); }
|
||||
.recording-event-icon { width: 34px; height: 34px; display: grid; place-items: center; border-radius: var(--radius-sm); background: var(--surface-subtle); color: var(--muted-strong); }
|
||||
.recording-event-icon.kind-crypto { background: var(--warning-soft); color: var(--warning); }
|
||||
.recording-event-icon.kind-fetch, .recording-event-icon.kind-xhr, .recording-event-icon.kind-form { background: var(--primary-soft); color: var(--primary-text); }
|
||||
.recording-event-icon.kind-websocket { background: var(--success-soft); color: var(--success); }
|
||||
.recording-event-icon.kind-navigation { background: var(--warning-soft); color: var(--warning); }
|
||||
.recording-pipeline-step button > span:nth-child(2) { min-width: 0; }
|
||||
.recording-pipeline-step small, .recording-pipeline-step strong, .recording-pipeline-step em, .recording-pipeline-step b { display: block; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.recording-pipeline-step small { color: var(--muted); font-size: 10px; font-weight: 650; }
|
||||
.recording-pipeline-step strong { margin-top: 2px; font-size: var(--text-sm); font-weight: 650; }
|
||||
.recording-pipeline-step em { margin-top: 2px; color: var(--muted); font-size: var(--text-xs); font-style: normal; }
|
||||
.recording-pipeline-step b { margin-top: 4px; color: var(--warning); font-size: 10px; font-weight: 650; }
|
||||
.recording-event-meta { display: grid; justify-items: end; gap: 5px; }
|
||||
.recording-event-meta i { padding: 2px 6px; border-radius: 999px; background: var(--warning-soft); color: var(--warning); font-size: 10px; font-style: normal; white-space: nowrap; }
|
||||
.recording-event-meta i.is-history { background: var(--surface-strong); color: var(--muted); }
|
||||
.recording-event-meta time { color: var(--muted); font-size: var(--text-xs); white-space: nowrap; }
|
||||
.recording-event-meta small { color: var(--muted); font-size: 10px; font-weight: 500; white-space: nowrap; }
|
||||
.recording-inspector > dl.recording-navigation-detail { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.recording-inspector > dl.recording-navigation-detail div:nth-child(odd) { border-left: 0; }
|
||||
.recording-inspector > dl.recording-navigation-detail div:nth-child(n + 3) { border-top: 1px solid var(--border); }
|
||||
.recording-navigation-detail dd { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.recording-column-empty { min-height: 180px; padding: 24px; display: grid; place-items: center; color: var(--muted); font-size: var(--text-sm); text-align: center; }
|
||||
.recording-inspector { max-height: 746px; padding: 14px; overflow: auto; display: grid; gap: 14px; align-content: start; }
|
||||
.recording-inspector > header { min-width: 0; display: flex; align-items: flex-start; justify-content: space-between; gap: 10px; }
|
||||
.recording-inspector > header > div { min-width: 0; }
|
||||
.recording-inspector > header span, .recording-inspector > header strong, .recording-inspector > header small { display: block; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.recording-inspector > header span { color: var(--primary); font-size: var(--text-xs); font-weight: 700; }
|
||||
.recording-inspector > header strong { margin-top: 3px; font-size: var(--text-lg); }
|
||||
.recording-inspector > header small { margin-top: 3px; color: var(--muted); font-size: var(--text-xs); }
|
||||
.recording-inspector > header > i { flex: 0 0 auto; color: var(--muted); font-size: var(--text-xs); font-style: normal; }
|
||||
.recording-inspector > header > i.is-error { color: var(--danger); font-weight: 700; }
|
||||
.recording-inspector > dl { margin: 0; display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); border-top: 1px solid var(--border); border-bottom: 1px solid var(--border); }
|
||||
.recording-inspector > dl div { min-width: 0; padding: 9px 5px; text-align: center; }
|
||||
.recording-inspector > dl div + div { border-left: 1px solid var(--border); }
|
||||
.recording-inspector dt { color: var(--muted); font-size: 10px; }
|
||||
.recording-inspector dd { margin: 3px 0 0; overflow: hidden; font-size: var(--text-sm); font-weight: 650; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.recording-values { display: grid; gap: 6px; }
|
||||
.recording-values > strong { font-size: var(--text-sm); }
|
||||
.recording-values pre, .recording-evidence pre { max-height: 160px; }
|
||||
.recording-evidence { border-top: 1px solid var(--border); border-bottom: 1px solid var(--border); }
|
||||
.recording-evidence summary { padding: 9px 0; color: var(--muted-strong); font-size: var(--text-sm); font-weight: 600; cursor: pointer; }
|
||||
.recording-evidence[open] { padding-bottom: 10px; }
|
||||
.profile-inference { padding: 11px 0 0; display: grid; gap: 10px; border-top: 2px solid var(--primary); }
|
||||
.profile-inference.is-medium { border-top-color: var(--warning); }
|
||||
.profile-inference.is-low { border-top-color: var(--border-strong); }
|
||||
.profile-inference__heading { min-width: 0; display: grid; grid-template-columns: 28px minmax(0, 1fr) auto; align-items: start; gap: 8px; }
|
||||
.profile-inference__mark { width: 28px; height: 28px; display: grid; place-items: center; border-radius: var(--radius-sm); background: var(--primary-soft); color: var(--primary); }
|
||||
.profile-inference__heading > span:nth-child(2) { min-width: 0; }
|
||||
.profile-inference__heading small, .profile-inference__heading strong { display: block; }
|
||||
.profile-inference__heading small { color: var(--primary-text); font-size: var(--text-xs); font-weight: 700; }
|
||||
.profile-inference__heading strong { margin-top: 2px; font-size: var(--text-sm); line-height: 1.45; }
|
||||
.profile-inference__heading > i { min-height: 23px; padding: 0 7px; display: inline-flex; align-items: center; gap: 4px; border: 1px solid color-mix(in srgb, var(--success) 34%, var(--border)); border-radius: 999px; color: var(--success); font-size: 10px; font-style: normal; font-weight: 650; white-space: nowrap; }
|
||||
.profile-inference.is-medium .profile-inference__heading > i { border-color: color-mix(in srgb, var(--warning) 34%, var(--border)); color: var(--warning); }
|
||||
.profile-inference.is-low .profile-inference__heading > i { border-color: var(--border); color: var(--muted-strong); }
|
||||
.profile-inference__flow { min-width: 0; padding: 8px 9px; display: flex; align-items: center; flex-wrap: wrap; gap: 4px; border-top: 1px solid var(--border); border-bottom: 1px solid var(--border); background: var(--surface-subtle); }
|
||||
.profile-inference__flow > span { min-width: 0; display: inline-flex; align-items: center; gap: 4px; color: var(--muted); }
|
||||
.profile-inference__flow code { max-width: 210px; overflow: hidden; color: var(--foreground); font-size: 10px; font-weight: 600; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.profile-inference__sources { display: grid; gap: 5px; }
|
||||
.profile-inference__sources > div { min-width: 0; padding: 7px 8px; display: grid; grid-template-columns: 24px minmax(0, 1fr); gap: 2px 7px; border: 1px solid var(--border); border-radius: var(--radius-sm); background: var(--surface-subtle); }
|
||||
.profile-inference__sources span { grid-row: span 2; width: 21px; height: 21px; display: grid; place-items: center; border-radius: 50%; background: var(--warning-soft); color: var(--warning); font-size: 9px; font-weight: 700; }
|
||||
.profile-inference__sources strong, .profile-inference__sources small { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.profile-inference__sources strong { font-size: var(--text-xs); }
|
||||
.profile-inference__sources small { color: var(--muted); font-size: 10px; }
|
||||
.profile-inference__arguments { margin: 0; display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 7px 12px; }
|
||||
.profile-inference__arguments > div { min-width: 0; }
|
||||
.profile-inference__arguments dt { color: var(--muted); font-size: 10px; }
|
||||
.profile-inference__arguments dd { margin: 2px 0 0; overflow: hidden; font-size: var(--text-xs); font-weight: 600; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.profile-inference__evidence { border-top: 1px solid var(--border); }
|
||||
.profile-inference__evidence summary { padding-top: 8px; color: var(--muted-strong); font-size: var(--text-xs); font-weight: 650; cursor: pointer; }
|
||||
.profile-inference__evidence ol { margin: 8px 0 0; padding: 0; display: grid; gap: 6px; list-style: none; }
|
||||
.profile-inference__evidence li { display: grid; grid-template-columns: 7px minmax(0, 1fr); align-items: start; gap: 7px; color: var(--muted-strong); font-size: var(--text-xs); line-height: 1.45; }
|
||||
.profile-inference__evidence li > i { width: 7px; height: 7px; margin-top: 4px; border-radius: 50%; background: var(--border-strong); }
|
||||
.profile-inference__evidence li[data-strength='proven'] > i { background: var(--success); }
|
||||
.profile-inference__evidence li[data-strength='supported'] > i { background: var(--primary); }
|
||||
.profile-inference__next { padding: 9px 0 0; display: grid; gap: 9px; border-top: 1px solid var(--border); }
|
||||
.profile-inference__next > span { color: var(--muted-strong); font-size: var(--text-xs); line-height: 1.5; }
|
||||
.profile-inference__next .ui-button { justify-self: stretch; }
|
||||
.recording-deep-action { padding: 11px; display: grid; gap: 10px; border: 1px solid color-mix(in srgb, var(--primary) 34%, var(--border)); border-radius: var(--radius-md); background: var(--primary-soft); }
|
||||
.recording-deep-action > div:first-child { display: flex; align-items: center; gap: 8px; color: var(--primary); }
|
||||
.recording-deep-action > div:first-child span { min-width: 0; }
|
||||
.recording-deep-action strong, .recording-deep-action small { display: block; }
|
||||
.recording-deep-action strong { color: var(--foreground); font-size: var(--text-sm); }
|
||||
.recording-deep-action small { margin-top: 2px; color: var(--muted-strong); font-size: var(--text-xs); }
|
||||
.recording-recipe-action { padding: 11px; display: grid; gap: 10px; border: 1px solid color-mix(in srgb, var(--warning) 34%, var(--border)); border-radius: var(--radius-md); background: var(--warning-soft); }
|
||||
.recording-recipe-action > div:first-child { display: flex; align-items: center; gap: 8px; color: var(--warning); }
|
||||
.recording-recipe-action > div:first-child span { min-width: 0; }
|
||||
.recording-recipe-action strong, .recording-recipe-action small { display: block; }
|
||||
.recording-recipe-action strong { color: var(--foreground); font-size: var(--text-sm); }
|
||||
.recording-recipe-action small { margin-top: 2px; color: var(--muted-strong); font-size: var(--text-xs); }
|
||||
.recording-recipe-editor { display: grid; gap: 9px; }
|
||||
.recording-recipe-editor > label, .recording-recipe-editor > div:not(.recording-recipe-editor__actions) { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; }
|
||||
.recording-recipe-editor > label { grid-template-columns: minmax(0, 1fr); }
|
||||
.recording-recipe-editor label { min-width: 0; display: grid; gap: 4px; }
|
||||
.recording-recipe-editor label > span { color: var(--muted-strong); font-size: var(--text-xs); font-weight: 600; }
|
||||
.recording-recipe-editor__actions, .recording-recipe-buttons { display: flex; justify-content: flex-end; gap: 7px; }
|
||||
.recording-recipes { padding-top: 13px; display: grid; gap: 9px; border-top: 1px solid var(--border); }
|
||||
.recording-recipes__heading { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
||||
.recording-recipes__heading strong { font-size: var(--text-sm); }
|
||||
.recording-recipes__heading select { width: min(190px, 58%); }
|
||||
.recording-recipe-meta { display: flex; align-items: center; justify-content: space-between; gap: 8px; color: var(--muted-strong); font-size: var(--text-xs); }
|
||||
.recording-recipe-meta i { color: var(--primary-text); font-style: normal; }
|
||||
.recording-recipes textarea { min-height: 82px; resize: vertical; font-family: var(--font-mono); font-size: var(--text-sm); }
|
||||
.recording-recipe-result { display: grid; gap: 6px; }
|
||||
.recording-recipe-result > div { min-width: 0; display: grid; grid-template-columns: minmax(0, 1fr) auto 34px; align-items: center; gap: 7px; }
|
||||
.recording-recipe-result strong { overflow: hidden; font-size: var(--text-sm); white-space: nowrap; text-overflow: ellipsis; }
|
||||
.recording-recipe-result span { color: var(--muted); font-size: var(--text-xs); white-space: nowrap; }
|
||||
.recording-recipe-result pre { max-height: 190px; }
|
||||
|
||||
/* ---------- 登录态工作区 ---------- */
|
||||
.context-options { display: flex; flex-wrap: wrap; gap: 12px; align-items: center; }
|
||||
.context-options select { width: auto; min-width: 240px; }
|
||||
.context-options > span { overflow: hidden; color: var(--muted); font-size: var(--text-sm); white-space: nowrap; text-overflow: ellipsis; }
|
||||
.context-mode { display: grid; gap: 16px; }
|
||||
.context-mode-tabs { justify-self: start; }
|
||||
.context-empty { min-height: 300px; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px; border-radius: var(--radius-lg); background: var(--surface); box-shadow: var(--shadow-sm); color: var(--muted); }
|
||||
.context-empty svg { color: var(--border-strong); }
|
||||
.context-empty strong { color: var(--muted-strong); font-size: var(--text-lg); }
|
||||
.context-empty span { font-size: var(--text-sm); }
|
||||
.context-session-strip { padding: 6px; display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 6px; border-radius: var(--radius-lg); background: var(--surface); box-shadow: var(--shadow-sm); }
|
||||
.context-session-strip > div { min-width: 0; padding: 10px 12px; display: grid; gap: 2px; align-content: start; border-radius: var(--radius-md); background: var(--surface-subtle); }
|
||||
.context-session-strip small { color: var(--muted); font-size: var(--text-xs); font-weight: 650; letter-spacing: .04em; text-transform: uppercase; }
|
||||
.context-session-strip strong { overflow: hidden; font-size: var(--text-lg); font-weight: 650; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.context-session-strip span { overflow: hidden; color: var(--muted); font-size: var(--text-sm); white-space: nowrap; text-overflow: ellipsis; }
|
||||
.context-session-strip .auth-state { grid-template-columns: 20px minmax(0, 1fr) auto; align-items: center; gap: 8px; }
|
||||
.context-session-strip .auth-state > span { min-width: 0; display: grid; gap: 2px; }
|
||||
.context-session-strip .auth-state > svg { color: var(--muted); }
|
||||
.context-session-strip .auth-state.authenticated > svg, .context-session-strip .auth-state.authenticated strong { color: var(--success); }
|
||||
.context-session-strip .auth-state.unauthenticated strong { color: var(--danger); }
|
||||
.context-session-strip .auth-state > i { color: var(--muted); font-size: var(--text-sm); font-style: normal; }
|
||||
.context-workspace { display: grid; grid-template-columns: minmax(0, 1fr) minmax(320px, 380px); gap: 16px; align-items: start; }
|
||||
.context-primary { min-width: 0; display: grid; gap: 16px; }
|
||||
.context-diff, .context-inventory, .context-node-browser { padding: 16px 18px; display: grid; gap: 13px; border-radius: var(--radius-lg); background: var(--surface); box-shadow: var(--shadow-sm); }
|
||||
.context-section-heading { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.context-section-heading span { color: var(--muted); font-size: var(--text-sm); }
|
||||
.diff-state { padding: 3px 9px; border-radius: 999px; background: var(--surface-subtle); color: var(--muted-strong); font-size: var(--text-xs); font-weight: 650; }
|
||||
.diff-state.changed, .diff-state.document_changed { background: var(--warning-soft); color: var(--warning); }
|
||||
.diff-summary { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; }
|
||||
.diff-summary > span { padding: 10px 12px; display: grid; gap: 2px; border-radius: var(--radius-md); background: var(--surface-subtle); color: var(--muted); font-size: var(--text-sm); }
|
||||
.diff-summary strong { color: var(--foreground); font-size: var(--text-xl); font-weight: 700; }
|
||||
.diff-events { display: grid; gap: 5px; }
|
||||
.diff-events span { display: flex; gap: 7px; align-items: baseline; font-size: var(--text-sm); }
|
||||
.diff-events i { color: var(--success); font-style: normal; font-weight: 700; }
|
||||
.diff-events .removed i { color: var(--danger); }
|
||||
.diff-events .removed { color: var(--muted); text-decoration: line-through; }
|
||||
.context-inventory-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; }
|
||||
.context-inventory-grid > div { min-width: 0; padding: 12px 13px; display: grid; gap: 8px; align-content: start; border-radius: var(--radius-md); background: var(--surface-subtle); }
|
||||
.context-inventory-grid > div > strong { font-size: var(--text-xs); font-weight: 650; letter-spacing: .04em; text-transform: uppercase; color: var(--muted); }
|
||||
.context-inventory-grid > div > span { font-size: var(--text-xl); font-weight: 700; }
|
||||
.context-inventory-grid ul { margin: 0; padding: 0; display: grid; gap: 6px; list-style: none; }
|
||||
.context-inventory-grid li { display: flex; align-items: center; gap: 7px; font-size: var(--text-sm); }
|
||||
.context-inventory-grid li b { font-weight: 600; }
|
||||
.context-inventory-grid li span, .context-inventory-grid li small { overflow: hidden; color: var(--muted); white-space: nowrap; text-overflow: ellipsis; }
|
||||
.context-inventory-grid li i { width: 7px; height: 7px; flex: 0 0 auto; border-radius: 50%; background: var(--border-strong); }
|
||||
.context-inventory-grid li i.ready, .context-inventory-grid li i.document { background: var(--success); }
|
||||
.context-inventory-grid li i.history { background: var(--primary); }
|
||||
.context-inventory-grid p { margin: 0; color: var(--muted); font-size: var(--text-sm); line-height: 1.5; }
|
||||
.context-node-search { position: relative; width: 240px; }
|
||||
.context-node-search > svg { position: absolute; left: 10px; top: 50%; transform: translateY(-50%); color: var(--muted); pointer-events: none; }
|
||||
.context-node-search input { height: 32px; padding-left: 29px; font-size: var(--text-sm); }
|
||||
.context-node-head { padding: 0 12px 6px; display: grid; grid-template-columns: minmax(0, 1.6fr) 92px 62px 64px; gap: 10px; border-bottom: 1px solid var(--border); color: var(--muted); font-size: var(--text-xs); font-weight: 650; letter-spacing: .04em; text-transform: uppercase; }
|
||||
.context-node-list { max-height: 320px; overflow-y: auto; display: grid; }
|
||||
.context-node-list > button { width: 100%; padding: 8px 12px; display: grid; grid-template-columns: minmax(0, 1.6fr) 92px 62px 64px; gap: 10px; align-items: center; border: 0; border-bottom: 1px solid var(--border); background: transparent; color: var(--foreground); font-size: var(--text-sm); text-align: left; cursor: pointer; }
|
||||
.context-node-list > button:last-child { border-bottom: 0; }
|
||||
.context-node-list > button:hover { background: var(--surface-subtle); }
|
||||
.context-node-list > button.active { background: var(--primary-soft); box-shadow: inset 3px 0 0 var(--primary); }
|
||||
.context-node-list strong, .context-node-list small { display: block; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.context-node-list strong { font-size: var(--text-md); font-weight: 600; }
|
||||
.context-node-list small { margin-top: 1px; color: var(--muted); }
|
||||
.context-node-list code { overflow: hidden; font-size: var(--text-sm); white-space: nowrap; text-overflow: ellipsis; }
|
||||
.context-node-list i { padding: 1px 6px; border-radius: 999px; background: var(--surface-subtle); color: var(--muted); font-size: var(--text-xs); font-style: normal; font-weight: 600; text-align: center; }
|
||||
.context-node-list i.ready { background: var(--success-soft); color: var(--success); }
|
||||
.context-inspector { min-width: 0; display: grid; gap: 16px; position: sticky; top: 76px; }
|
||||
.context-inspector > section { padding: 16px; display: grid; gap: 13px; border-radius: var(--radius-lg); background: var(--surface); box-shadow: var(--shadow-sm); }
|
||||
.context-inspector-empty { padding: 14px 12px; border-radius: var(--radius-md); background: var(--surface-subtle); color: var(--muted); font-size: var(--text-sm); line-height: 1.5; }
|
||||
.context-node-error { padding: 9px 12px; display: flex; gap: 8px; align-items: flex-start; border-radius: var(--radius-md); background: var(--danger-soft); color: var(--danger); font-size: var(--text-sm); }
|
||||
.node-identity { display: grid; gap: 3px; }
|
||||
.node-identity code { color: var(--muted); font-size: var(--text-sm); }
|
||||
.node-identity strong { font-size: var(--text-lg); font-weight: 650; overflow-wrap: anywhere; }
|
||||
.node-identity span { color: var(--muted); font-size: var(--text-sm); overflow-wrap: anywhere; }
|
||||
.node-properties { margin: 0; display: grid; grid-template-columns: 1fr 1fr; gap: 10px 12px; }
|
||||
.node-properties dt { color: var(--muted); font-size: var(--text-xs); font-weight: 650; letter-spacing: .04em; text-transform: uppercase; }
|
||||
.node-properties dd { margin: 3px 0 0; overflow: hidden; font-size: var(--text-md); white-space: nowrap; text-overflow: ellipsis; }
|
||||
.node-actions { display: flex; gap: 8px; }
|
||||
.node-value-editor { display: flex; gap: 8px; align-items: flex-end; }
|
||||
.node-value-editor .ui-field { flex: 1; }
|
||||
.auth-evidence ul { margin: 0; padding-left: 18px; display: grid; gap: 6px; font-size: var(--text-sm); line-height: 1.5; }
|
||||
.signal-names { display: grid; gap: 4px; font-size: var(--text-sm); }
|
||||
.signal-names strong { font-weight: 650; }
|
||||
.signal-names span { color: var(--muted); overflow-wrap: anywhere; }
|
||||
.context-utility-panel { max-width: 760px; display: grid; gap: 13px; align-content: start; }
|
||||
.context-utility-panel > p { margin: 0; color: var(--muted); font-size: var(--text-sm); }
|
||||
.eval-mode { justify-self: start; }
|
||||
.eval-warning { padding: 10px 13px; display: flex; gap: 9px; align-items: flex-start; border-radius: var(--radius-md); background: var(--primary-soft); color: var(--primary-text); font-size: var(--text-sm); line-height: 1.5; }
|
||||
.eval-warning svg { flex: 0 0 auto; margin-top: 1px; }
|
||||
.code-editor { font-family: var(--font-mono); font-size: var(--text-sm); }
|
||||
.eval-result-meta { display: flex; flex-wrap: wrap; gap: 7px; }
|
||||
.eval-result-meta span { padding: 3px 9px; border-radius: 999px; background: var(--surface-subtle); color: var(--muted-strong); font-size: var(--text-xs); font-weight: 600; }
|
||||
.invoke-result { max-height: 320px; }
|
||||
.context-json { display: grid; gap: 10px; }
|
||||
.context-json pre { max-height: 560px; }
|
||||
.panel-title { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.panel-title > span { font-size: var(--text-lg); font-weight: 650; }
|
||||
|
||||
/* ---------- 引擎连接 ---------- */
|
||||
.managed-policy-banner { padding: 12px 16px; display: flex; gap: 10px; align-items: flex-start; border-radius: var(--radius-lg); background: var(--warning-soft); box-shadow: var(--shadow-sm); }
|
||||
.managed-policy-banner > svg { flex: 0 0 auto; margin-top: 2px; color: var(--warning); }
|
||||
.managed-policy-banner strong, .managed-policy-banner small { display: block; }
|
||||
.managed-policy-banner strong { font-size: var(--text-md); font-weight: 650; }
|
||||
.managed-policy-banner small { margin-top: 2px; color: var(--muted-strong); font-size: var(--text-sm); }
|
||||
.managed-policy-banner i { display: block; margin-top: 3px; color: var(--warning); font-size: var(--text-sm); font-style: normal; }
|
||||
.bridge-identity-strip { padding: 13px 18px; display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 14px; border-radius: var(--radius-lg); background: var(--surface); box-shadow: var(--shadow-sm); }
|
||||
.bridge-identity-strip > div { min-width: 0; }
|
||||
.bridge-identity-strip span { color: var(--muted); font-size: var(--text-xs); font-weight: 650; letter-spacing: .04em; text-transform: uppercase; }
|
||||
.bridge-identity-strip code, .bridge-identity-strip strong { display: block; margin-top: 4px; overflow: hidden; font-size: var(--text-md); white-space: nowrap; text-overflow: ellipsis; }
|
||||
.engine-layout { display: grid; grid-template-columns: minmax(0, 1fr) minmax(320px, 400px); gap: 16px; align-items: start; }
|
||||
.settings-form { min-width: 0; display: grid; gap: 16px; }
|
||||
.pairing-workspace { padding: 18px; display: grid; gap: 15px; border-radius: var(--radius-lg); background: var(--surface); box-shadow: var(--shadow-sm); }
|
||||
.pairing-workspace.pending { box-shadow: inset 3px 0 0 var(--warning), var(--shadow-sm); }
|
||||
.pairing-workspace.paired { box-shadow: inset 3px 0 0 var(--success), var(--shadow-sm); }
|
||||
.pairing-workspace.error { box-shadow: inset 3px 0 0 var(--danger), var(--shadow-sm); }
|
||||
.pairing-workspace__heading { display: flex; gap: 13px; align-items: flex-start; }
|
||||
.pairing-icon { width: 40px; height: 40px; flex: 0 0 auto; display: grid; place-items: center; border-radius: var(--radius-md); background: var(--primary-soft); color: var(--primary-text); }
|
||||
.pairing-workspace__heading p { margin: 4px 0 0; color: var(--muted); font-size: var(--text-sm); line-height: 1.5; }
|
||||
/* 未配对 idle 态:居中 hero,配对是该页此时的主任务 */
|
||||
.pairing-workspace.idle { padding: 30px 22px 22px; justify-items: center; text-align: center; }
|
||||
.pairing-workspace.idle .pairing-workspace__heading { flex-direction: column; align-items: center; gap: 12px; }
|
||||
.pairing-workspace.idle .pairing-icon { width: 52px; height: 52px; border-radius: var(--radius-lg); }
|
||||
.pairing-workspace.idle .pairing-icon svg { width: 24px; height: 24px; }
|
||||
.pairing-workspace.idle .editor-actions { justify-content: center; }
|
||||
.pairing-code { padding: 16px; display: grid; gap: 4px; justify-items: center; border-radius: var(--radius-md); background: var(--surface-subtle); text-align: center; }
|
||||
.pairing-code span { color: var(--muted); font-size: var(--text-xs); font-weight: 650; letter-spacing: .05em; text-transform: uppercase; }
|
||||
.pairing-code strong { font-family: var(--font-mono); font-size: 30px; font-weight: 700; letter-spacing: .12em; }
|
||||
.pairing-code small { color: var(--muted); font-size: var(--text-sm); }
|
||||
.paired-engine-meta { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
|
||||
.paired-engine-meta > div { min-width: 0; }
|
||||
.paired-engine-meta span { color: var(--muted); font-size: var(--text-xs); font-weight: 650; letter-spacing: .04em; text-transform: uppercase; }
|
||||
.paired-engine-meta code { display: block; margin-top: 3px; overflow: hidden; font-size: var(--text-sm); white-space: nowrap; text-overflow: ellipsis; }
|
||||
.advanced-connection { border-radius: var(--radius-lg); background: var(--surface); box-shadow: var(--shadow-sm); }
|
||||
.advanced-connection > summary { padding: 15px 18px; font-size: var(--text-md); font-weight: 650; cursor: pointer; list-style-position: inside; }
|
||||
.advanced-connection__body { padding: 2px 18px 16px; display: grid; gap: 13px; }
|
||||
.toggle-row { display: flex; align-items: center; justify-content: space-between; gap: 14px; cursor: pointer; }
|
||||
.toggle-row > span { min-width: 0; }
|
||||
.toggle-row strong { font-size: var(--text-md); font-weight: 600; }
|
||||
.toggle-row small { display: block; margin-top: 2px; color: var(--muted); font-size: var(--text-sm); }
|
||||
.panel-policy-settings { padding: 18px; display: grid; gap: 14px; border-radius: var(--radius-lg); background: var(--surface); box-shadow: var(--shadow-sm); }
|
||||
.panel-policy-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
|
||||
.grant-editor { padding: 18px; display: grid; gap: 14px; border-radius: var(--radius-lg); background: var(--surface); box-shadow: var(--shadow-sm); }
|
||||
.grant-editor > p { margin: -6px 0 0; color: var(--muted); font-size: var(--text-sm); line-height: 1.5; }
|
||||
.tab-picker { display: grid; gap: 10px; }
|
||||
.tab-picker-group { padding: 6px; display: grid; gap: 2px; border-radius: var(--radius-md); background: var(--surface-subtle); }
|
||||
.tab-picker-group label { padding: 7px 9px; display: flex; align-items: flex-start; gap: 10px; border-radius: var(--radius-sm); cursor: pointer; }
|
||||
.tab-picker-group label:hover { background: var(--surface); }
|
||||
.tab-picker-group label > input { margin-top: 2px; }
|
||||
.tab-picker-group label > span { min-width: 0; }
|
||||
.tab-picker-group label strong, .tab-picker-group label small { display: block; }
|
||||
.tab-picker-group label strong { font-size: var(--text-md); font-weight: 600; }
|
||||
.tab-picker-group label small { margin-top: 1px; overflow: hidden; color: var(--muted); font-size: var(--text-sm); white-space: nowrap; text-overflow: ellipsis; }
|
||||
.tab-picker-group .frame-target { margin-left: 25px; }
|
||||
.grant-options { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
|
||||
.grant-risk-toggle { padding: 10px 13px; border-radius: var(--radius-md); background: var(--warning-soft); }
|
||||
.grant-scope-list { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.grant-scope-list span { padding: 3px 9px; border-radius: 999px; background: var(--surface-subtle); color: var(--muted-strong); font-size: var(--text-xs); font-weight: 600; }
|
||||
.grant-status { padding: 11px 14px; display: grid; gap: 2px; border-radius: var(--radius-md); background: var(--success-soft); }
|
||||
.grant-status strong { color: var(--success); font-size: var(--text-md); font-weight: 650; }
|
||||
.grant-status span { color: var(--muted-strong); font-size: var(--text-sm); }
|
||||
.protocol-panel { padding: 18px; display: grid; gap: 4px; align-content: start; border-radius: var(--radius-lg); background: var(--surface); box-shadow: var(--shadow-sm); position: sticky; top: 76px; }
|
||||
.protocol-panel h2 { margin-bottom: 10px; }
|
||||
.protocol-panel > div { padding: 9px 0; display: grid; gap: 3px; border-bottom: 1px solid var(--border); }
|
||||
.protocol-panel > div:last-child { border-bottom: 0; }
|
||||
.protocol-panel code { color: var(--primary-text); font-size: var(--text-sm); font-weight: 600; }
|
||||
.protocol-panel span { color: var(--muted); font-size: var(--text-sm); line-height: 1.5; }
|
||||
|
||||
/* ---------- 窄屏适配 ---------- */
|
||||
@media (max-width: 1080px) {
|
||||
.task-status-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.network-layout, .context-workspace, .engine-layout, .rule-layout, .cookie-layout, .split-view { grid-template-columns: minmax(0, 1fr); }
|
||||
.network-inspector, .context-inspector, .cookie-editor-pane, .protocol-panel { position: static; }
|
||||
.recording-workbench { grid-template-columns: 220px minmax(0, 1fr); }
|
||||
.recording-inspector { grid-column: 1 / -1; max-height: none; border-top: 1px solid var(--border); }
|
||||
.recording-pipeline { border-right: 0; }
|
||||
.proxy-tools { grid-template-columns: minmax(0, 1fr); }
|
||||
.bridge-identity-strip { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
||||
.ua-management { grid-template-columns: minmax(0, 1fr); }
|
||||
.ua-assignments { border-right: 0; border-bottom: 1px solid var(--border); }
|
||||
.ua-current-site { grid-template-columns: minmax(200px, .8fr) minmax(240px, 1fr); }
|
||||
.ua-current-site > .editor-actions { grid-column: 1 / 3; justify-content: flex-end; }
|
||||
.recording-heading { grid-template-columns: minmax(0, 1fr) auto; }
|
||||
.recording-heading__actions { grid-column: 1 / -1; min-width: 0; }
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.app-shell { grid-template-columns: minmax(0, 1fr); }
|
||||
.sidebar { position: static; height: auto; border-right: 0; border-bottom: 1px solid var(--border); }
|
||||
.sidebar-brand { height: 56px; }
|
||||
.sidebar nav { display: flex; overflow-x: auto; overflow-y: hidden; padding: 10px; }
|
||||
.sidebar-group { display: contents; }
|
||||
.sidebar-group__label { display: none; }
|
||||
.sidebar nav button { width: auto; flex: 0 0 auto; grid-template-columns: 18px max-content; white-space: nowrap; }
|
||||
.sidebar nav button > svg:last-child { display: none; }
|
||||
.sidebar-theme { margin-top: 0; grid-auto-flow: column; align-items: center; justify-content: space-between; }
|
||||
.sidebar-theme select { width: 150px; }
|
||||
.sidebar-status { min-height: 54px; }
|
||||
.topbar { padding: 0 16px; }
|
||||
.content-area { padding: 16px; }
|
||||
.page-heading { flex-direction: column; align-items: flex-start; }
|
||||
.ua-current-site { grid-template-columns: minmax(0, 1fr); }
|
||||
.ua-current-site > .editor-actions { grid-column: auto; justify-content: stretch; }
|
||||
.ua-current-site > .editor-actions .ui-button { flex: 1; }
|
||||
.ua-assignment-list > div { grid-template-columns: minmax(0, 1fr) 34px; }
|
||||
.ua-assignment-list code { display: none; }
|
||||
.task-command-bar, .agent-runtime-summary { flex-direction: column; display: flex; align-items: stretch; }
|
||||
.task-status-grid, .context-session-strip, .diff-summary, .context-inventory-grid, .grant-options, .panel-policy-grid, .form-grid, .paired-engine-meta { grid-template-columns: minmax(0, 1fr); }
|
||||
.agent-action-row { grid-template-columns: 12px 76px minmax(0, 1fr) 76px; }
|
||||
.agent-action-row span:nth-child(4), .agent-action-row span:last-child { display: none; }
|
||||
.activity-table__head, .activity-table__row { grid-template-columns: 120px minmax(0, 1fr) 80px; }
|
||||
.activity-table__head span:nth-child(2), .activity-table__head span:nth-child(4), .activity-table__head span:last-child,
|
||||
.activity-table__row > span:nth-child(2), .activity-table__row > span:nth-child(4), .activity-table__row > span:last-child { display: none; }
|
||||
.network-table-head, .network-row { grid-template-columns: 56px 50px minmax(0, 1fr) 66px; }
|
||||
.network-table-head span:nth-child(4), .network-row > span:nth-child(4) { display: none; }
|
||||
.recording-heading { grid-template-columns: minmax(0, 1fr); align-items: flex-start; }
|
||||
.recording-mode-switch { justify-self: start; }
|
||||
.recording-heading__actions { grid-column: auto; justify-self: stretch; justify-content: flex-start; }
|
||||
.recording-controls { flex-wrap: wrap; }
|
||||
.recording-summary { width: 100%; order: 3; margin-left: 0; }
|
||||
.recording-navigation { grid-template-columns: 22px minmax(0, 1fr); }
|
||||
.recording-navigation > .ui-button { grid-column: 1 / -1; justify-self: stretch; }
|
||||
.recording-workbench { grid-template-columns: minmax(0, 1fr); }
|
||||
.recording-traces, .recording-pipeline { border-right: 0; border-bottom: 1px solid var(--border); }
|
||||
.recording-traces > div, .recording-pipeline__body { max-height: 420px; }
|
||||
.recording-inspector { grid-column: auto; border-top: 0; }
|
||||
.recording-event-meta i { display: none; }
|
||||
.cookie-columns { grid-template-columns: 24px minmax(0, 1fr) minmax(0, 1fr) 34px; }
|
||||
.cookie-columns > span:nth-child(4), .cookie-columns > span:nth-child(5) { display: none; }
|
||||
.cookie-toolbar select { min-width: 0; flex: 1; }
|
||||
.context-node-head { display: none; }
|
||||
.context-node-list > button { grid-template-columns: minmax(0, 1fr) 64px; }
|
||||
.context-node-list code, .context-node-list i { display: none; }
|
||||
.rule-table .table-head, .rule-table .table-row { grid-template-columns: minmax(0, 1fr) 34px; }
|
||||
.rule-table .table-row > span, .rule-table .table-head > span { display: none; }
|
||||
.proxy-rule-table .table-head, .proxy-rule-table .table-row { grid-template-columns: minmax(0, 1fr) 34px; }
|
||||
.proxy-rule-table .table-row > span, .proxy-rule-table .table-row > svg, .proxy-rule-table .table-head > span { display: none; }
|
||||
}
|
||||
@@ -0,0 +1,857 @@
|
||||
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react';
|
||||
import { browser, type Browser } from 'wxt/browser';
|
||||
import {
|
||||
Activity, AlertTriangle, Bot, Braces, Check, ChevronRight, CircleGauge, CloudDownload, Cookie, Copy,
|
||||
Database, Download, Eye, Fingerprint, History, KeyRound, MousePointer2, Network, Play, Power, Radio,
|
||||
RefreshCw, Route, Save, Search, Send, Server, ShieldCheck, Square, Trash2, Upload, UserRoundCog, Wrench, X,
|
||||
} from 'lucide-react';
|
||||
import { ProductBrand, YakitMark } from '@/components/brand/Brand';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Field } from '@/components/ui/field';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import {
|
||||
AUDIT_CATEGORY_LABELS, AUDIT_OUTCOME_LABELS, HANDOFF_REASON_LABELS, waitingHandoff,
|
||||
} from '@/features/handoff/presentation';
|
||||
import { cookieKey, cookieRemovalInput } from '@/features/cookies/presentation';
|
||||
import { AutoSwitchView } from '@/features/proxy/ui/AutoSwitchView';
|
||||
import { ProxyProfilesView } from '@/features/proxy/ui/ProxyProfilesView';
|
||||
import { RuleSourcesView } from '@/features/proxy/ui/RuleSourcesView';
|
||||
import { RecordingWorkspace } from '@/features/browser-recording/RecordingWorkspace';
|
||||
import { AuthorizationTestingWorkspace } from '@/features/authorization-testing/ui/AuthorizationTestingWorkspace';
|
||||
import { AGENT_RUNTIME_STORAGE_KEY, AUDIT_STORAGE_KEY, isStateStorageChange } from '@/protocol/storage';
|
||||
import type {
|
||||
ActiveTabInfo, AgentRuntime, AuditEvent, BridgePairingStatus, BridgeStatus, BrowserCookie, BrowserRequestAnalysisBundle, CookieInput, CookieTransferFormat, EnterprisePolicyStatus, ExtensionState, HumanHandoff,
|
||||
NetworkCaptureStatus, NetworkRequestExport, NetworkRequestRecord, PageContext, PageEvalResult,
|
||||
PageFrameSummary, PageNodeDetails, PageNodeSummary,
|
||||
UserAgentProfile, UserAgentProfileInput, YakPocGenerateResult,
|
||||
} from '@/types/models';
|
||||
import { errorMessage, request } from '@/platform/messaging/runtime';
|
||||
import { APPEARANCE_STORAGE_KEY, getAppearance, setThemePreference, type ThemePreference } from '@/platform/storage/appearance';
|
||||
import './App.css';
|
||||
|
||||
type Section = 'overview' | 'authorization' | 'proxies' | 'rules' | 'sources' | 'cookies' | 'user-agent' | 'network' | 'context' | 'engine' | 'activity';
|
||||
const FIREFOX_AMO_BUILD = import.meta.env.FIREFOX && import.meta.env.MODE === 'store';
|
||||
|
||||
const NAVIGATION: Array<{ label: string; icon?: ReactNode; items: Array<{ id: Section; label: string; icon: ReactNode }> }> = [
|
||||
{
|
||||
label: '工作区',
|
||||
items: [
|
||||
{ id: 'overview', label: '运行概览', icon: <CircleGauge size={17} /> },
|
||||
{ id: 'authorization', label: '授权测试', icon: <Fingerprint size={17} /> },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: '网络与流量',
|
||||
items: [
|
||||
{ id: 'proxies', label: '代理出口', icon: <Network size={17} /> },
|
||||
{ id: 'rules', label: '自动切换', icon: <Route size={17} /> },
|
||||
{ id: 'sources', label: '规则订阅', icon: <CloudDownload size={17} /> },
|
||||
{ id: 'network', label: '网络活动', icon: <Activity size={17} /> },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: '常用工具', icon: <Wrench size={13} />,
|
||||
items: [
|
||||
{ id: 'cookies', label: 'Cookie Editor', icon: <Cookie size={17} /> },
|
||||
{ id: 'user-agent', label: 'UA 快速切换', icon: <UserRoundCog size={17} /> },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: 'Agent 与系统',
|
||||
items: [
|
||||
{ id: 'context', label: '登录态工作区', icon: <KeyRound size={17} /> },
|
||||
{ id: 'engine', label: '引擎连接', icon: <Server size={17} /> },
|
||||
{ id: 'activity', label: '操作记录', icon: <History size={17} /> },
|
||||
],
|
||||
},
|
||||
];
|
||||
const SECTIONS = NAVIGATION.flatMap((group) => group.items);
|
||||
|
||||
const CONTEXT_SECTION_LABELS: Record<PageContext['diff']['changedSections'][number], string> = {
|
||||
capture_options: '采集范围',
|
||||
document: '文档',
|
||||
authentication: '认证',
|
||||
forms: '表单',
|
||||
interactive: '可操作元素',
|
||||
storage: 'Storage',
|
||||
cookies: 'Cookie',
|
||||
};
|
||||
|
||||
function Empty({ children }: { children: ReactNode }) {
|
||||
return <div className="empty-state"><Database size={22} /><span>{children}</span></div>;
|
||||
}
|
||||
|
||||
function App() {
|
||||
const initialHash = location.hash.slice(1) as Section;
|
||||
const [section, setSection] = useState<Section>(SECTIONS.some((item) => item.id === initialHash) ? initialHash : 'overview');
|
||||
const [state, setState] = useState<ExtensionState>();
|
||||
const [tab, setTab] = useState<ActiveTabInfo>();
|
||||
const [tabs, setTabs] = useState<ActiveTabInfo[]>([]);
|
||||
const [bridge, setBridge] = useState<BridgeStatus>({ state: 'disconnected', message: '未连接引擎' });
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [notice, setNotice] = useState<{ kind: 'ok' | 'error'; text: string }>();
|
||||
const [theme, setTheme] = useState<ThemePreference>('system');
|
||||
|
||||
const load = useCallback(async () => {
|
||||
const requestedTabId = Number(new URLSearchParams(location.search).get('tabId'));
|
||||
const [nextState, nextTab, nextTabs, nextBridge] = await Promise.all([
|
||||
request('state.get'),
|
||||
Number.isSafeInteger(requestedTabId) && requestedTabId > 0
|
||||
? request('tab.get', { tabId: requestedTabId }).catch(() => request('tab.active').catch(() => undefined))
|
||||
: request('tab.active').catch(() => undefined),
|
||||
request('tab.list'),
|
||||
request('bridge.status'),
|
||||
]);
|
||||
setState(nextState);
|
||||
setTab(nextTab);
|
||||
setTabs(nextTabs);
|
||||
setBridge(nextBridge);
|
||||
}, []);
|
||||
|
||||
const refreshTabs = useCallback(async () => {
|
||||
const nextTabs = await request('tab.list');
|
||||
setTabs(nextTabs);
|
||||
setTab((current) => current ? nextTabs.find((item) => item.id === current.id) : current);
|
||||
}, []);
|
||||
|
||||
useEffect(() => { void load(); }, [load]);
|
||||
useEffect(() => {
|
||||
let timer: ReturnType<typeof globalThis.setTimeout> | undefined;
|
||||
const scheduleRefresh = () => {
|
||||
if (timer) globalThis.clearTimeout(timer);
|
||||
timer = globalThis.setTimeout(() => void refreshTabs().catch(() => undefined), 80);
|
||||
};
|
||||
const onCreated = () => scheduleRefresh();
|
||||
const onUpdated = (_tabId: number, change: Browser.tabs.OnUpdatedInfo) => {
|
||||
if (change.url !== undefined || change.title !== undefined || change.status === 'complete') scheduleRefresh();
|
||||
};
|
||||
const onRemoved = () => scheduleRefresh();
|
||||
browser.tabs.onCreated.addListener(onCreated);
|
||||
browser.tabs.onUpdated.addListener(onUpdated);
|
||||
browser.tabs.onRemoved.addListener(onRemoved);
|
||||
return () => {
|
||||
if (timer) globalThis.clearTimeout(timer);
|
||||
browser.tabs.onCreated.removeListener(onCreated);
|
||||
browser.tabs.onUpdated.removeListener(onUpdated);
|
||||
browser.tabs.onRemoved.removeListener(onRemoved);
|
||||
};
|
||||
}, [refreshTabs]);
|
||||
useEffect(() => {
|
||||
const listener = (changes: Record<string, unknown>) => {
|
||||
if (isStateStorageChange(changes)) void request('state.get').then(setState).catch(() => undefined);
|
||||
};
|
||||
browser.storage.onChanged.addListener(listener);
|
||||
return () => browser.storage.onChanged.removeListener(listener);
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
const listener = (message: unknown) => {
|
||||
const input = message as { action?: string; payload?: BridgeStatus };
|
||||
if (input?.action === 'bridge.status.changed' && input.payload) setBridge(input.payload);
|
||||
};
|
||||
browser.runtime.onMessage.addListener(listener);
|
||||
return () => browser.runtime.onMessage.removeListener(listener);
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
void getAppearance().then((appearance) => setTheme(appearance.theme));
|
||||
const listener = (changes: Record<string, unknown>, area: string) => {
|
||||
if (area !== 'local' || !(APPEARANCE_STORAGE_KEY in changes)) return;
|
||||
const next = (changes[APPEARANCE_STORAGE_KEY] as { newValue?: { theme?: ThemePreference } })?.newValue;
|
||||
setTheme(next?.theme && ['system', 'light', 'dark'].includes(next.theme) ? next.theme : 'system');
|
||||
};
|
||||
browser.storage.onChanged.addListener(listener);
|
||||
return () => browser.storage.onChanged.removeListener(listener);
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
const onHash = () => {
|
||||
const value = location.hash.slice(1) as Section;
|
||||
if (SECTIONS.some((item) => item.id === value)) setSection(value);
|
||||
};
|
||||
window.addEventListener('hashchange', onHash);
|
||||
return () => window.removeEventListener('hashchange', onHash);
|
||||
}, []);
|
||||
|
||||
const navigate = (next: Section) => {
|
||||
setSection(next);
|
||||
history.replaceState(null, '', `#${next}`);
|
||||
};
|
||||
|
||||
const selectTab = async (tabId: number) => {
|
||||
const next = await request('tab.get', { tabId });
|
||||
setTab(next);
|
||||
const url = new URL(location.href);
|
||||
url.searchParams.set('tabId', String(tabId));
|
||||
history.replaceState(null, '', `${url.pathname}${url.search}${url.hash}`);
|
||||
};
|
||||
|
||||
const run = async (task: () => Promise<void>, success?: string) => {
|
||||
setBusy(true);
|
||||
setNotice(undefined);
|
||||
try {
|
||||
await task();
|
||||
if (success) setNotice({ kind: 'ok', text: success });
|
||||
} catch (error) {
|
||||
setNotice({ kind: 'error', text: errorMessage(error) });
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (!state) return <div className="workspace-loading"><RefreshCw className="spin" size={19} /> 正在初始化 Yakit Browser Agent</div>;
|
||||
const handoff = waitingHandoff(state.handoff);
|
||||
|
||||
return (
|
||||
<div className="app-shell">
|
||||
<aside className="sidebar">
|
||||
<div className="sidebar-brand"><ProductBrand /></div>
|
||||
<nav>{NAVIGATION.map((group) => <div className="sidebar-group" key={group.label}><span className="sidebar-group__label">{group.icon}{group.label}</span>{group.items.map((item) => <button key={item.id} className={section === item.id ? 'active' : ''} onClick={() => navigate(item.id)}>{item.icon}<span>{item.label}</span><ChevronRight size={14} /></button>)}</div>)}</nav>
|
||||
<div className="sidebar-theme">
|
||||
<span>外观</span>
|
||||
<select aria-label="界面主题" value={theme} onChange={(event) => { const next = event.target.value as ThemePreference; setTheme(next); void setThemePreference(next); }}>
|
||||
<option value="system">跟随系统</option>
|
||||
<option value="light">浅色</option>
|
||||
<option value="dark">深色</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="sidebar-status"><span className="sidebar-yakit-mark"><YakitMark /><i className={`connection-dot ${bridge.state}`} /></span><div><strong>{bridge.state === 'connected' ? '引擎在线' : '引擎离线'}</strong><span>{state.bridge.transport === 'native' ? state.bridge.nativeHost : state.bridge.endpoint}</span></div></div>
|
||||
</aside>
|
||||
|
||||
<main className="workspace">
|
||||
<header className="topbar">
|
||||
{section === 'authorization' ? <div className="topbar-workspace-context">
|
||||
<Fingerprint size={16} />
|
||||
<div><strong>授权测试</strong><small>A/B 页面在工作区内选择</small></div>
|
||||
</div> : <div className="topbar-tab">
|
||||
<span className="topbar-tab__favicon">{tab?.favIconUrl ? <img src={tab.favIconUrl} alt="" /> : <Radio size={13} />}</span>
|
||||
<select className="target-tab-select" aria-label="目标标签页" value={tab?.id || ''} onChange={(event) => void selectTab(Number(event.target.value))}><option value="" disabled>选择目标标签页</option>{tabs.map((item) => <option value={item.id} key={item.id}>{item.title}</option>)}</select>
|
||||
</div>}
|
||||
<div className="topbar-actions"><span className={`permission-state ${bridge.state === 'connected' ? 'enabled' : ''}`}><ShieldCheck size={14} />{bridge.state === 'connected' ? '实例已连接' : '实例离线'}</span><Button size="icon" variant="ghost" title="刷新状态" onClick={() => void load()}><RefreshCw size={17} /></Button></div>
|
||||
</header>
|
||||
|
||||
{handoff && <HandoffBanner handoff={handoff} setState={setState} run={run} busy={busy} />}
|
||||
|
||||
<div className="content-area">
|
||||
{section === 'overview' && <Overview state={state} bridge={bridge} tab={tab} navigate={navigate} run={run} busy={busy} />}
|
||||
{section === 'authorization' && <AuthorizationTestingWorkspace state={state} setState={setState} tabs={tabs} activeTab={tab} bridge={bridge} refreshTabs={refreshTabs} run={run} busy={busy} />}
|
||||
{section === 'proxies' && <ProxyProfilesView state={state} setState={setState} run={run} busy={busy} tab={tab} />}
|
||||
{section === 'rules' && <AutoSwitchView state={state} setState={setState} tab={tab} run={run} busy={busy} />}
|
||||
{section === 'sources' && <RuleSourcesView state={state} setState={setState} tab={tab} run={run} busy={busy} />}
|
||||
{section === 'cookies' && <CookieEditor key={tab?.id || 0} tab={tab} run={run} busy={busy} />}
|
||||
{section === 'user-agent' && <UserAgents state={state} setState={setState} tab={tab} run={run} busy={busy} />}
|
||||
{section === 'network' && <NetworkActivity key={tab?.id || 0} tab={tab} bridge={bridge} run={run} busy={busy} />}
|
||||
{section === 'context' && <ContextTool key={tab?.id || 0} tab={tab} run={run} busy={busy} />}
|
||||
{section === 'engine' && <EngineSettings state={state} setState={setState} bridge={bridge} setBridge={setBridge} tabs={tabs} run={run} busy={busy} />}
|
||||
{section === 'activity' && <ActivityLog run={run} busy={busy} />}
|
||||
</div>
|
||||
{notice && <div className={`toast ${notice.kind}`}>{notice.kind === 'ok' ? <Check size={15} /> : <X size={15} />}{notice.text}</div>}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function HandoffBanner({ handoff, setState, run, busy }: { handoff: HumanHandoff; setState: (state: ExtensionState) => void; run: (task: () => Promise<void>, success?: string) => Promise<void>; busy: boolean }) {
|
||||
const resolve = (outcome: 'completed' | 'cancelled') => run(
|
||||
async () => setState(await request('handoff.resolve', { id: handoff.id, outcome })),
|
||||
outcome === 'completed' ? '已通知 Agent 继续执行' : '人工接管已取消',
|
||||
);
|
||||
return <section className="handoff-banner" aria-live="assertive">
|
||||
<AlertTriangle size={20} />
|
||||
<div className="handoff-banner__copy">
|
||||
<span>{HANDOFF_REASON_LABELS[handoff.reason]}</span>
|
||||
<strong>{handoff.message}</strong>
|
||||
<small title={handoff.target.grantedUrl}>{handoff.target.title} · {handoff.target.origin}</small>
|
||||
</div>
|
||||
<div className="handoff-banner__actions">
|
||||
<Button variant="primary" disabled={busy} onClick={() => void resolve('completed')}><Check size={15} />操作已完成</Button>
|
||||
<Button variant="ghost" disabled={busy} onClick={() => void resolve('cancelled')}><X size={15} />取消任务</Button>
|
||||
</div>
|
||||
</section>;
|
||||
}
|
||||
|
||||
function ActivityLog({ run, busy }: { run: (task: () => Promise<void>, success?: string) => Promise<void>; busy: boolean }) {
|
||||
const [events, setEvents] = useState<AuditEvent[]>([]);
|
||||
const [runtime, setRuntime] = useState<AgentRuntime>({ state: 'idle', updatedAt: Date.now(), actions: [] });
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadError, setLoadError] = useState('');
|
||||
const loadEvents = useCallback(async () => {
|
||||
try {
|
||||
setLoadError('');
|
||||
setEvents(await request('audit.list', { limit: 200 }));
|
||||
} catch (error) {
|
||||
setLoadError(errorMessage(error));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
const loadRuntime = useCallback(() => request('agent.runtime.get').then(setRuntime), []);
|
||||
useEffect(() => {
|
||||
void Promise.all([loadEvents(), loadRuntime()]);
|
||||
const listener = (changes: Record<string, unknown>) => {
|
||||
if (AUDIT_STORAGE_KEY in changes) void loadEvents();
|
||||
if (AGENT_RUNTIME_STORAGE_KEY in changes) void loadRuntime();
|
||||
};
|
||||
browser.storage.onChanged.addListener(listener);
|
||||
return () => browser.storage.onChanged.removeListener(listener);
|
||||
}, [loadEvents, loadRuntime]);
|
||||
|
||||
const runtimeLabel = {
|
||||
idle: '无活动任务', running: 'Agent 运行中', paused: '已暂停', waiting_for_human: '等待用户',
|
||||
revoked: '授权已撤销', expired: '授权已过期',
|
||||
}[runtime.state];
|
||||
const downloadDiagnostics = () => run(async () => {
|
||||
const bundle = await request('diagnostics.export');
|
||||
const url = URL.createObjectURL(new Blob([JSON.stringify(bundle, null, 2)], { type: 'application/json' }));
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = `yakit-browser-agent-diagnostics-${new Date().toISOString().replaceAll(':', '-')}.json`;
|
||||
link.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}, '脱敏诊断包已导出');
|
||||
|
||||
return <div className="section-view activity-view">
|
||||
<div className="page-heading"><div><h1>Agent 操作时间线</h1><p>实时动作保存在浏览器 session;长期审计只保存脱敏摘要,不记录参数、页面内容、Cookie 或执行结果。</p></div><div className="activity-heading-actions"><span className={`agent-runtime-state ${runtime.state}`}><Activity size={15} />{runtimeLabel}</span><Button variant="ghost" disabled={busy} onClick={() => void downloadDiagnostics()}><Download size={15} />导出诊断</Button></div></div>
|
||||
<section className="agent-runtime-band">
|
||||
<div className="agent-runtime-summary"><div><span>浏览器实例</span><strong>{runtime.taskId ? '已接入 Agent' : '等待调用'}</strong><small>{runtime.grantId ? '配对级访问' : '尚无能力调用'}</small></div><div><span>最近更新</span><strong>{new Date(runtime.updatedAt).toLocaleTimeString()}</strong><small>{runtime.actions.length} 条 session 动作</small></div><div className="agent-runtime-controls">{runtime.state === 'running' || runtime.state === 'waiting_for_human' ? <Button disabled={busy} onClick={() => void run(async () => setRuntime(await request('agent.pause')), 'Agent 已暂停')}><Square size={15} />暂停</Button> : runtime.state === 'paused' ? <Button variant="primary" disabled={busy} onClick={() => void run(async () => setRuntime(await request('agent.resume')), 'Agent 已恢复')}><Play size={15} />恢复</Button> : null}<Button variant="ghost" disabled={busy || runtime.actions.length === 0} onClick={() => void run(async () => setRuntime(await request('agent.actions.clear')), 'Session 时间线已清空')}><Trash2 size={15} />清空</Button></div></div>
|
||||
{runtime.actions.length === 0 ? <div className="agent-actions-empty">当前 session 尚无 Agent 能力调用。</div> : <div className="agent-action-list" role="list">{[...runtime.actions].reverse().slice(0, 50).map((action) => <div key={action.id} className="agent-action-row" role="listitem"><span className={`action-state ${action.state}`} /> <time>{new Date(action.startedAt).toLocaleTimeString()}</time><code title={action.method}>{action.method}</code><span>{action.targetTabId ? `Tab ${action.targetTabId}` : '扩展本机'}</span><strong className={action.state}>{action.state}</strong><span>{action.durationMs === undefined ? '进行中' : `${action.durationMs} ms`}</span></div>)}</div>}
|
||||
</section>
|
||||
<div className="activity-subheading"><div><h2>持久化脱敏审计</h2><p>最近 500 条授权、Bridge、接管与能力结果。</p></div><Button variant="ghost" disabled={busy || events.length === 0} onClick={() => void run(async () => { await request('audit.clear'); setEvents([]); }, '操作记录已清空')}><Trash2 size={15} />清空审计</Button></div>
|
||||
{loading ? <div className="activity-loading"><RefreshCw className="spin" size={16} />正在读取记录</div> : loadError ? <div className="activity-loading error"><AlertTriangle size={16} />{loadError}<Button size="sm" variant="ghost" onClick={() => void loadEvents()}>重试</Button></div> : events.length === 0 ? <Empty>还没有操作记录。</Empty> : <div className="activity-table" role="table" aria-label="扩展操作记录">
|
||||
<div className="activity-table__head" role="row"><span>时间</span><span>类型</span><span>动作</span><span>目标 / 摘要</span><span>结果</span><span>耗时</span></div>
|
||||
{events.map((event) => <div className="activity-table__row" role="row" key={event.id}>
|
||||
<time dateTime={new Date(event.timestamp).toISOString()}>{new Date(event.timestamp).toLocaleString()}</time>
|
||||
<span>{AUDIT_CATEGORY_LABELS[event.category]}</span>
|
||||
<code title={event.action}>{event.action}</code>
|
||||
<span title={event.summary}>{event.summary || (event.targetTabId ? `标签页 ${event.targetTabId}` : event.taskId ? `任务 ${event.taskId}` : '扩展本机')}</span>
|
||||
<span className={`audit-outcome ${event.outcome}`} title={event.errorCode}>{AUDIT_OUTCOME_LABELS[event.outcome]}</span>
|
||||
<span>{event.durationMs === undefined ? '—' : `${event.durationMs} ms`}</span>
|
||||
</div>)}
|
||||
</div>}
|
||||
</div>;
|
||||
}
|
||||
|
||||
function Overview({ state, bridge, tab, navigate, run, busy }: { state: ExtensionState; bridge: BridgeStatus; tab?: ActiveTabInfo; navigate: (value: Section) => void; run: (task: () => Promise<void>, success?: string) => Promise<void>; busy: boolean }) {
|
||||
const activeProxy = state.proxyProfiles.find((profile) => profile.id === state.activeProxyId)?.name || (state.activeProxyId === 'auto' ? '自动切换' : '未知');
|
||||
const [runtime, setRuntime] = useState<AgentRuntime>({ state: 'idle', updatedAt: Date.now(), actions: [] });
|
||||
const [network, setNetwork] = useState<NetworkCaptureStatus>();
|
||||
const [loginContext, setLoginContext] = useState<PageContext>();
|
||||
useEffect(() => {
|
||||
void request('agent.runtime.get').then(setRuntime).catch(() => undefined);
|
||||
if (tab) void request('network.capture.status', { tabId: tab.id }).then(setNetwork).catch(() => setNetwork(undefined));
|
||||
const listener = (changes: Record<string, unknown>) => {
|
||||
if (AGENT_RUNTIME_STORAGE_KEY in changes) void request('agent.runtime.get').then(setRuntime).catch(() => undefined);
|
||||
};
|
||||
browser.storage.onChanged.addListener(listener);
|
||||
return () => browser.storage.onChanged.removeListener(listener);
|
||||
}, [tab?.id]);
|
||||
const site = tab?.url ? new URL(tab.url) : undefined;
|
||||
const latestAction = [...runtime.actions].reverse()[0];
|
||||
const captureLoginEnvironment = () => run(async () => {
|
||||
if (!tab) throw new Error('请先选择 HTTP(S) 标签页');
|
||||
setLoginContext(await request('context.capture', {
|
||||
tabId: tab.id, includeDom: true, includeStorage: true, includeCookies: true,
|
||||
}));
|
||||
}, '登录环境已采集');
|
||||
const startCapture = () => run(async () => {
|
||||
if (!tab) throw new Error('请先选择 HTTP(S) 标签页');
|
||||
setNetwork(await request('network.capture.start', { tabId: tab.id, captureHeaders: false, captureBody: false }));
|
||||
navigate('network');
|
||||
}, '网络元数据捕获已启动');
|
||||
return <div className="section-view overview-view">
|
||||
<div className="page-heading"><div><h1>运行概览</h1><p>{tab?.title || '选择一个 HTTP(S) 标签页,建立浏览器现场。'}</p></div><span className={`large-status ${bridge.state}`}><Radio size={16} />{bridge.state === 'connected' ? `Yak ${bridge.engineVersion || '引擎'} 在线` : 'Yak 引擎离线'}</span></div>
|
||||
<div className="task-command-bar">
|
||||
<div className="task-site-identity"><KeyRound size={18} /><span><strong>{loginContext?.authentication.status === 'authenticated' ? '检测到登录环境' : loginContext?.authentication.status === 'unauthenticated' ? '未检测到登录态' : '登录环境待采集'}</strong><small>{site ? `${site.protocol.replace(':', '').toUpperCase()} · ${site.origin}` : '当前页面不可访问'}</small></span></div>
|
||||
<div className="task-quick-actions"><Button disabled={busy || !tab} onClick={() => void captureLoginEnvironment()}><Braces size={15} />采集登录环境</Button><Button disabled={busy || !tab || network?.active} onClick={() => void startCapture()}><Activity size={15} />{network?.active ? '正在捕获' : '抓取请求'}</Button><Button variant="primary" onClick={() => navigate('engine')}><Bot size={15} />管理 Agent 连接</Button></div>
|
||||
</div>
|
||||
<div className="task-status-grid">
|
||||
<section><span>浏览器现场</span><strong>{loginContext ? `${loginContext.document?.forms.length || 0} 表单 / ${loginContext.document?.interactive.length || 0} 节点` : '尚未采集'}</strong><small>{loginContext?.authentication.evidence[0] || 'Cookie、Storage 与认证信号仅在用户点击后读取'}</small><button onClick={() => navigate('context')}>打开上下文<ChevronRight size={15} /></button></section>
|
||||
<section><span>代理与流量</span><strong>{activeProxy}</strong><small>{network?.active ? `${network.count} 条请求,${network.droppedCount} 条丢弃` : `${state.proxyRules.filter((rule) => rule.enabled).length} 条手动规则 · ${state.proxyRuleSources.filter((source) => source.enabled).length} 个订阅源`}</small><button onClick={() => navigate(network?.active ? 'network' : 'rules')}>查看流量策略<ChevronRight size={15} /></button></section>
|
||||
<section><span>Agent 连接</span><strong>{bridge.state === 'connected' ? `实例在线 · ${runtime.state}` : '实例离线'}</strong><small>{bridge.state === 'connected' ? '当前浏览器内的 HTTP(S) 页面可直接被引用' : '配对并连接 Yakit 后即可使用,无需逐页授权'}</small><button onClick={() => navigate('activity')}>查看动作时间线<ChevronRight size={15} /></button></section>
|
||||
<section className={state.handoff?.state === 'waiting_for_user' ? 'needs-attention' : ''}><span>需要用户处理</span><strong>{state.handoff?.state === 'waiting_for_user' ? HANDOFF_REASON_LABELS[state.handoff.reason] : runtime.state === 'paused' ? 'Agent 已暂停' : '没有待办步骤'}</strong><small>{state.handoff?.state === 'waiting_for_user' ? state.handoff.message : latestAction ? `最近 ${latestAction.method} · ${latestAction.state}` : '二维码、MFA 与 CAPTCHA 会在这里出现'}</small><button onClick={() => navigate('activity')}>会话控制<ChevronRight size={15} /></button></section>
|
||||
</div>
|
||||
<div className="task-workflow-list">
|
||||
<button onClick={() => navigate('cookies')}><Cookie size={18} /><span><strong>检查 Cookie 与登录线索</strong><small>直接检查原始值,导出默认脱敏。</small></span><ChevronRight size={16} /></button>
|
||||
<button onClick={() => navigate('network')}><Send size={18} /><span><strong>请求转到 Yakit</strong><small>选择捕获记录后打开 Web Fuzzer、生成 Yak PoC 或准备 AI 分析。</small></span><ChevronRight size={16} /></button>
|
||||
<button onClick={() => navigate('context')}><Braces size={18} /><span><strong>观测签名与加解密</strong><small>短时观测 WebCrypto、CryptoJS、JSEncrypt、WebSocket 和请求调用栈。</small></span><ChevronRight size={16} /></button>
|
||||
</div>
|
||||
</div>;
|
||||
}
|
||||
|
||||
|
||||
function CookieEditor({ tab, run, busy }: { tab?: ActiveTabInfo; run: (task: () => Promise<void>, success?: string) => Promise<void>; busy: boolean }) {
|
||||
const [url, setUrl] = useState(tab?.url || '');
|
||||
const [cookies, setCookies] = useState<BrowserCookie[]>([]);
|
||||
const [query, setQuery] = useState('');
|
||||
const [filter, setFilter] = useState<'all' | 'session' | 'persistent' | 'httpOnly' | 'partitioned'>('all');
|
||||
const [sort, setSort] = useState<'name' | 'domain' | 'expires' | 'size'>('name');
|
||||
const [group, setGroup] = useState<'none' | 'domain' | 'path'>('domain');
|
||||
const [selected, setSelected] = useState<Set<string>>(new Set());
|
||||
const [transferFormat, setTransferFormat] = useState<CookieTransferFormat>('json');
|
||||
const [includeExportValues, setIncludeExportValues] = useState(false);
|
||||
const [importText, setImportText] = useState('');
|
||||
const [transferStatus, setTransferStatus] = useState('');
|
||||
const [draft, setDraft] = useState<Omit<CookieInput, 'url'>>({
|
||||
name: '', value: '', path: '/', secure: url.startsWith('https:'), httpOnly: false, sameSite: 'unspecified',
|
||||
});
|
||||
const keyOf = cookieKey;
|
||||
const reload = () => run(async () => {
|
||||
if (!tab?.id) throw new Error('请选择目标标签页');
|
||||
setCookies(await request('cookie.list', { url, tabId: tab.id }));
|
||||
setSelected(new Set());
|
||||
});
|
||||
const editCookie = (cookie: BrowserCookie) => {
|
||||
setDraft({
|
||||
name: cookie.name, value: cookie.value, domain: cookie.hostOnly ? undefined : cookie.domain,
|
||||
path: cookie.path, secure: cookie.secure, httpOnly: cookie.httpOnly,
|
||||
sameSite: cookie.sameSite as CookieInput['sameSite'], expirationDate: cookie.expirationDate,
|
||||
storeId: cookie.storeId, firstPartyDomain: cookie.firstPartyDomain, partitionKey: cookie.partitionKey,
|
||||
});
|
||||
};
|
||||
const visibleCookies = cookies.filter((cookie) => {
|
||||
const needle = query.trim().toLowerCase();
|
||||
const queryMatch = !needle || [cookie.name, cookie.domain, cookie.path].some((value) => value.toLowerCase().includes(needle));
|
||||
const filterMatch = filter === 'all' || (filter === 'session' && cookie.session) || (filter === 'persistent' && !cookie.session)
|
||||
|| (filter === 'httpOnly' && cookie.httpOnly) || (filter === 'partitioned' && Boolean(cookie.partitionKey));
|
||||
return queryMatch && filterMatch;
|
||||
}).sort((left, right) => {
|
||||
if (sort === 'domain') return `${left.domain}${left.path}${left.name}`.localeCompare(`${right.domain}${right.path}${right.name}`);
|
||||
if (sort === 'expires') return (left.expirationDate || Number.MAX_SAFE_INTEGER) - (right.expirationDate || Number.MAX_SAFE_INTEGER);
|
||||
if (sort === 'size') return right.value.length - left.value.length;
|
||||
return left.name.localeCompare(right.name);
|
||||
});
|
||||
const groupedCookies = new Map<string, BrowserCookie[]>();
|
||||
for (const cookie of visibleCookies) {
|
||||
const key = group === 'domain' ? cookie.domain : group === 'path' ? cookie.path : '全部 Cookie';
|
||||
groupedCookies.set(key, [...(groupedCookies.get(key) || []), cookie]);
|
||||
}
|
||||
const removeInputs = (items: BrowserCookie[]) => items.map(cookieRemovalInput);
|
||||
const downloadExport = async () => {
|
||||
if (!tab?.id) throw new Error('请选择目标标签页');
|
||||
const text = await request('cookie.export', {
|
||||
url,
|
||||
tabId: tab.id,
|
||||
format: transferFormat,
|
||||
includeValues: includeExportValues,
|
||||
});
|
||||
const blobUrl = URL.createObjectURL(new Blob([text], { type: 'text/plain;charset=utf-8' }));
|
||||
const anchor = document.createElement('a');
|
||||
anchor.href = blobUrl;
|
||||
anchor.download = `cookies-${new URL(url).hostname}.${transferFormat === 'json' ? 'json' : 'txt'}`;
|
||||
anchor.click();
|
||||
URL.revokeObjectURL(blobUrl);
|
||||
};
|
||||
useEffect(() => { if (url.startsWith('http')) void reload(); }, []);
|
||||
return <div className="section-view">
|
||||
<div className="page-heading"><div><h1>Cookie Editor</h1><p>HttpOnly、Cookie Store、CHIPS 分区与多格式交换。</p></div><button disabled={busy || !url} onClick={() => void reload()}><RefreshCw size={16} />刷新</button></div>
|
||||
<div className="url-bar"><input value={url} onChange={(event) => setUrl(event.target.value)} /><span>{cookies.length} cookies</span></div>
|
||||
<div className="cookie-toolbar"><div className="network-search"><Search size={14} /><input aria-label="搜索 Cookie" placeholder="搜索名称、Domain 或 Path" value={query} onChange={(event) => setQuery(event.target.value)} /></div><select aria-label="Cookie 筛选" value={filter} onChange={(event) => setFilter(event.target.value as typeof filter)}><option value="all">全部</option><option value="session">Session</option><option value="persistent">持久</option><option value="httpOnly">HttpOnly</option><option value="partitioned">Partitioned</option></select><select aria-label="Cookie 排序" value={sort} onChange={(event) => setSort(event.target.value as typeof sort)}><option value="name">按名称</option><option value="domain">按 Domain</option><option value="expires">按过期时间</option><option value="size">按值大小</option></select><select aria-label="Cookie 分组" value={group} onChange={(event) => setGroup(event.target.value as typeof group)}><option value="domain">Domain 分组</option><option value="path">Path 分组</option><option value="none">不分组</option></select><Button variant="danger" disabled={busy || selected.size === 0} onClick={() => void run(async () => { if (!tab?.id) throw new Error('请选择目标标签页'); const result = await request('cookie.removeMany', { cookies: removeInputs(cookies.filter((cookie) => selected.has(keyOf(cookie)))) }); setTransferStatus(`删除 ${result.removed},失败 ${result.failed}`); setCookies(await request('cookie.list', { url, tabId: tab.id })); setSelected(new Set()); }, '已执行批量删除')}><Trash2 size={14} />删除 {selected.size || ''}</Button></div>
|
||||
<div className="cookie-layout"><div className="cookie-table"><div className="table-head cookie-columns"><input aria-label="选择全部可见 Cookie" type="checkbox" checked={visibleCookies.length > 0 && visibleCookies.every((cookie) => selected.has(keyOf(cookie)))} onChange={(event) => setSelected(event.target.checked ? new Set(visibleCookies.map(keyOf)) : new Set())} /><span>名称</span><span>值</span><span>Domain / Path</span><span>属性</span><span /></div>{visibleCookies.length === 0 ? <Empty>没有符合条件的 Cookie。</Empty> : [...groupedCookies].map(([groupName, items]) => <div className="cookie-group" key={groupName}><div className="cookie-group__heading"><strong>{groupName}</strong><span>{items.length}</span></div>{items.map((cookie) => {
|
||||
const cookieKey = keyOf(cookie);
|
||||
return <div className="table-row cookie-columns" key={cookieKey}><input aria-label={`选择 ${cookie.name}`} type="checkbox" checked={selected.has(cookieKey)} onChange={(event) => setSelected((current) => { const next = new Set(current); if (event.target.checked) next.add(cookieKey); else next.delete(cookieKey); return next; })} /><button className="cookie-name-button" title="编辑 Cookie" onClick={() => editCookie(cookie)}><strong>{cookie.name}</strong></button><code className="cookie-value" title={cookie.value}>{cookie.value}</code><span><small>{cookie.domain}</small><small>{cookie.path}</small></span><span className="tag-list">{cookie.httpOnly && <i>HttpOnly</i>}{cookie.secure && <i>Secure</i>}{cookie.partitionKey && <i>Partitioned</i>}{cookie.sameSite && <i>{cookie.sameSite}</i>}{cookie.priority && <i>{cookie.priority}</i>}{cookie.sameParty && <i>SameParty</i>}</span><button className="icon-button danger" title="删除 Cookie" onClick={() => void run(async () => { if (!tab?.id) throw new Error('请选择目标标签页'); await request('cookie.remove', removeInputs([cookie])[0]); setCookies(await request('cookie.list', { url, tabId: tab.id })); }, 'Cookie 已删除')}><Trash2 size={15} /></button></div>;
|
||||
})}</div>)}</div>
|
||||
<div className="rule-editor cookie-editor-pane"><h2>写入 Cookie</h2><Field label="名称"><input value={draft.name} onChange={(event) => setDraft({ ...draft, name: event.target.value })} /></Field><Field label="值"><textarea rows={4} value={draft.value} onChange={(event) => setDraft({ ...draft, value: event.target.value })} /></Field><Field label="Domain" hint="留空创建 HostOnly Cookie"><input value={draft.domain || ''} onChange={(event) => setDraft({ ...draft, domain: event.target.value || undefined })} /></Field><Field label="Path"><input value={draft.path} onChange={(event) => setDraft({ ...draft, path: event.target.value })} /></Field><Field label="过期时间"><input type="datetime-local" value={draft.expirationDate ? new Date(draft.expirationDate * 1_000).toISOString().slice(0, 16) : ''} onChange={(event) => setDraft({ ...draft, expirationDate: event.target.value ? new Date(event.target.value).getTime() / 1_000 : undefined })} /></Field><Field label="SameSite"><select value={draft.sameSite} onChange={(event) => setDraft({ ...draft, sameSite: event.target.value as CookieInput['sameSite'] })}><option value="unspecified">Unspecified</option><option value="lax">Lax</option><option value="strict">Strict</option><option value="no_restriction">None</option></select></Field><Field label="Partition top-level site"><input placeholder="https://top.example" value={draft.partitionKey?.topLevelSite || ''} onChange={(event) => setDraft({ ...draft, partitionKey: event.target.value ? { ...draft.partitionKey, topLevelSite: event.target.value } : undefined })} /></Field><label className="check-row"><input type="checkbox" checked={draft.secure} onChange={(event) => setDraft({ ...draft, secure: event.target.checked })} />Secure</label><label className="check-row"><input type="checkbox" checked={draft.httpOnly} onChange={(event) => setDraft({ ...draft, httpOnly: event.target.checked })} />HttpOnly</label><label className="check-row"><input type="checkbox" disabled={!draft.partitionKey} checked={draft.partitionKey?.hasCrossSiteAncestor || false} onChange={(event) => setDraft({ ...draft, partitionKey: { ...draft.partitionKey, hasCrossSiteAncestor: event.target.checked } })} />Cross-site ancestor</label><button className="primary-button" disabled={busy || !url || !draft.name || !tab?.id} onClick={() => void run(async () => { if (!tab?.id) throw new Error('请选择目标标签页'); await request('cookie.set', { url, tabId: tab.id, ...draft }); setCookies(await request('cookie.list', { url, tabId: tab.id })); }, 'Cookie 已写入')}><Save size={16} />保存 Cookie</button><div className="cookie-transfer"><h2>导入 / 导出</h2><div><select value={transferFormat} onChange={(event) => setTransferFormat(event.target.value as CookieTransferFormat)}><option value="json">JSON</option><option value="netscape">Netscape</option><option value="set-cookie">Set-Cookie</option></select><label className="check-row"><input type="checkbox" checked={includeExportValues} onChange={(event) => setIncludeExportValues(event.target.checked)} />导出原始值</label></div><textarea rows={6} value={importText} onChange={(event) => setImportText(event.target.value)} placeholder="粘贴 Cookie 数据" /><div className="editor-actions"><Button variant="primary" disabled={busy || !importText.trim() || !tab?.id} onClick={() => void run(async () => { if (!tab?.id) throw new Error('请选择目标标签页'); const result = await request('cookie.import', { url, tabId: tab.id, format: transferFormat, text: importText }); setTransferStatus(`导入 ${result.imported},失败 ${result.failed}${result.warnings.length ? `;${result.warnings.join(';')}` : ''}`); setCookies(await request('cookie.list', { url, tabId: tab.id })); }, 'Cookie 导入完成')}><Upload size={14} />导入</Button><Button variant="ghost" disabled={busy || cookies.length === 0} onClick={() => void run(downloadExport, includeExportValues ? 'Cookie 已导出(包含值)' : 'Cookie 已脱敏导出')}><Download size={14} />导出</Button></div>{transferStatus && <p className="transfer-status">{transferStatus}</p>}</div></div>
|
||||
</div>
|
||||
</div>;
|
||||
}
|
||||
|
||||
function UserAgents({ state, setState, tab, run, busy }: { state: ExtensionState; setState: (state: ExtensionState) => void; tab?: ActiveTabInfo; run: (task: () => Promise<void>, success?: string) => Promise<void>; busy: boolean }) {
|
||||
const [profiles, setProfiles] = useState<UserAgentProfile[]>([]);
|
||||
const [selectedProfileId, setSelectedProfileId] = useState('chrome-windows');
|
||||
const [draft, setDraft] = useState<UserAgentProfileInput>({ name: '', userAgent: '' });
|
||||
const url = tab?.url?.startsWith('http') ? tab.url : '';
|
||||
let hostname = '';
|
||||
try { hostname = url ? new URL(url).hostname : ''; } catch { hostname = ''; }
|
||||
const currentAssignment = state.userAgentAssignments.find((assignment) => assignment.hostname === hostname);
|
||||
const profileMap = new Map(profiles.map((profile) => [profile.id, profile]));
|
||||
const selectedProfile = profileMap.get(selectedProfileId);
|
||||
const effectiveProfile = currentAssignment ? profileMap.get(currentAssignment.profileId) : undefined;
|
||||
|
||||
const loadProfiles = useCallback(async () => {
|
||||
const next = await request('ua.catalog');
|
||||
setProfiles(next);
|
||||
const current = state.userAgentAssignments.find((assignment) => assignment.hostname === hostname);
|
||||
if (current && next.some((profile) => profile.id === current.profileId)) setSelectedProfileId(current.profileId);
|
||||
}, [hostname, state.userAgentAssignments]);
|
||||
useEffect(() => { void loadProfiles(); }, [loadProfiles, state.customUserAgentProfiles]);
|
||||
|
||||
const applyAndReload = () => run(async () => {
|
||||
if (!tab || !url || !selectedProfile) throw new Error('请选择可访问的目标页面和 User-Agent 预设');
|
||||
setState(await request('ua.site.apply', { url, profileId: selectedProfile.id }));
|
||||
await browser.tabs.reload(tab.id);
|
||||
}, `${selectedProfile?.name || 'User-Agent'} 已应用并刷新页面`);
|
||||
const resetAndReload = () => run(async () => {
|
||||
if (!tab || !url) throw new Error('请选择可访问的目标页面');
|
||||
setState(await request('ua.site.reset', { url }));
|
||||
await browser.tabs.reload(tab.id);
|
||||
}, '已恢复浏览器默认 User-Agent 并刷新页面');
|
||||
const saveProfile = () => run(async () => {
|
||||
const saved = await request('ua.profile.save', draft);
|
||||
const next = await request('ua.catalog');
|
||||
setProfiles(next);
|
||||
setSelectedProfileId(saved.id);
|
||||
setDraft({ name: '', userAgent: '' });
|
||||
}, '自定义 User-Agent 预设已保存');
|
||||
|
||||
return <div className="section-view ua-view">
|
||||
<div className="page-heading"><div><span className="page-eyebrow">常用工具</span><h1>User-Agent 快速切换</h1><p>为单个 hostname 修改真实网络请求头;不伪装 Navigator、Client Hints、屏幕或 TLS 指纹。</p></div></div>
|
||||
<section className="ua-current-site">
|
||||
<div><span>当前目标</span><strong>{hostname || '当前标签页不可配置'}</strong><small>{effectiveProfile ? `正在使用 ${effectiveProfile.name}` : '使用浏览器默认 User-Agent'}</small></div>
|
||||
<select aria-label="当前站点 User-Agent" disabled={!hostname || busy} value={selectedProfileId} onChange={(event) => setSelectedProfileId(event.target.value)}>{profiles.map((profile) => <option key={profile.id} value={profile.id}>{profile.name}{profile.builtin ? '' : ' · 自定义'}</option>)}</select>
|
||||
<div className="editor-actions"><Button variant="ghost" disabled={!currentAssignment || busy} onClick={() => void resetAndReload()}>恢复默认</Button><Button variant="primary" disabled={!hostname || !selectedProfile || busy} onClick={() => void applyAndReload()}><RefreshCw size={14} />应用并刷新</Button></div>
|
||||
</section>
|
||||
<div className="ua-management">
|
||||
<section className="ua-assignments"><div className="context-section-heading"><div><h2>站点绑定</h2><span>每个 hostname 只保留一个生效预设</span></div></div>{state.userAgentAssignments.length === 0 ? <Empty>还没有站点 User-Agent 绑定。</Empty> : <div className="ua-assignment-list">{[...state.userAgentAssignments].sort((left, right) => left.hostname.localeCompare(right.hostname)).map((assignment) => { const profile = profileMap.get(assignment.profileId); return <div key={assignment.id}><span><strong>{assignment.hostname}</strong><small>{profile?.name || '预设已删除'}</small></span><code title={profile?.userAgent}>{profile?.userAgent || assignment.profileId}</code><Button size="icon" variant="ghost" title="恢复该站点默认 UA" aria-label={`移除 ${assignment.hostname} 的 UA 绑定`} onClick={() => void run(async () => setState(await request('ua.site.reset', { url: `https://${assignment.hostname}/` })), '站点 UA 绑定已移除')}><Trash2 size={14} /></Button></div>; })}</div>}
|
||||
</section>
|
||||
<aside className="ua-profile-editor"><div className="context-section-heading"><div><h2>{draft.id ? '编辑自定义预设' : '自定义预设'}</h2><span>保存后可在 Popup 和当前站点中复用</span></div></div><Field label="名称"><input value={draft.name} onChange={(event) => setDraft({ ...draft, name: event.target.value })} placeholder="例如 API Client" /></Field><Field label="User-Agent"><textarea rows={5} value={draft.userAgent} onChange={(event) => setDraft({ ...draft, userAgent: event.target.value })} placeholder="Custom-Agent/1.0" /></Field><div className="editor-actions">{draft.id && <Button variant="ghost" onClick={() => setDraft({ name: '', userAgent: '' })}>取消编辑</Button>}<Button variant="primary" disabled={busy || !draft.name.trim() || !draft.userAgent.trim()} onClick={() => void saveProfile()}><Save size={14} />保存预设</Button></div><div className="custom-ua-list">{profiles.filter((profile) => !profile.builtin).map((profile) => <div key={profile.id}><button onClick={() => setDraft({ id: profile.id, name: profile.name, userAgent: profile.userAgent })}><strong>{profile.name}</strong><small>{profile.userAgent}</small></button><Button size="icon" variant="ghost" title="删除自定义预设" aria-label={`删除 ${profile.name}`} onClick={() => void run(async () => { setState(await request('ua.profile.delete', { id: profile.id })); await loadProfiles(); }, '自定义 UA 预设已删除')}><Trash2 size={14} /></Button></div>)}</div></aside>
|
||||
</div>
|
||||
</div>;
|
||||
}
|
||||
|
||||
function networkLabel(record: NetworkRequestRecord): { host: string; path: string } {
|
||||
try {
|
||||
const parsed = new URL(record.url);
|
||||
return { host: parsed.host, path: `${parsed.pathname}${parsed.search}` };
|
||||
} catch {
|
||||
return { host: record.url, path: '' };
|
||||
}
|
||||
}
|
||||
|
||||
function NetworkActivity({
|
||||
tab,
|
||||
bridge,
|
||||
run,
|
||||
busy,
|
||||
}: {
|
||||
tab?: ActiveTabInfo;
|
||||
bridge: BridgeStatus;
|
||||
run: (task: () => Promise<void>, success?: string) => Promise<void>;
|
||||
busy: boolean;
|
||||
}) {
|
||||
const [status, setStatus] = useState<NetworkCaptureStatus>();
|
||||
const [records, setRecords] = useState<NetworkRequestRecord[]>([]);
|
||||
const [selectedId, setSelectedId] = useState('');
|
||||
const [exported, setExported] = useState<NetworkRequestExport>();
|
||||
const [previewError, setPreviewError] = useState('');
|
||||
const [generatedPoc, setGeneratedPoc] = useState<YakPocGenerateResult>();
|
||||
const [analysisBundle, setAnalysisBundle] = useState<BrowserRequestAnalysisBundle>();
|
||||
const [loadError, setLoadError] = useState('');
|
||||
const [captureHeaders, setCaptureHeaders] = useState(false);
|
||||
const [captureBody, setCaptureBody] = useState(false);
|
||||
const [query, setQuery] = useState('');
|
||||
const transformShared = bridge.state === 'connected';
|
||||
|
||||
const shareTransform = async () => {
|
||||
if (!tab) throw new Error('请先选择需要使用的页面');
|
||||
if (bridge.state !== 'connected') await request('bridge.connect');
|
||||
};
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (!tab) return;
|
||||
try {
|
||||
setLoadError('');
|
||||
const nextStatus = await request('network.capture.status', { tabId: tab.id });
|
||||
setStatus(nextStatus);
|
||||
if (nextStatus.options) {
|
||||
setCaptureHeaders(nextStatus.options.captureHeaders);
|
||||
setCaptureBody(nextStatus.options.captureBody);
|
||||
}
|
||||
const nextRecords = nextStatus.active
|
||||
? await request('network.capture.list', { ...nextStatus.target, limit: 200 })
|
||||
: [];
|
||||
setRecords(nextRecords);
|
||||
setSelectedId((current) => nextRecords.some((record) => record.id === current) ? current : nextRecords[0]?.id || '');
|
||||
} catch (error) {
|
||||
setLoadError(errorMessage(error));
|
||||
}
|
||||
}, [tab]);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
const listener = (message: unknown) => {
|
||||
const input = message as { action?: string; payload?: { tabId?: number } };
|
||||
if (input?.action === 'network.capture.changed' && input.payload?.tabId === tab?.id) void load();
|
||||
};
|
||||
browser.runtime.onMessage.addListener(listener);
|
||||
return () => browser.runtime.onMessage.removeListener(listener);
|
||||
}, [load, tab?.id]);
|
||||
|
||||
const selected = records.find((record) => record.id === selectedId);
|
||||
useEffect(() => {
|
||||
setExported(undefined);
|
||||
setPreviewError('');
|
||||
setGeneratedPoc(undefined);
|
||||
setAnalysisBundle(undefined);
|
||||
if (!selected || !status?.active || !selected.requestHeadersCaptured) return;
|
||||
void request('network.capture.export', { ...status.target, id: selected.id })
|
||||
.then(setExported)
|
||||
.catch((error) => setPreviewError(errorMessage(error)));
|
||||
}, [selected, status]);
|
||||
|
||||
const visibleRecords = records.filter((record) => {
|
||||
const needle = query.trim().toLowerCase();
|
||||
return !needle || record.url.toLowerCase().includes(needle) || record.method.toLowerCase().includes(needle)
|
||||
|| String(record.statusCode || '').includes(needle);
|
||||
});
|
||||
const canSendToYakit = bridge.state === 'connected' && Boolean(bridge.capabilities?.includes('yakit.web_fuzzer.open'));
|
||||
const canGeneratePoc = bridge.state === 'connected' && Boolean(bridge.capabilities?.includes('yakit.poc.generate'));
|
||||
const canPrepareAnalysis = bridge.state === 'connected' && Boolean(bridge.capabilities?.includes('yakit.browser_request.prepare_analysis'));
|
||||
const captureTarget = status?.active ? status.target : tab ? { tabId: tab.id } : undefined;
|
||||
const persistenceHint = status?.persistence === 'degraded'
|
||||
? `会话存储失败,当前记录仅保留在内存中${status.persistenceError ? `:${status.persistenceError}` : ''}`
|
||||
: status?.persistence === 'memory-only'
|
||||
? '当前浏览器不提供会话存储,记录仅保留在内存中'
|
||||
: status?.persistence === 'pending'
|
||||
? '最新记录正在写入浏览器会话存储'
|
||||
: status?.persistence === 'persisted' ? '记录已写入浏览器会话存储' : undefined;
|
||||
const persistenceSuffix = status?.persistence === 'degraded' || status?.persistence === 'memory-only' ? ' · 仅内存' : '';
|
||||
|
||||
const start = () => run(async () => {
|
||||
if (!tab) throw new Error('请选择目标标签页');
|
||||
const next = await request('network.capture.start', {
|
||||
tabId: tab.id, captureHeaders, captureBody, maxEntries: 100, maxBodyBytes: 32 * 1024,
|
||||
});
|
||||
setStatus(next);
|
||||
setRecords([]);
|
||||
setSelectedId('');
|
||||
}, captureHeaders || captureBody ? '网络捕获已开始,敏感字段仅保存在本次浏览器会话' : '网络元数据捕获已开始');
|
||||
|
||||
return <div className="section-view network-view">
|
||||
<div className="page-heading"><div><h1>网络活动</h1><p>HTTP 请求、表单导航、实时通信与前端加密调用。</p></div><div className="network-heading-actions">
|
||||
<span className={`capture-state ${status?.active ? 'active' : ''}`} title={persistenceHint}><i />{status?.active ? `${status.count} 条请求${persistenceSuffix}` : '未捕获'}</span>
|
||||
{status?.active ? <Button variant="ghost" disabled={busy || !captureTarget} onClick={() => void run(async () => { setStatus(await request('network.capture.stop', captureTarget!)); setRecords([]); setSelectedId(''); }, '网络捕获已停止')}><Square size={14} />停止</Button> : <Button variant="primary" disabled={busy || !tab?.url?.startsWith('http')} onClick={() => void start()}><Play size={14} />开始捕获</Button>}
|
||||
</div></div>
|
||||
|
||||
<div className="network-control-bar">
|
||||
<label><Switch checked={captureHeaders} disabled={status?.active || busy} onCheckedChange={setCaptureHeaders} /><span><strong>请求头与 Cookie</strong><small>生成可重放请求所必需</small></span></label>
|
||||
<label><Switch checked={captureBody} disabled={status?.active || busy} onCheckedChange={setCaptureBody} /><span><strong>请求体</strong><small>每条最多保留 32 KiB</small></span></label>
|
||||
<div className="network-search"><Search size={14} /><input aria-label="筛选网络请求" placeholder="筛选 URL、方法或状态码" value={query} onChange={(event) => setQuery(event.target.value)} /></div>
|
||||
<Button size="icon" variant="ghost" title="刷新网络记录" aria-label="刷新网络记录" onClick={() => void load()}><RefreshCw size={15} /></Button>
|
||||
<Button size="icon" variant="ghost" title="清空网络记录" aria-label="清空网络记录" disabled={!status?.active || records.length === 0 || busy} onClick={() => void run(async () => { const next = await request('network.capture.clear', status!.target); setStatus(next); setRecords([]); setSelectedId(''); }, '网络记录已清空')}><Trash2 size={15} /></Button>
|
||||
</div>
|
||||
|
||||
{loadError ? <div className="network-error"><AlertTriangle size={15} />{loadError}<Button size="sm" variant="ghost" onClick={() => void load()}>重试</Button></div> : <div className="network-layout">
|
||||
<div className="network-timeline">
|
||||
<div className="network-table-head"><span>方法</span><span>状态</span><span>目标</span><span>类型</span><span>耗时</span></div>
|
||||
{visibleRecords.length === 0 ? <Empty>{status?.active ? '等待目标页面发出 Fetch/XHR 请求。' : '开始捕获后,网络请求会显示在这里。'}</Empty> : visibleRecords.map((record) => {
|
||||
const label = networkLabel(record);
|
||||
return <button className={`network-row ${selectedId === record.id ? 'selected' : ''}`} key={record.id} onClick={() => setSelectedId(record.id)}>
|
||||
<strong className={`method method-${record.method.toLowerCase()}`}>{record.method}</strong>
|
||||
<span className={record.error || (record.statusCode || 0) >= 400 ? 'status-error' : 'status-good'}>{record.error ? 'ERR' : record.statusCode || '...'}</span>
|
||||
<span className="network-target"><strong>{label.path || '/'}</strong><small>{label.host}</small></span>
|
||||
<span>{record.resourceType}</span>
|
||||
<span>{record.durationMs === undefined ? '—' : `${record.durationMs} ms`}</span>
|
||||
</button>;
|
||||
})}
|
||||
</div>
|
||||
|
||||
<aside className="network-inspector">
|
||||
{!selected ? <Empty>选择一条请求查看详情。</Empty> : <>
|
||||
<div className="network-inspector__heading"><div><span>{selected.method}</span><strong>{networkLabel(selected).path || '/'}</strong><small title={selected.url}>{selected.url}</small></div><span className={selected.error || (selected.statusCode || 0) >= 400 ? 'status-error' : 'status-good'}>{selected.error || selected.statusLine || selected.statusCode || 'Pending'}</span></div>
|
||||
<dl className="network-meta"><div><dt>来源</dt><dd>{selected.resourceType}</dd></div><div><dt>文档</dt><dd>{selected.documentId ? selected.documentId.slice(0, 12) : `frame ${selected.frameId}`}</dd></div><div><dt>大小</dt><dd>{selected.responseSize === undefined ? '未知' : `${selected.responseSize} B`}</dd></div><div><dt>耗时</dt><dd>{selected.durationMs === undefined ? '进行中' : `${selected.durationMs} ms`}</dd></div></dl>
|
||||
<div className="network-packet-heading"><strong>原始请求</strong><div><Button size="icon" variant="ghost" title="复制原始请求" aria-label="复制原始请求" disabled={!exported} onClick={() => void run(async () => { await navigator.clipboard.writeText(exported!.rawRequest); }, '原始请求已复制')}><Copy size={14} /></Button><Button size="sm" variant="ghost" disabled={!exported || !canGeneratePoc || busy} title={!canGeneratePoc ? '当前 Yak 引擎不支持 PoC 生成' : undefined} onClick={() => void run(async () => { setGeneratedPoc(await request('network.capture.poc', { ...status!.target, id: selected.id })); }, 'Yak PoC 已生成')}><Braces size={14} />PoC</Button><Button size="sm" variant="ghost" disabled={!exported || !canPrepareAnalysis || busy} title={!canPrepareAnalysis ? '当前 Yak 引擎不支持分析上下文' : undefined} onClick={() => void run(async () => { setAnalysisBundle(await request('network.capture.analysis', { ...status!.target, id: selected.id })); }, 'AI 分析上下文已生成')}><Bot size={14} />分析</Button><Button size="sm" variant="primary" disabled={!exported || !canSendToYakit || busy} title={!canSendToYakit ? '连接支持 Web Fuzzer 的 Yak 引擎后可用' : undefined} onClick={() => void run(async () => { await request('network.capture.send', { ...status!.target, id: selected.id }); }, '已在 Yakit 中打开 Web Fuzzer')}><Send size={14} />Yakit</Button></div></div>
|
||||
{exported ? <><pre className="network-packet">{exported.rawRequest}</pre>{exported.limitations.length > 0 && <div className="network-limitations"><AlertTriangle size={14} />{exported.limitations.join(';')}</div>}</> : <div className="network-preview-empty"><ShieldCheck size={16} /><span>{previewError || '该请求只保存了元数据。重新开始捕获并启用“请求头与 Cookie”后可生成重放包。'}</span></div>}
|
||||
{generatedPoc && <div className="network-artifact"><div><strong>{generatedPoc.fileName}</strong><Button size="icon" variant="ghost" title="复制 Yak PoC" aria-label="复制 Yak PoC" onClick={() => void run(async () => navigator.clipboard.writeText(generatedPoc.code), 'Yak PoC 已复制')}><Copy size={14} /></Button></div><pre>{generatedPoc.code}</pre></div>}
|
||||
{analysisBundle && <div className="network-artifact analysis"><div><strong>AI 分析上下文</strong><Button size="icon" variant="ghost" title="复制 AI 分析上下文" aria-label="复制 AI 分析上下文" onClick={() => void run(async () => navigator.clipboard.writeText(JSON.stringify(analysisBundle, null, 2)), 'AI 分析上下文已复制')}><Copy size={14} /></Button></div><pre>{JSON.stringify(analysisBundle, null, 2)}</pre></div>}
|
||||
</>}
|
||||
</aside>
|
||||
</div>}
|
||||
|
||||
<RecordingWorkspace
|
||||
tab={tab}
|
||||
busy={busy}
|
||||
run={run}
|
||||
gatewayShared={transformShared}
|
||||
onShareGateway={shareTransform}
|
||||
/>
|
||||
</div>;
|
||||
}
|
||||
|
||||
function ContextTool({ tab, run, busy }: { tab?: ActiveTabInfo; run: (task: () => Promise<void>, success?: string) => Promise<void>; busy: boolean }) {
|
||||
const [context, setContext] = useState<PageContext>();
|
||||
const [frames, setFrames] = useState<PageFrameSummary[]>([]);
|
||||
const [selectedFrameId, setSelectedFrameId] = useState(0);
|
||||
const [includeStorage, setIncludeStorage] = useState(false);
|
||||
const [includeCookies, setIncludeCookies] = useState(false);
|
||||
const [selectedNodeId, setSelectedNodeId] = useState('');
|
||||
const [nodeDetails, setNodeDetails] = useState<PageNodeDetails>();
|
||||
const [nodeError, setNodeError] = useState('');
|
||||
const [nodeQuery, setNodeQuery] = useState('');
|
||||
const [nodeValue, setNodeValue] = useState('');
|
||||
const [path, setPath] = useState('');
|
||||
const [args, setArgs] = useState('[]');
|
||||
const [result, setResult] = useState('');
|
||||
const [code, setCode] = useState(`({\n title: document.title,\n href: location.href,\n appGlobals: Object.keys(window).filter((key) => /encrypt|sign|crypto/i.test(key)).slice(0, 20)\n})`);
|
||||
const [evalMode, setEvalMode] = useState<'expression' | 'program'>('expression');
|
||||
const [evalResult, setEvalResult] = useState<PageEvalResult>();
|
||||
|
||||
useEffect(() => {
|
||||
if (!tab) return;
|
||||
void request('frame.list', { tabId: tab.id }).then((items) => {
|
||||
setFrames(items);
|
||||
if (!items.some((frame) => frame.frameId === selectedFrameId && frame.accessible)) setSelectedFrameId(0);
|
||||
}).catch(() => setFrames([]));
|
||||
}, [tab, selectedFrameId]);
|
||||
|
||||
const capture = () => run(async () => {
|
||||
const selectedSemanticKey = context?.document.interactive.find((node) => node.nodeId === selectedNodeId)?.semanticKey;
|
||||
const next = await request('context.capture', { includeDom: true, includeStorage, includeCookies, tabId: tab?.id, frameId: selectedFrameId });
|
||||
setContext(next);
|
||||
setSelectedNodeId(next.document.interactive.find((node) => node.semanticKey === selectedSemanticKey)?.nodeId || next.document.interactive[0]?.nodeId || '');
|
||||
setNodeDetails(undefined);
|
||||
setNodeError('');
|
||||
}, context ? '页面上下文与变化已刷新' : '页面上下文已采集');
|
||||
|
||||
useEffect(() => {
|
||||
setNodeDetails(undefined);
|
||||
setNodeError('');
|
||||
setNodeValue('');
|
||||
if (!context || !selectedNodeId) return;
|
||||
void request('context.node.inspect', { ...context.target, captureId: context.captureId, nodeId: selectedNodeId })
|
||||
.then(setNodeDetails)
|
||||
.catch((error) => setNodeError(errorMessage(error)));
|
||||
}, [context, selectedNodeId]);
|
||||
|
||||
const selectedNode = context?.document.interactive.find((node) => node.nodeId === selectedNodeId);
|
||||
const visibleNodes = context?.document.interactive.filter((node) => {
|
||||
const needle = nodeQuery.trim().toLowerCase();
|
||||
return !needle || node.accessibleName.toLowerCase().includes(needle) || node.text.toLowerCase().includes(needle)
|
||||
|| node.tag.toLowerCase().includes(needle) || node.role.toLowerCase().includes(needle) || node.nodeId.includes(needle);
|
||||
}) || [];
|
||||
const authLabel = context?.authentication.status === 'authenticated' ? '可能已登录'
|
||||
: context?.authentication.status === 'unauthenticated' ? '可能未登录' : '登录态未知';
|
||||
const diffLabel = context?.diff.kind === 'initial' ? '首次快照' : context?.diff.kind === 'unchanged' ? '没有变化'
|
||||
: context?.diff.kind === 'document_changed' ? '文档已变化' : '发现变化';
|
||||
const canSetValue = selectedNode && ['input', 'textarea', 'select'].includes(selectedNode.tag) && selectedNode.type !== 'file';
|
||||
const act = (action: 'click' | 'focus' | 'scroll' | 'setValue') => run(async () => {
|
||||
if (!context || !selectedNode) throw new Error('请选择页面元素');
|
||||
const response = await request('context.node.action', {
|
||||
...context.target, captureId: context.captureId, nodeId: selectedNode.nodeId, action,
|
||||
...(action === 'setValue' ? { value: nodeValue } : {}),
|
||||
});
|
||||
setNodeDetails(response.node);
|
||||
}, action === 'click' ? '已向页面元素发送点击' : action === 'setValue' ? '页面字段已写入' : '页面元素已定位');
|
||||
|
||||
return <div className="section-view">
|
||||
<div className="page-heading"><div><h1>登录态工作区</h1><p>生成文档绑定的结构化快照,识别认证信号并跟踪页面变化。</p></div><Button variant="primary" disabled={busy || !tab?.url?.startsWith('http')} onClick={() => void capture()}><RefreshCw size={16} />{context ? '刷新并比较' : '采集页面'}</Button></div>
|
||||
<div className="context-options"><label className="check-row"><input type="checkbox" checked={includeStorage} onChange={(event) => setIncludeStorage(event.target.checked)} />读取 Storage 值与数据库清单</label><label className="check-row"><input type="checkbox" checked={includeCookies} onChange={(event) => setIncludeCookies(event.target.checked)} />读取 Cookie 值</label><select aria-label="目标 frame" value={selectedFrameId} onChange={(event) => { setSelectedFrameId(Number(event.target.value)); setContext(undefined); }}>{frames.filter((frame) => frame.accessible).map((frame) => <option key={frame.frameId} value={frame.frameId}>#{frame.frameId} · {frame.isTop ? '主 frame' : frame.sameOrigin ? '同源' : '跨源'} · {frame.title || frame.origin}</option>)}</select><span>{tab?.url || '当前标签页不可访问'}</span></div>
|
||||
<Tabs defaultValue="workspace" className="context-mode">
|
||||
<TabsList className={`context-mode-tabs ${FIREFOX_AMO_BUILD ? 'invoke-only' : ''}`}><TabsTrigger value="workspace">浏览器现场</TabsTrigger>{!FIREFOX_AMO_BUILD && <><TabsTrigger value="invoke">函数调用</TabsTrigger><TabsTrigger value="eval">主世界 Eval</TabsTrigger></>}<TabsTrigger value="json">原始 JSON</TabsTrigger></TabsList>
|
||||
<TabsContent value="workspace" className="context-workspace-tab">
|
||||
{!context ? <div className="context-empty"><KeyRound size={25} /><strong>尚未建立页面快照</strong><span>采集后显示登录态、上下文变化和可操作元素。</span></div> : <>
|
||||
<div className="context-session-strip">
|
||||
<div className={`auth-state ${context.authentication.status}`}><ShieldCheck size={17} /><span><small>认证判断</small><strong>{authLabel}</strong></span><i>{Math.round(context.authentication.confidence * 100)}%</i></div>
|
||||
<div><small>快照</small><strong>{context.captureId.slice(0, 8)}</strong><span>{new Date(context.capturedAt).toLocaleTimeString()}</span></div>
|
||||
<div><small>变化</small><strong>{diffLabel}</strong><span>{context.diff.changedSections.length ? context.diff.changedSections.map((section) => CONTEXT_SECTION_LABELS[section]).join(' / ') : '当前为比较基线'}</span></div>
|
||||
<div><small>文档</small><strong>{context.target.documentId?.slice(0, 12) || `frame ${context.target.frameId}`}</strong><span>{context.frames.length} 个 frame · {context.document.interactive.length} 个节点</span></div>
|
||||
</div>
|
||||
<div className="context-workspace">
|
||||
<div className="context-primary">
|
||||
<section className="context-diff"><div className="context-section-heading"><div><h2>上下文变化</h2><span>{context.diff.fromCaptureId ? `${context.diff.fromCaptureId.slice(0, 8)} → ${context.captureId.slice(0, 8)}` : '等待下一次快照'}</span></div><span className={`diff-state ${context.diff.kind}`}>{diffLabel}</span></div>
|
||||
<div className="diff-summary"><span><strong>+{context.diff.addedNodes.length}</strong>节点</span><span><strong>-{context.diff.removedNodes.length}</strong>节点</span><span><strong>+{context.diff.addedCookieNames.length}</strong>Cookie</span><span><strong>+{context.diff.addedStorageKeys.length}</strong>Storage</span></div>
|
||||
{(context.diff.addedNodes.length > 0 || context.diff.removedNodes.length > 0) && <div className="diff-events">{context.diff.addedNodes.slice(0, 4).map((node) => <span key={`add:${node.semanticKey}`}><i>+</i>{node.text || node.tag}</span>)}{context.diff.removedNodes.slice(0, 4).map((node) => <span key={`remove:${node.semanticKey}`} className="removed"><i>-</i>{node.text || node.tag}</span>)}</div>}
|
||||
</section>
|
||||
<section className="context-inventory"><div className="context-section-heading"><div><h2>页面现场清单</h2><span>frame、浏览器存储和当前文档生命周期</span></div></div><div className="context-inventory-grid">
|
||||
<div><strong>Frames</strong><span>{context.frames.length}</span><ul>{context.frames.slice(0, 12).map((frame) => <li key={frame.frameId}><i className={frame.accessible ? 'ready' : ''} /> <b>#{frame.frameId}</b><span>{frame.isTop ? '主 frame' : frame.sameOrigin ? '同源' : '跨源'}</span><small title={frame.url}>{frame.origin || frame.url}</small></li>)}</ul></div>
|
||||
<div><strong>IndexedDB / Cache</strong><span>{context.document.storageInventory ? context.document.storageInventory.indexedDB.databases.length + context.document.storageInventory.cacheStorage.names.length : 0}</span>{context.document.storageInventory ? <ul>{context.document.storageInventory.indexedDB.databases.slice(0, 6).map((database) => <li key={`db:${database.name}`}><Database size={11} /><b>{database.name}</b><span>{database.stores.length} stores</span></li>)}{context.document.storageInventory.cacheStorage.names.slice(0, 6).map((name) => <li key={`cache:${name}`}><Database size={11} /><b>{name}</b><span>Cache</span></li>)}</ul> : <p>启用 Storage 后采集数据库与 Cache 名称。</p>}</div>
|
||||
<div><strong>Lifecycle</strong><span>{context.lifecycle.length}</span><ul>{context.lifecycle.slice(-8).reverse().map((event) => <li key={event.id}><i className={event.kind} /><b>{event.kind}</b><span>frame #{event.frameId}</span><small>{new Date(event.timestamp).toLocaleTimeString()}</small></li>)}</ul>{context.lifecycle.length === 0 && <p>当前文档尚未记录 SPA 或导航变化。</p>}</div>
|
||||
</div></section>
|
||||
<section className="context-node-browser"><div className="context-section-heading"><div><h2>可操作元素</h2><span>引用仅在当前快照和文档内有效</span></div><div className="context-node-search"><Search size={14} /><input aria-label="筛选页面元素" placeholder="筛选名称、标签或 nodeId" value={nodeQuery} onChange={(event) => setNodeQuery(event.target.value)} /></div></div>
|
||||
<div className="context-node-head"><span>元素</span><span>类型</span><span>引用</span><span>状态</span></div>
|
||||
<div className="context-node-list">{visibleNodes.length === 0 ? <Empty>当前快照没有匹配的可操作元素。</Empty> : visibleNodes.map((node) => <button key={node.nodeId} className={node.nodeId === selectedNodeId ? 'active' : ''} onClick={() => setSelectedNodeId(node.nodeId)}><span><strong>{node.accessibleName || node.text || node.name || '未命名元素'}</strong><small>{node.selectorHint}</small></span><code>{node.tag}{node.type ? `:${node.type}` : ''}</code><code>{node.nodeId}</code><i className={node.visible && !node.disabled ? 'ready' : ''}>{node.disabled ? '禁用' : node.visible ? '可见' : '隐藏'}</i></button>)}</div>
|
||||
</section>
|
||||
</div>
|
||||
<aside className="context-inspector">
|
||||
<section><div className="context-section-heading"><div><h2>元素检查器</h2><span>{selectedNode?.nodeId || '未选择'}</span></div><Eye size={15} /></div>
|
||||
{!selectedNode ? <div className="context-inspector-empty">选择一个节点查看稳定引用和可用操作。</div> : <>{nodeError ? <div className="context-node-error"><AlertTriangle size={14} />{nodeError}</div> : <>
|
||||
<div className="node-identity"><code>{selectedNode.tag}{selectedNode.type ? `:${selectedNode.type}` : ''}</code><strong>{selectedNode.accessibleName || selectedNode.text || selectedNode.name || '未命名元素'}</strong><span>{selectedNode.selectorHint}</span></div>
|
||||
<dl className="node-properties"><div><dt>Capture</dt><dd>{context.captureId.slice(0, 12)}</dd></div><div><dt>Node</dt><dd>{selectedNode.nodeId}</dd></div><div><dt>Frame</dt><dd>{context.target.frameId}</dd></div><div><dt>Shadow</dt><dd>{selectedNode.shadowDepth}</dd></div>{nodeDetails?.bounds && <><div><dt>X / Y</dt><dd>{Math.round(nodeDetails.bounds.x)} / {Math.round(nodeDetails.bounds.y)}</dd></div><div><dt>尺寸</dt><dd>{Math.round(nodeDetails.bounds.width)} × {Math.round(nodeDetails.bounds.height)}</dd></div></>}</dl>
|
||||
<div className="node-actions"><Button size="sm" variant="ghost" disabled={busy} onClick={() => void act('scroll')}><Radio size={14} />定位</Button><Button size="sm" variant="ghost" disabled={busy} onClick={() => void act('focus')}><Eye size={14} />聚焦</Button><Button size="sm" variant="primary" disabled={busy || selectedNode.disabled} onClick={() => void act('click')}><MousePointer2 size={14} />点击</Button></div>
|
||||
{canSetValue && <div className="node-value-editor"><Field label="写入字段值"><input type={selectedNode.type === 'password' ? 'password' : 'text'} value={nodeValue} onChange={(event) => setNodeValue(event.target.value)} /></Field><Button size="sm" disabled={busy} onClick={() => void act('setValue')}>写入</Button></div>}
|
||||
</>}</>}
|
||||
</section>
|
||||
<section className="auth-evidence"><div className="context-section-heading"><div><h2>认证信号</h2><span>启发式判断,不等同于服务端会话验证</span></div></div>{context.authentication.evidence.length ? <ul>{context.authentication.evidence.map((item) => <li key={item}>{item}</li>)}</ul> : <div className="context-inspector-empty">没有发现明确的登录或退出信号。</div>}{context.authentication.cookieNames.length > 0 && <div className="signal-names"><strong>Cookie</strong><span>{context.authentication.cookieNames.join(', ')}</span></div>}{context.authentication.storageKeys.length > 0 && <div className="signal-names"><strong>Storage</strong><span>{context.authentication.storageKeys.join(', ')}</span></div>}</section>
|
||||
</aside>
|
||||
</div>
|
||||
</>}
|
||||
</TabsContent>
|
||||
{!FIREFOX_AMO_BUILD && <><TabsContent value="invoke" className="context-utility-panel"><h2>调用页面函数</h2><p>按全局路径复用页面已有的签名、加密或解密逻辑。</p><Field label="函数路径"><input value={path} onChange={(event) => setPath(event.target.value)} placeholder="app.crypto.encrypt" /></Field><Field label="参数 JSON 数组"><textarea rows={7} value={args} onChange={(event) => setArgs(event.target.value)} /></Field><Button variant="primary" disabled={busy || !path} onClick={() => void run(async () => { const parsed = JSON.parse(args); if (!Array.isArray(parsed)) throw new Error('参数必须是 JSON 数组'); setResult(JSON.stringify(await request('context.invoke', { path, args: parsed, tabId: tab?.id }), null, 2)); }, '页面函数调用完成')}><Braces size={16} />执行函数</Button>{result && <pre className="invoke-result">{result}</pre>}</TabsContent>
|
||||
<TabsContent value="eval" className="context-utility-panel">
|
||||
<h2>页面主世界 Eval</h2>
|
||||
<div className="segmented eval-mode"><button className={evalMode === 'expression' ? 'active' : ''} onClick={() => setEvalMode('expression')}>表达式</button><button className={evalMode === 'program' ? 'active' : ''} onClick={() => setEvalMode('program')}>程序</button></div>
|
||||
<div className="eval-warning"><ShieldCheck size={15} /><span>{evalMode === 'program' ? '程序模式是 async 函数体,返回结果需显式使用 return,并需要独立的 browser.page.eval.program 授权。' : '表达式模式自动返回表达式值,Agent 只需要 browser.page.eval.expression 授权。'}</span></div>
|
||||
<Field label={evalMode === 'expression' ? 'JavaScript 表达式' : 'JavaScript 程序'}><textarea className="code-editor" rows={12} value={code} onChange={(event) => setCode(event.target.value)} spellCheck={false} /></Field>
|
||||
<Button variant="primary" disabled={busy || !code.trim()} onClick={() => void run(async () => setEvalResult(await request('context.eval', { mode: evalMode, code, tabId: tab?.id, timeoutMs: 10_000 })), '页面代码执行完成')}><Braces size={16} />预览目标后执行</Button>
|
||||
{evalResult && <div className="eval-result-meta"><span>模式 {evalMode}</span><span>类型 {evalResult.type}</span><span>{evalResult.durationMs} ms</span>{evalResult.truncated && <span>结果已截断</span>}</div>}{evalResult && <pre className="invoke-result">{JSON.stringify(evalResult.value, null, 2)}</pre>}
|
||||
</TabsContent></>}
|
||||
<TabsContent value="json" className="context-json"><div className="panel-title"><span>结构化上下文</span>{context && <button onClick={() => void navigator.clipboard.writeText(JSON.stringify(context, null, 2))}>复制 JSON</button>}</div><pre>{context ? JSON.stringify(context, null, 2) : '尚未采集页面上下文。'}</pre></TabsContent>
|
||||
</Tabs>
|
||||
</div>;
|
||||
}
|
||||
|
||||
function EngineSettings({ state, setState, bridge, setBridge, tabs, run, busy }: { state: ExtensionState; setState: (state: ExtensionState) => void; bridge: BridgeStatus; setBridge: (status: BridgeStatus) => void; tabs: ActiveTabInfo[]; run: (task: () => Promise<void>, success?: string) => Promise<void>; busy: boolean }) {
|
||||
const [draft, setDraft] = useState(state.bridge);
|
||||
const [pairing, setPairing] = useState<BridgePairingStatus>({ state: 'idle', message: state.bridge.pairedEngine ? '当前浏览器已配对' : '尚未配对' });
|
||||
const [panelDraft, setPanelDraft] = useState(state.floatingPanel);
|
||||
const [policy, setPolicy] = useState<EnterprisePolicyStatus>({ managed: false, policy: {}, warnings: [] });
|
||||
useEffect(() => {
|
||||
void request('policy.status').then(setPolicy).catch(() => undefined);
|
||||
void request('bridge.pair.status').then(setPairing).catch(() => undefined);
|
||||
const listener = (message: unknown) => {
|
||||
const input = message as { action?: string; payload?: BridgePairingStatus };
|
||||
if (input.action === 'bridge.pairing.status.changed' && input.payload) setPairing(input.payload);
|
||||
};
|
||||
browser.runtime.onMessage.addListener(listener);
|
||||
return () => browser.runtime.onMessage.removeListener(listener);
|
||||
}, []);
|
||||
useEffect(() => setDraft(state.bridge), [state.bridge]);
|
||||
const save = () => run(async () => {
|
||||
if (draft.transport === 'native') {
|
||||
// Permission requests must be the first browser call made from the click gesture.
|
||||
const granted = await browser.permissions.request({ permissions: ['nativeMessaging'] });
|
||||
if (!granted) throw new Error('使用 Native Host 需要用户授予 Native Messaging 权限');
|
||||
}
|
||||
setState(await request('bridge.config.save', draft));
|
||||
}, 'Bridge 设置已保存');
|
||||
const savePanel = () => run(async () => {
|
||||
const siteOrigins = panelDraft.siteOrigins.map((value) => new URL(value).origin);
|
||||
const next = await request('panel.update', { ...panelDraft, siteOrigins });
|
||||
setState(next);
|
||||
setPanelDraft(next.floatingPanel);
|
||||
}, '悬浮面板策略已保存');
|
||||
return <div className="section-view engine-view">
|
||||
<div className="page-heading"><div><h1>Yak 引擎连接</h1><p>扩展主动连接本机 Bridge,网页无法直接访问此通道。</p></div><span className={`large-status ${bridge.state}`}><Radio size={16} />{bridge.message}</span></div>
|
||||
{policy.managed && <div className="managed-policy-banner"><ShieldCheck size={16} /><span><strong>此浏览器由组织策略管理</strong><small>{policy.policy.disableWebSocket ? '必须使用 Native Messaging' : policy.policy.bridgeTransport ? `传输锁定为 ${policy.policy.bridgeTransport}` : '连接与授权限制已应用'}{policy.policy.maxGrantMinutes ? ` · 授权最长 ${policy.policy.maxGrantMinutes} 分钟` : ''}{policy.policy.allowProgramEval === false ? ' · 程序 Eval 已禁用' : ''}</small>{policy.warnings.map((warning) => <i key={warning}>{warning}</i>)}</span></div>}
|
||||
{bridge.state === 'connected' && <div className="bridge-identity-strip"><div><span>引擎实例</span><code title={bridge.engineInstanceId}>{bridge.engineInstanceId?.slice(0, 18)}</code></div><div><span>连接</span><code title={bridge.connectionId}>{bridge.connectionId?.slice(0, 18)}</code></div><div><span>会话</span><code title={bridge.sessionId}>{bridge.sessionId?.slice(0, 18)}</code></div><div><span>心跳</span><strong>{bridge.latencyMs === undefined ? '等待首个回执' : `${bridge.latencyMs} ms`}</strong></div><div><span>恢复</span><strong>{bridge.resumed ? '已恢复 task session' : '新会话'}</strong></div></div>}
|
||||
<div className="engine-layout"><div className="settings-form">
|
||||
<section className={`pairing-workspace ${state.bridge.pairedEngine ? 'paired' : pairing.state}`}>
|
||||
<div className="pairing-workspace__heading"><span className="pairing-icon"><KeyRound size={19} /></span><div><h2>{state.bridge.pairedEngine ? '浏览器已安全配对' : pairing.state === 'pending' ? '等待 Yakit 确认' : '连接本机 Yakit'}</h2><p>{state.bridge.pairedEngine ? '设备身份已锁定到首次批准的 Yak 引擎。' : pairing.message}</p></div></div>
|
||||
{pairing.state === 'pending' && <div className="pairing-code" aria-live="polite"><span>配对验证码</span><strong>{pairing.code?.slice(0, 3)} {pairing.code?.slice(3)}</strong><small>{pairing.expiresAt ? `${Math.max(0, Math.ceil((pairing.expiresAt - Date.now()) / 1000))} 秒内有效` : ''}</small></div>}
|
||||
{state.bridge.pairedEngine && <div className="paired-engine-meta"><div><span>引擎身份</span><code title={state.bridge.pairedEngine.engineIdentityId}>{state.bridge.pairedEngine.engineIdentityId.slice(0, 24)}</code></div><div><span>设备 ID</span><code title={state.bridge.pairedEngine.deviceId}>{state.bridge.pairedEngine.deviceId.slice(0, 24)}</code></div></div>}
|
||||
<div className="editor-actions">
|
||||
{!state.bridge.pairedEngine && pairing.state !== 'pending' && <Button variant="primary" disabled={busy || pairing.state === 'requesting'} onClick={() => void run(async () => setPairing(await request('bridge.pair')))}><Power size={16} />{pairing.state === 'requesting' ? '正在查找' : '查找本机 Yakit'}</Button>}
|
||||
{!state.bridge.pairedEngine && pairing.state === 'pending' && <Button disabled={busy} onClick={() => void run(async () => setPairing(await request('bridge.pair.cancel')))}><X size={16} />取消申请</Button>}
|
||||
{state.bridge.pairedEngine && <Button variant="primary" disabled={busy} onClick={() => void run(async () => { if (bridge.state === 'connected') await request('bridge.disconnect'); else await request('bridge.connect'); setBridge(await request('bridge.status')); }, bridge.state === 'connected' ? 'Bridge 已断开' : 'Bridge 正在连接')}><Power size={16} />{bridge.state === 'connected' ? '断开连接' : '连接引擎'}</Button>}
|
||||
{state.bridge.pairedEngine && <Button variant="ghost" disabled={busy} onClick={() => { if (window.confirm('解除当前 Yak 引擎的本地配对?浏览器安装身份会保留,重新配对时 Yakit 将更新原可信记录。')) void run(async () => { const next = await request('bridge.unpair'); setState(next); setDraft(next.bridge); }, '本地配对凭据已清除'); }}><Trash2 size={16} />解除配对</Button>}
|
||||
</div>
|
||||
</section>
|
||||
<details className="advanced-connection"><summary>高级连接设置</summary><div className="advanced-connection__body">
|
||||
<div className="segmented"><button disabled={Boolean(policy.policy.bridgeTransport || policy.policy.disableWebSocket)} className={draft.transport === 'websocket' ? 'active' : ''} onClick={() => setDraft({ ...draft, transport: 'websocket' })}>本机 WebSocket</button><button disabled={Boolean(policy.policy.bridgeTransport || policy.policy.disableWebSocket)} className={draft.transport === 'native' ? 'active' : ''} onClick={() => setDraft({ ...draft, transport: 'native' })}>Native Host</button></div>
|
||||
{draft.transport === 'native' ? <Field label="Native Host" hint="仅在已安装 Yakit Native Host 时使用"><input disabled={Boolean(policy.policy.nativeHost)} value={draft.nativeHost} onChange={(event) => setDraft({ ...draft, nativeHost: event.target.value })} /></Field> : <Field label="WebSocket Endpoint" hint="只允许 127.0.0.1、localhost 或 ::1"><input disabled={Boolean(policy.policy.bridgeEndpoint)} value={draft.endpoint} onChange={(event) => setDraft({ ...draft, endpoint: event.target.value })} /></Field>}
|
||||
<label className="toggle-row"><span><strong>启动扩展时自动连接</strong><small>{draft.transport === 'native' ? '由浏览器拉起已注册的 Yakit Host' : 'Service Worker 使用心跳维持本机连接'}</small></span><Switch disabled={policy.policy.autoConnect !== undefined || !draft.pairedEngine} checked={draft.autoConnect} onCheckedChange={(checked) => setDraft({ ...draft, autoConnect: checked })} /></label>
|
||||
<div className="editor-actions"><Button disabled={busy} onClick={() => void save()}><Save size={16} />保存高级设置</Button></div>
|
||||
</div></details>
|
||||
<section className="panel-policy-settings"><h2>网页侧边工具</h2>
|
||||
<label className="toggle-row"><span><strong>启用悬浮面板</strong><small>轻量启动器常驻,React 工作台仅在展开时加载</small></span><Switch disabled={policy.policy.floatingPanelEnabled !== undefined} checked={panelDraft.enabled} onCheckedChange={(enabled) => setPanelDraft({ ...panelDraft, enabled })} /></label>
|
||||
<div className="panel-policy-grid"><Field label="显示条件"><select value={panelDraft.displayMode} onChange={(event) => setPanelDraft({ ...panelDraft, displayMode: event.target.value as 'always' | 'active-task' })}><option value="always">符合站点规则时显示</option><option value="active-task">仅活动任务或人工接管时显示</option></select></Field><Field label="站点规则"><select value={panelDraft.siteMode} onChange={(event) => setPanelDraft({ ...panelDraft, siteMode: event.target.value as 'all' | 'allowlist' | 'denylist' })}><option value="all">所有 HTTP(S) 站点</option><option value="allowlist">仅允许列表</option><option value="denylist">排除列表</option></select></Field></div>
|
||||
{panelDraft.siteMode !== 'all' && <Field label="站点 Origin" hint="每行一个完整 origin"><textarea rows={4} value={panelDraft.siteOrigins.join('\n')} onChange={(event) => setPanelDraft({ ...panelDraft, siteOrigins: event.target.value.split(/\s+/).filter(Boolean) })} placeholder="https://app.example.com" /></Field>}
|
||||
<label className="toggle-row"><span><strong>页面内快捷展开</strong><small>仅在当前站点策略允许显示时生效</small></span><Switch checked={panelDraft.shortcutEnabled} onCheckedChange={(shortcutEnabled) => setPanelDraft({ ...panelDraft, shortcutEnabled })} /></label>
|
||||
<label className="toggle-row"><span><strong>全屏自动收起</strong><small>进入全屏、演示或视频场景时关闭展开内容</small></span><Switch checked={panelDraft.autoCollapseFullscreen} onCheckedChange={(autoCollapseFullscreen) => setPanelDraft({ ...panelDraft, autoCollapseFullscreen })} /></label>
|
||||
<div className="editor-actions"><Button disabled={busy} onClick={() => void savePanel()}><Save size={16} />保存面板策略</Button></div>
|
||||
</section>
|
||||
<div className="grant-editor"><h2>浏览器实例访问</h2><p>配对成功后,Yakit 可直接引用此浏览器中的全部 HTTP(S) 页面;刷新、跳转和新标签页会自动跟随,不再逐页授权。</p><div className="grant-status"><strong>{bridge.state === 'connected' ? '实例已连接' : state.bridge.pairedEngine ? '实例已配对,当前离线' : '实例尚未配对'}</strong><span>{tabs.length} 个可访问页面 · 浏览器内部页始终排除 · 无痕窗口沿用浏览器自己的独立访问开关</span></div><div className="grant-scope-list"><span>人工:逐次确认 · 协同 AI:按风险判断 · YOLO:自动执行</span><span>{policy.policy.allowProgramEval === false ? '程序 Eval 已被企业策略禁用' : '程序 Eval 在 YOLO 下无需手动批准,仍受浏览器与企业策略限制'}</span>{policy.policy.grantAllowedOrigins?.length ? <span>企业来源白名单:{policy.policy.grantAllowedOrigins.length} 项</span> : null}</div></div>
|
||||
</div>
|
||||
<div className="protocol-panel"><h2>Bridge 方法</h2><div><code>browser.tabs / tab.open / frames</code><span>列出当前实例的 HTTP(S) 标签页、打开网页并读取完整 frame inventory</span></div><div><code>browser.context</code><span>生成结构化快照、存储 inventory、认证信号与上下文 diff</span></div><div><code>browser.node.*</code><span>检查或操作快照内的文档绑定节点引用</span></div><div><code>browser.cookies</code><span>读取指定标签页的浏览器 Cookie</span></div><div><code>browser.network.*</code><span>控制有界网络捕获、读取请求时间线并导出重放包</span></div><div><code>browser.takeover</code><span>将页面切到前台,交给用户扫码或二次验证</span></div><div><code>browser.invoke</code><span>调用页面已有全局函数</span></div><div><code>browser.eval</code><span>在页面主世界执行代码,支持 Promise 和超时</span></div><div><code>proxy.list / switch</code><span>读取并切换扩展代理配置</span></div></div>
|
||||
</div>
|
||||
</div>;
|
||||
}
|
||||
|
||||
export default App;
|
||||
@@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Yakit Browser Agent</title>
|
||||
<meta name="manifest.open_in_tab" content="true" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="./main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,11 @@
|
||||
import React from 'react';
|
||||
import {createRoot} from 'react-dom/client';
|
||||
import App from './App';
|
||||
import { watchTheme } from '@/platform/storage/appearance';
|
||||
import '@/styles/global.css'
|
||||
import './style.css';
|
||||
|
||||
watchTheme();
|
||||
|
||||
const root = createRoot(document.getElementById('app')!);
|
||||
root.render(<App/>);
|
||||
@@ -0,0 +1,2 @@
|
||||
html { scrollbar-gutter: stable; }
|
||||
html, body, #app { min-width: 320px; min-height: 100%; margin: 0; }
|
||||
@@ -0,0 +1,141 @@
|
||||
import {
|
||||
PAGE_REQUEST_EVENT,
|
||||
PAGE_RESPONSE_EVENT,
|
||||
type PageBridgeRequest,
|
||||
type PageBridgeResponse,
|
||||
} from '@/features/page-context/protocol';
|
||||
|
||||
export default defineUnlistedScript(() => {
|
||||
const script = document.currentScript;
|
||||
if (!script || script.getAttribute('data-yakit-page-bridge-ready') === 'true') return;
|
||||
script.setAttribute('data-yakit-page-bridge-ready', 'true');
|
||||
|
||||
const MAX_DEPTH = 6;
|
||||
const MAX_ITEMS = 100;
|
||||
const MAX_STRING = 100_000;
|
||||
|
||||
function serialize(value: unknown): { value: unknown; type: string; preview: string; truncated: boolean } {
|
||||
const seen = new WeakSet<object>();
|
||||
let truncated = false;
|
||||
|
||||
const visit = (input: unknown, depth: number): unknown => {
|
||||
if (input === null) return null;
|
||||
if (typeof input === 'string') {
|
||||
if (input.length > MAX_STRING) truncated = true;
|
||||
return input.slice(0, MAX_STRING);
|
||||
}
|
||||
if (typeof input === 'number' || typeof input === 'boolean') return input;
|
||||
if (typeof input === 'undefined') return { $type: 'undefined' };
|
||||
if (typeof input === 'bigint') return { $type: 'bigint', value: input.toString() };
|
||||
if (typeof input === 'symbol') return { $type: 'symbol', value: String(input) };
|
||||
if (typeof input === 'function') {
|
||||
const source = Function.prototype.toString.call(input);
|
||||
if (source.length > 2_000) truncated = true;
|
||||
return { $type: 'function', name: input.name || '', source: source.slice(0, 2_000) };
|
||||
}
|
||||
if (depth >= MAX_DEPTH) {
|
||||
truncated = true;
|
||||
return { $type: 'max-depth', constructor: (input as object).constructor?.name || 'Object' };
|
||||
}
|
||||
if (seen.has(input as object)) return { $type: 'circular' };
|
||||
seen.add(input as object);
|
||||
|
||||
if (input instanceof Error) {
|
||||
return { $type: 'error', name: input.name, message: input.message, stack: input.stack?.slice(0, 10_000) };
|
||||
}
|
||||
if (input instanceof Date) return { $type: 'date', value: input.toISOString() };
|
||||
if (input instanceof RegExp) return { $type: 'regexp', value: String(input) };
|
||||
if (input instanceof Node) {
|
||||
const element = input instanceof Element ? input : input.parentElement;
|
||||
const html = element?.outerHTML || input.textContent || '';
|
||||
if (html.length > 10_000) truncated = true;
|
||||
return {
|
||||
$type: 'node',
|
||||
name: input.nodeName,
|
||||
html: html.slice(0, 10_000),
|
||||
};
|
||||
}
|
||||
if (Array.isArray(input)) {
|
||||
if (input.length > MAX_ITEMS) truncated = true;
|
||||
return input.slice(0, MAX_ITEMS).map((item) => visit(item, depth + 1));
|
||||
}
|
||||
|
||||
const output: Record<string, unknown> = {};
|
||||
const keys = Reflect.ownKeys(input as object).slice(0, MAX_ITEMS);
|
||||
if (Reflect.ownKeys(input as object).length > MAX_ITEMS) truncated = true;
|
||||
for (const key of keys) {
|
||||
const name = typeof key === 'symbol' ? `[${String(key)}]` : key;
|
||||
try {
|
||||
output[name] = visit(Reflect.get(input as object, key), depth + 1);
|
||||
} catch (error) {
|
||||
output[name] = { $type: 'unreadable', message: error instanceof Error ? error.message : String(error) };
|
||||
}
|
||||
}
|
||||
return output;
|
||||
};
|
||||
|
||||
const normalized = visit(value, 0);
|
||||
let preview: string;
|
||||
try {
|
||||
preview = typeof value === 'string' ? value : JSON.stringify(normalized);
|
||||
} catch {
|
||||
preview = String(value);
|
||||
}
|
||||
return {
|
||||
value: normalized,
|
||||
type: value === null ? 'null' : typeof value,
|
||||
preview: preview.slice(0, 2_000),
|
||||
truncated: truncated || preview.length > 2_000,
|
||||
};
|
||||
}
|
||||
|
||||
script.addEventListener(PAGE_REQUEST_EVENT, (rawEvent) => {
|
||||
if (!(rawEvent instanceof CustomEvent) || typeof rawEvent.detail !== 'string') return;
|
||||
void (async () => {
|
||||
let request: PageBridgeRequest;
|
||||
try {
|
||||
request = JSON.parse(rawEvent.detail) as PageBridgeRequest;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const startedAt = performance.now();
|
||||
let response: PageBridgeResponse;
|
||||
try {
|
||||
let rawResult: unknown;
|
||||
if (request.operation === 'eval') {
|
||||
const source = request.mode === 'expression'
|
||||
? `(${request.code}\n)`
|
||||
: `(async () => {\n${request.code}\n})()`;
|
||||
rawResult = (0, eval)(source);
|
||||
} else {
|
||||
const segments = request.path.split('.').filter(Boolean);
|
||||
let owner: unknown = window;
|
||||
let target: unknown = window;
|
||||
for (const segment of segments) {
|
||||
owner = target;
|
||||
target = Reflect.get(target as object, segment);
|
||||
}
|
||||
if (typeof target !== 'function') throw new TypeError(`${request.path} is not a function`);
|
||||
rawResult = Reflect.apply(target, owner, request.args);
|
||||
}
|
||||
const result = serialize(await rawResult);
|
||||
response = {
|
||||
id: request.id,
|
||||
ok: true,
|
||||
result: { ...result, durationMs: Math.round((performance.now() - startedAt) * 100) / 100 },
|
||||
};
|
||||
} catch (error) {
|
||||
response = {
|
||||
id: request.id,
|
||||
ok: false,
|
||||
error: {
|
||||
name: error instanceof Error ? error.name : 'Error',
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
stack: error instanceof Error ? error.stack?.slice(0, 10_000) : undefined,
|
||||
},
|
||||
};
|
||||
}
|
||||
script.dispatchEvent(new CustomEvent(PAGE_RESPONSE_EVENT, { detail: JSON.stringify(response) }));
|
||||
})();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,970 @@
|
||||
import { PAGE_RECORDER_PROTOCOL_VERSION, PAGE_RECORDER_REGISTRY_KEY } from '@/features/browser-recording/constants';
|
||||
import {
|
||||
PAGE_RECORDER_REQUEST_EVENT,
|
||||
PAGE_RECORDER_RESPONSE_EVENT,
|
||||
type PageRecorderBridgeCommand,
|
||||
type PageRecorderBridgeRequest,
|
||||
type PageRecorderBridgeResponse,
|
||||
} from '@/features/browser-recording/bridge-protocol';
|
||||
import { PAGE_CALLABLE_REGISTRY_KEY } from '@/features/page-callable/constants';
|
||||
import { executeRequestTransaction, executeSideEffectFreeCallable } from '@/features/page-callable/request-transaction';
|
||||
import { callableExecutionPolicy, settleCallableResult } from '@/features/page-callable/execution';
|
||||
import {
|
||||
createCryptoAdapterRuntime,
|
||||
PAGE_CRYPTO_ADAPTERS,
|
||||
type CallableOperationKind,
|
||||
type CryptoAdapterInvocationPlan,
|
||||
type CryptoAdapterOperation,
|
||||
type CryptoAdapterRuntime,
|
||||
type CryptoAdapterToolkit,
|
||||
} from '@/features/browser-crypto/adapters';
|
||||
import { executeTransformDirection } from '@/features/browser-transform/mapping';
|
||||
import {
|
||||
createCommunicationBoundaryRuntime,
|
||||
type CommunicationBoundaryRuntime,
|
||||
} from '@/features/browser-recording/main-world/boundaries/communication';
|
||||
import {
|
||||
createNetworkBoundaryRuntime,
|
||||
type NetworkBoundaryRuntime,
|
||||
} from '@/features/browser-recording/main-world/boundaries/network';
|
||||
import {
|
||||
createRequestPreparationRuntime,
|
||||
type RequestPreparationRuntime,
|
||||
} from '@/features/browser-recording/main-world/boundaries/request-preparation';
|
||||
import {
|
||||
createEncodingTransformRuntime,
|
||||
type EncodingTransformRuntime,
|
||||
} from '@/features/browser-recording/main-world/transforms/encoding';
|
||||
import {
|
||||
createLibraryTransformRuntime,
|
||||
type LibraryTransformRuntime,
|
||||
} from '@/features/browser-recording/main-world/transforms/library-transform';
|
||||
import {
|
||||
createRecordingEvidenceRuntime,
|
||||
type RecordingEvidenceRuntime,
|
||||
} from '@/features/browser-recording/main-world/evidence';
|
||||
import {
|
||||
createRecordingTraceRuntime,
|
||||
type RecordingTraceContext,
|
||||
type RecordingTraceRuntime,
|
||||
} from '@/features/browser-recording/main-world/trace';
|
||||
import { RetainedCallBudget } from '@/features/browser-recording/main-world/retained-call-budget';
|
||||
import { estimateRetainedCallBytes } from '@/features/browser-recording/main-world/retained-value-size';
|
||||
import { ExtensionError } from '@/shared/errors';
|
||||
import type {
|
||||
BrowserPageCallableExecution,
|
||||
BrowserPageCallableExecutionPolicy,
|
||||
BrowserPageCallableTransaction,
|
||||
BrowserRecordingCrypto,
|
||||
BrowserRecordingNavigation,
|
||||
BrowserRecordingTransform,
|
||||
BrowserTransformDirection,
|
||||
BrowserTransformDirectionName,
|
||||
BrowserTransformPacket,
|
||||
} from '@/types/models';
|
||||
|
||||
type RecordingKind = 'interaction' | 'fetch' | 'xhr' | 'form' | 'beacon' | 'worker' | 'message'
|
||||
| 'websocket' | 'crypto' | 'transform' | 'navigation';
|
||||
|
||||
interface RecorderOptions {
|
||||
captureValues: boolean;
|
||||
maxEntries: number;
|
||||
maxValueBytes: number;
|
||||
expiresAt?: number;
|
||||
}
|
||||
|
||||
interface ValueEvidence {
|
||||
path: string;
|
||||
fingerprint: string;
|
||||
encoding: 'text' | 'bytes' | 'hex' | 'base64' | 'json';
|
||||
byteLength: number;
|
||||
preview?: string;
|
||||
}
|
||||
|
||||
type CallArgumentRole = 'data' | 'key' | 'iv' | 'algorithm' | 'options' | 'signature'
|
||||
| 'salt' | 'nonce' | 'aad' | 'unknown';
|
||||
|
||||
interface CallArgumentEvidence {
|
||||
index: number;
|
||||
role: CallArgumentRole;
|
||||
dataType: string;
|
||||
byteLength?: number;
|
||||
replaceable: boolean;
|
||||
retained: boolean;
|
||||
summary?: string;
|
||||
}
|
||||
|
||||
interface RecordingEvent {
|
||||
id: string;
|
||||
sequence: number;
|
||||
timestamp: number;
|
||||
durationMs?: number;
|
||||
recordingId: string;
|
||||
traceId: string;
|
||||
interactionId?: string;
|
||||
parentEventId?: string;
|
||||
kind: RecordingKind;
|
||||
source?: 'page' | 'browser';
|
||||
documentId?: string;
|
||||
operation: string;
|
||||
label?: string;
|
||||
url?: string;
|
||||
method?: string;
|
||||
crypto?: BrowserRecordingCrypto;
|
||||
transform?: BrowserRecordingTransform;
|
||||
direction?: 'send' | 'receive';
|
||||
socketId?: string;
|
||||
channelId?: string;
|
||||
byteLength?: number;
|
||||
resultByteLength?: number;
|
||||
dataType?: string;
|
||||
stack?: string;
|
||||
scriptUrl?: string;
|
||||
wrapperHandleId?: string;
|
||||
callHandleId?: string;
|
||||
callableCapable?: boolean;
|
||||
arguments?: CallArgumentEvidence[];
|
||||
inputs: ValueEvidence[];
|
||||
outputs: ValueEvidence[];
|
||||
sensitiveCaptured: boolean;
|
||||
inputPreview?: string;
|
||||
outputPreview?: string;
|
||||
error?: string;
|
||||
navigation?: BrowserRecordingNavigation;
|
||||
}
|
||||
|
||||
interface PageCallableMetadata {
|
||||
id: string;
|
||||
name: string;
|
||||
kind: 'recorded-call' | 'business-closure' | 'request-transaction' | 'global-function';
|
||||
operation: string;
|
||||
algorithm?: string;
|
||||
crypto?: BrowserRecordingCrypto;
|
||||
origin: string;
|
||||
lifecycle: 'document';
|
||||
execution: BrowserPageCallableExecutionPolicy;
|
||||
inputSlots: Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
index: number;
|
||||
role: CallArgumentRole;
|
||||
dataType: string;
|
||||
required: boolean;
|
||||
retained: boolean;
|
||||
}>;
|
||||
output: {
|
||||
dataType: string;
|
||||
encoding: 'auto' | 'utf8' | 'hex' | 'base64' | 'json';
|
||||
shape: 'value' | 'envelope';
|
||||
paths: string[];
|
||||
};
|
||||
transaction?: BrowserPageCallableTransaction;
|
||||
provenance: {
|
||||
recordingId?: string;
|
||||
traceId?: string;
|
||||
eventId?: string;
|
||||
sourceUrl?: string;
|
||||
lineNumber?: number;
|
||||
functionName?: string;
|
||||
};
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
interface PageCallableRegistryEntry {
|
||||
metadata: PageCallableMetadata;
|
||||
invoke(args: unknown[], context?: { domInputCount: number }): unknown;
|
||||
}
|
||||
|
||||
interface RecorderSnapshot {
|
||||
version: typeof PAGE_RECORDER_PROTOCOL_VERSION;
|
||||
active: boolean;
|
||||
recordingId?: string;
|
||||
startedAt?: number;
|
||||
count: number;
|
||||
droppedCount: number;
|
||||
retainedCallCount: number;
|
||||
retainedCallBytes: number;
|
||||
retainedCallDroppedCount: number;
|
||||
options?: RecorderOptions;
|
||||
events: RecordingEvent[];
|
||||
callables: PageCallableMetadata[];
|
||||
}
|
||||
|
||||
interface RecordedCallHandle {
|
||||
id: string;
|
||||
retainedBytes: number;
|
||||
kind: CallableOperationKind;
|
||||
operation: string;
|
||||
crypto: BrowserRecordingCrypto;
|
||||
original: Function;
|
||||
thisArg: unknown;
|
||||
args: unknown[];
|
||||
inputIndex: number;
|
||||
originalInput: unknown;
|
||||
eventId?: string;
|
||||
traceId?: string;
|
||||
recordingId?: string;
|
||||
sourceUrl?: string;
|
||||
outputDataType?: string;
|
||||
outputEncoding?: PageCallableMetadata['output']['encoding'];
|
||||
resultMode: 'sync' | 'promise';
|
||||
adaptInput(value: unknown): unknown;
|
||||
}
|
||||
|
||||
interface RecorderController {
|
||||
version: typeof PAGE_RECORDER_PROTOCOL_VERSION;
|
||||
command(command: string, input?: Record<string, unknown>): unknown;
|
||||
}
|
||||
|
||||
interface DeepBreakMatcher {
|
||||
wrapperHandleId: string;
|
||||
operation: string;
|
||||
scriptUrl?: string;
|
||||
}
|
||||
|
||||
type RecordingEventInput = Omit<RecordingEvent,
|
||||
'id' | 'sequence' | 'timestamp' | 'recordingId' | 'traceId' | 'interactionId' | 'parentEventId' | 'sensitiveCaptured' | 'inputs' | 'outputs'
|
||||
> & { inputs?: ValueEvidence[]; outputs?: ValueEvidence[] };
|
||||
|
||||
export default defineUnlistedScript(() => {
|
||||
const REGISTRY_KEY = PAGE_RECORDER_REGISTRY_KEY;
|
||||
const CALLABLE_REGISTRY_KEY = PAGE_CALLABLE_REGISTRY_KEY;
|
||||
const registry = window as unknown as Record<string, unknown>;
|
||||
const bridgeScript = document.currentScript;
|
||||
if (bridgeScript instanceof HTMLScriptElement) {
|
||||
const bridgeParse = JSON.parse.bind(JSON);
|
||||
const bridgeStringify = JSON.stringify.bind(JSON);
|
||||
const allowedCommands = new Set<PageRecorderBridgeCommand>([
|
||||
'start', 'resume', 'navigation.record', 'stop', 'clear', 'status', 'get',
|
||||
'callable.create', 'callable.list', 'callable.execute', 'callable.delete', 'transform.execute',
|
||||
]);
|
||||
bridgeScript.addEventListener(PAGE_RECORDER_REQUEST_EVENT, (rawEvent) => {
|
||||
if (!(rawEvent instanceof CustomEvent) || typeof rawEvent.detail !== 'string') return;
|
||||
void (async () => {
|
||||
let request: PageRecorderBridgeRequest;
|
||||
try { request = bridgeParse(rawEvent.detail) as PageRecorderBridgeRequest; } catch { return; }
|
||||
if (!request?.id || !allowedCommands.has(request.command)) return;
|
||||
let response: PageRecorderBridgeResponse;
|
||||
try {
|
||||
const activeController = registry[REGISTRY_KEY] as RecorderController | undefined;
|
||||
if (activeController?.version !== PAGE_RECORDER_PROTOCOL_VERSION || typeof activeController.command !== 'function') {
|
||||
throw new Error('页面录制器尚未就绪');
|
||||
}
|
||||
response = {
|
||||
id: request.id,
|
||||
ok: true,
|
||||
result: await Promise.resolve(activeController.command(request.command, request.input || {})),
|
||||
};
|
||||
} catch (error) {
|
||||
response = {
|
||||
id: request.id,
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
try {
|
||||
bridgeScript.dispatchEvent(new CustomEvent(PAGE_RECORDER_RESPONSE_EVENT, { detail: bridgeStringify(response) }));
|
||||
} catch (error) {
|
||||
const fallback: PageRecorderBridgeResponse = {
|
||||
id: request.id,
|
||||
ok: false,
|
||||
error: `页面录制器结果无法序列化:${error instanceof Error ? error.message : String(error)}`,
|
||||
};
|
||||
bridgeScript.dispatchEvent(new CustomEvent(PAGE_RECORDER_RESPONSE_EVENT, { detail: bridgeStringify(fallback) }));
|
||||
}
|
||||
})();
|
||||
});
|
||||
}
|
||||
const existing = registry[REGISTRY_KEY] as RecorderController | undefined;
|
||||
if (existing?.version === PAGE_RECORDER_PROTOCOL_VERSION) return;
|
||||
|
||||
const nativeStringify = JSON.stringify.bind(JSON);
|
||||
const nativeAtob = window.atob.bind(window);
|
||||
const encoder = new TextEncoder();
|
||||
const decoder = new TextDecoder();
|
||||
const restorers: Array<() => void> = [];
|
||||
const handles = new RetainedCallBudget<RecordedCallHandle>();
|
||||
const activeEventStack: string[] = [];
|
||||
let expiryTimer: number | undefined;
|
||||
let active = false;
|
||||
let recordingId: string | undefined;
|
||||
let startedAt: number | undefined;
|
||||
let uniqueSequence = 0;
|
||||
let deepBreakMatcher: DeepBreakMatcher | undefined;
|
||||
let restoreAfterDeepBreak = false;
|
||||
let options: RecorderOptions = { captureValues: false, maxEntries: 200, maxValueBytes: 2_048 };
|
||||
const evidenceRuntime: RecordingEvidenceRuntime = createRecordingEvidenceRuntime(window, () => options);
|
||||
const traceRuntime: RecordingTraceRuntime = createRecordingTraceRuntime({
|
||||
active: () => active,
|
||||
recordingId: () => recordingId,
|
||||
captureValues: () => options.captureValues,
|
||||
maxEntries: () => options.maxEntries,
|
||||
parentEventId: () => activeEventStack.at(-1),
|
||||
unique,
|
||||
});
|
||||
|
||||
function pageCallableRegistry(): Map<string, PageCallableRegistryEntry> {
|
||||
const current = registry[CALLABLE_REGISTRY_KEY];
|
||||
if (current instanceof Map) return current as Map<string, PageCallableRegistryEntry>;
|
||||
const created = new Map<string, PageCallableRegistryEntry>();
|
||||
Object.defineProperty(registry, CALLABLE_REGISTRY_KEY, {
|
||||
value: created,
|
||||
configurable: true,
|
||||
enumerable: false,
|
||||
writable: false,
|
||||
});
|
||||
return created;
|
||||
}
|
||||
|
||||
function callableMetadata(): PageCallableMetadata[] {
|
||||
return [...pageCallableRegistry().values()].slice(-128).map((entry) => entry.metadata);
|
||||
}
|
||||
|
||||
function clearRecordedCallables(): void {
|
||||
const callables = pageCallableRegistry();
|
||||
for (const [id, entry] of callables) {
|
||||
if (entry.metadata.kind === 'recorded-call') callables.delete(id);
|
||||
}
|
||||
}
|
||||
|
||||
function unique(prefix: string): string {
|
||||
uniqueSequence += 1;
|
||||
return `${prefix}-${Date.now().toString(36)}-${Math.floor(performance.now() * 1000).toString(36)}-${uniqueSequence.toString(36)}`;
|
||||
}
|
||||
|
||||
function dataType(value: unknown): string {
|
||||
return evidenceRuntime.dataType(value);
|
||||
}
|
||||
|
||||
function asBytes(value: unknown): Uint8Array | undefined {
|
||||
return evidenceRuntime.asBytes(value);
|
||||
}
|
||||
|
||||
function bytesToBase64(bytes: Uint8Array): string {
|
||||
return evidenceRuntime.bytesToBase64(bytes);
|
||||
}
|
||||
|
||||
function fingerprint(value: string): string {
|
||||
return evidenceRuntime.fingerprint(value);
|
||||
}
|
||||
|
||||
function reseedFingerprints(): void {
|
||||
evidenceRuntime.reseed();
|
||||
}
|
||||
|
||||
function collectEvidence(
|
||||
value: unknown,
|
||||
path = '$',
|
||||
depth = 0,
|
||||
output: ValueEvidence[] = [],
|
||||
parseStringContainers = true,
|
||||
): ValueEvidence[] {
|
||||
return evidenceRuntime.collect(value, path, depth, output, parseStringContainers);
|
||||
}
|
||||
|
||||
function byteLength(value: unknown): number | undefined {
|
||||
return evidenceRuntime.byteLength(value);
|
||||
}
|
||||
|
||||
function preview(value: unknown): string | undefined {
|
||||
return evidenceRuntime.preview(value);
|
||||
}
|
||||
|
||||
function stackInfo(): { stack?: string; scriptUrl?: string } {
|
||||
try {
|
||||
const stack = new Error().stack?.split('\n').slice(2, 10).join('\n').slice(0, 4_096);
|
||||
const scriptUrl = stack?.match(/https?:\/\/[^\s)]+/)?.[0]?.slice(0, 2_048);
|
||||
return { stack, scriptUrl };
|
||||
} catch { return {}; }
|
||||
}
|
||||
|
||||
function pauseForDeepCapture(wrapperHandleId: string, scriptUrl?: string): void {
|
||||
const matcher = deepBreakMatcher;
|
||||
if (!matcher || matcher.wrapperHandleId !== wrapperHandleId) return;
|
||||
if (matcher.scriptUrl && scriptUrl && !scriptUrl.startsWith(matcher.scriptUrl)) return;
|
||||
const restoreAfterResume = restoreAfterDeepBreak;
|
||||
deepBreakMatcher = undefined;
|
||||
restoreAfterDeepBreak = false;
|
||||
if (restoreAfterResume) stop();
|
||||
}
|
||||
|
||||
function deepCaptureFunction(wrapperHandleId: string): Function | undefined {
|
||||
return cryptoAdapterRuntime.wrapperFunction(wrapperHandleId)
|
||||
|| communicationBoundaryRuntime.wrapperFunction(wrapperHandleId);
|
||||
}
|
||||
|
||||
function record(input: RecordingEventInput, context?: RecordingTraceContext): RecordingEvent | undefined {
|
||||
return traceRuntime.record(input, context) as RecordingEvent | undefined;
|
||||
}
|
||||
|
||||
function observe(factory: () => RecordingEventInput, context?: RecordingTraceContext): RecordingEvent | undefined {
|
||||
return traceRuntime.observe(factory, context) as RecordingEvent | undefined;
|
||||
}
|
||||
|
||||
function bestEffort(operation: () => void): void {
|
||||
try { operation(); } catch { /* Recording must not change page behavior. */ }
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
try { return (error instanceof Error ? error.message : String(error)).slice(0, 512); } catch { return 'Unknown error'; }
|
||||
}
|
||||
|
||||
function argumentEvidence(
|
||||
index: number,
|
||||
role: CallArgumentRole,
|
||||
value: unknown,
|
||||
replaceable: boolean,
|
||||
retained: boolean,
|
||||
summary?: string,
|
||||
): CallArgumentEvidence {
|
||||
const type = dataType(value);
|
||||
const sizeEligible = ['data', 'key', 'iv', 'signature', 'salt', 'nonce', 'aad'].includes(role)
|
||||
&& type !== 'CryptoKey';
|
||||
const size = sizeEligible ? byteLength(value) : undefined;
|
||||
return {
|
||||
index,
|
||||
role,
|
||||
dataType: type.slice(0, 120),
|
||||
byteLength: size === undefined ? undefined : Math.max(0, size),
|
||||
replaceable,
|
||||
retained,
|
||||
summary: summary?.slice(0, 240),
|
||||
};
|
||||
}
|
||||
|
||||
function interactionLabel(target: EventTarget | null): string {
|
||||
if (!(target instanceof Element)) return '页面操作';
|
||||
const element = target.closest('button, a, input, select, textarea, [role]') || target;
|
||||
const text = [element.getAttribute('aria-label'), element.getAttribute('name'), element.getAttribute('title'), element.textContent]
|
||||
.find((value) => value?.trim())?.trim().replace(/\s+/g, ' ').slice(0, 120);
|
||||
return text || element.tagName.toLowerCase();
|
||||
}
|
||||
|
||||
function beginInteraction(operation: string, target: EventTarget | null): void {
|
||||
if (!active) return;
|
||||
const interactionId = unique('interaction');
|
||||
const context = { traceId: unique('trace'), interactionId };
|
||||
traceRuntime.bindContext(context);
|
||||
observe(() => ({ kind: 'interaction', operation, label: interactionLabel(target) }), context);
|
||||
}
|
||||
|
||||
function patchInteractions(): void {
|
||||
const onClick = (event: MouseEvent) => { if (event.button === 0) beginInteraction('click', event.target); };
|
||||
const onSubmit = (event: SubmitEvent) => beginInteraction('submit', event.target);
|
||||
document.addEventListener('click', onClick, true);
|
||||
document.addEventListener('submit', onSubmit, true);
|
||||
restorers.push(() => {
|
||||
document.removeEventListener('click', onClick, true);
|
||||
document.removeEventListener('submit', onSubmit, true);
|
||||
});
|
||||
}
|
||||
|
||||
function registerHandle(input: Omit<RecordedCallHandle, 'id' | 'retainedBytes'>): string | undefined {
|
||||
const id = unique('handle');
|
||||
const retainedBytes = estimateRetainedCallBytes(input.args);
|
||||
return handles.add({ id, retainedBytes, ...input }) ? id : undefined;
|
||||
}
|
||||
|
||||
function invokeCryptoAdapter(
|
||||
operation: CryptoAdapterOperation,
|
||||
original: Function,
|
||||
thisArg: unknown,
|
||||
args: unknown[],
|
||||
wrapperHandleId: string,
|
||||
installDynamic: (operations: CryptoAdapterOperation[]) => void,
|
||||
): unknown {
|
||||
const invokeOriginal = (): unknown => operation.invocationMode === 'construct'
|
||||
? Reflect.construct(original, args)
|
||||
: Reflect.apply(original, thisArg, args);
|
||||
let plan: CryptoAdapterInvocationPlan;
|
||||
try {
|
||||
plan = operation.describe(thisArg, args, cryptoAdapterToolkit);
|
||||
} catch {
|
||||
return invokeOriginal();
|
||||
}
|
||||
const started = performance.now();
|
||||
const inputIndex = plan.inputIndex;
|
||||
const callHandleId = plan.callableKind && inputIndex >= 0 ? registerHandle({
|
||||
kind: plan.callableKind,
|
||||
operation: `${plan.crypto.adapterId}.${plan.crypto.operation}`,
|
||||
crypto: plan.crypto,
|
||||
original,
|
||||
thisArg,
|
||||
args: [...args],
|
||||
inputIndex,
|
||||
originalInput: args[inputIndex],
|
||||
outputEncoding: plan.outputEncoding || plan.crypto.outputEncoding,
|
||||
resultMode: operation.resultMode,
|
||||
adaptInput: plan.adaptInput || ((value) => defaultAdaptInput(value, args[inputIndex])),
|
||||
}) : undefined;
|
||||
const item = observe(() => ({
|
||||
kind: 'crypto',
|
||||
operation: plan.crypto.operation,
|
||||
crypto: plan.crypto,
|
||||
wrapperHandleId,
|
||||
callHandleId,
|
||||
callableCapable: Boolean(callHandleId),
|
||||
arguments: plan.arguments,
|
||||
byteLength: inputIndex >= 0 ? byteLength(args[inputIndex]) : undefined,
|
||||
dataType: inputIndex >= 0 ? dataType(args[inputIndex]) : undefined,
|
||||
inputPreview: inputIndex >= 0 ? preview(args[inputIndex]) : undefined,
|
||||
inputs: inputIndex >= 0
|
||||
? plan.inputEvidence?.(args[inputIndex]) || collectEvidence(args[inputIndex], '$input')
|
||||
: [],
|
||||
...stackInfo(),
|
||||
}));
|
||||
if (item && callHandleId) {
|
||||
const handle = handles.get(callHandleId);
|
||||
if (handle) Object.assign(handle, {
|
||||
eventId: item.id,
|
||||
traceId: item.traceId,
|
||||
recordingId: item.recordingId,
|
||||
sourceUrl: item.scriptUrl,
|
||||
});
|
||||
}
|
||||
pauseForDeepCapture(wrapperHandleId, item?.scriptUrl);
|
||||
if (item) activeEventStack.push(item.id);
|
||||
const complete = (output: unknown): void => {
|
||||
if (plan.discoverResult) {
|
||||
try { installDynamic(plan.discoverResult(output)); } catch { /* Runtime session discovery is optional. */ }
|
||||
}
|
||||
if (!item) return;
|
||||
item.durationMs = Math.max(0, performance.now() - started);
|
||||
item.resultByteLength = byteLength(output);
|
||||
item.outputPreview = preview(output);
|
||||
item.outputs = plan.outputEvidence?.(output) || collectEvidence(output, '$output');
|
||||
item.error = plan.outputError?.(output) || item.error;
|
||||
const handle = callHandleId ? handles.get(callHandleId) : undefined;
|
||||
if (handle) handle.outputDataType = dataType(output);
|
||||
};
|
||||
const fail = (error: unknown): void => {
|
||||
if (item) item.error = errorMessage(error);
|
||||
};
|
||||
try {
|
||||
const output = invokeOriginal();
|
||||
if (operation.resultMode === 'promise') {
|
||||
if (item) activeEventStack.pop();
|
||||
if (output && typeof (output as { then?: unknown }).then === 'function') {
|
||||
void (output as Promise<unknown>).then(complete, fail);
|
||||
} else {
|
||||
complete(output);
|
||||
}
|
||||
} else {
|
||||
if (item) activeEventStack.pop();
|
||||
complete(output);
|
||||
}
|
||||
return output;
|
||||
} catch (error) {
|
||||
if (item) activeEventStack.pop();
|
||||
fail(error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
const cryptoAdapterToolkit: CryptoAdapterToolkit = {
|
||||
unique,
|
||||
byteLength,
|
||||
dataType,
|
||||
fingerprint,
|
||||
argument: argumentEvidence,
|
||||
collectEvidence: (value, path) => collectEvidence(value, path),
|
||||
defaultOutputEvidence: (value) => collectEvidence(value, '$output'),
|
||||
defaultAdaptInput,
|
||||
bytesForInput,
|
||||
bytesToBase64,
|
||||
};
|
||||
|
||||
const cryptoAdapterRuntime: CryptoAdapterRuntime = createCryptoAdapterRuntime(
|
||||
PAGE_CRYPTO_ADAPTERS,
|
||||
{ window, crypto: globalThis.crypto },
|
||||
cryptoAdapterToolkit,
|
||||
{
|
||||
unique,
|
||||
invoke: invokeCryptoAdapter,
|
||||
},
|
||||
);
|
||||
|
||||
const communicationBoundaryRuntime: CommunicationBoundaryRuntime = createCommunicationBoundaryRuntime(window, {
|
||||
unique,
|
||||
describe(value, path) {
|
||||
return {
|
||||
byteLength: byteLength(value),
|
||||
dataType: dataType(value),
|
||||
preview: preview(value),
|
||||
evidence: collectEvidence(value, path),
|
||||
};
|
||||
},
|
||||
stackInfo,
|
||||
emit: (input, context) => {
|
||||
if (context) traceRuntime.bindContext(context);
|
||||
return observe(() => input, context);
|
||||
},
|
||||
afterWrapperInvoke: pauseForDeepCapture,
|
||||
});
|
||||
|
||||
const networkBoundaryRuntime: NetworkBoundaryRuntime = createNetworkBoundaryRuntime(window, {
|
||||
unique,
|
||||
byteLength,
|
||||
dataType,
|
||||
asBytes,
|
||||
preview,
|
||||
collectEvidence: (value, path) => collectEvidence(value, path),
|
||||
stackInfo,
|
||||
context: () => traceRuntime.context(),
|
||||
emit: (event, context) => { observe(() => event, context); },
|
||||
});
|
||||
|
||||
const encodingTransformRuntime: EncodingTransformRuntime = createEncodingTransformRuntime(window, {
|
||||
byteLength,
|
||||
preview,
|
||||
collectEvidence: (value, path) => collectEvidence(value, path),
|
||||
stackInfo,
|
||||
emit: (event) => { observe(() => ({ kind: 'transform', ...event })); },
|
||||
});
|
||||
|
||||
const libraryTransformRuntime: LibraryTransformRuntime = createLibraryTransformRuntime(window, {
|
||||
currentTrace: () => traceRuntime.currentContext(),
|
||||
collectEvidence: (value, path) => collectEvidence(value, path),
|
||||
byteLength,
|
||||
dataType,
|
||||
preview,
|
||||
stackInfo,
|
||||
emit: (event, context) => { observe(() => ({ kind: 'transform', ...event }), context); },
|
||||
});
|
||||
|
||||
const requestPreparationRuntime: RequestPreparationRuntime = createRequestPreparationRuntime(window, {
|
||||
currentTrace: () => traceRuntime.currentContext(),
|
||||
collectEvidence: (value, path) => collectEvidence(value, path),
|
||||
byteLength,
|
||||
dataType,
|
||||
preview,
|
||||
stackInfo,
|
||||
emit: (event, context) => { observe(() => ({ kind: 'transform', ...event }), context); },
|
||||
});
|
||||
|
||||
function installObservers(): void {
|
||||
bestEffort(patchInteractions);
|
||||
cryptoAdapterRuntime.start();
|
||||
communicationBoundaryRuntime.start();
|
||||
networkBoundaryRuntime.start();
|
||||
requestPreparationRuntime.start();
|
||||
encodingTransformRuntime.start();
|
||||
libraryTransformRuntime.start();
|
||||
}
|
||||
|
||||
function stop(): void {
|
||||
active = false;
|
||||
if (expiryTimer !== undefined) window.clearTimeout(expiryTimer);
|
||||
expiryTimer = undefined;
|
||||
cryptoAdapterRuntime.stop();
|
||||
communicationBoundaryRuntime.stop();
|
||||
networkBoundaryRuntime.stop();
|
||||
requestPreparationRuntime.stop();
|
||||
encodingTransformRuntime.stop();
|
||||
libraryTransformRuntime.stop();
|
||||
while (restorers.length) bestEffort(restorers.pop()!);
|
||||
activeEventStack.length = 0;
|
||||
traceRuntime.releaseContext();
|
||||
deepBreakMatcher = undefined;
|
||||
restoreAfterDeepBreak = false;
|
||||
}
|
||||
|
||||
function resumeRecording(): void {
|
||||
if (active || !startedAt) return;
|
||||
active = true;
|
||||
installObservers();
|
||||
if (options.expiresAt) expiryTimer = window.setTimeout(stop, Math.max(0, options.expiresAt - Date.now()));
|
||||
}
|
||||
|
||||
function snapshot(limit = options.maxEntries): RecorderSnapshot {
|
||||
const trace = traceRuntime.snapshot(limit);
|
||||
return {
|
||||
version: PAGE_RECORDER_PROTOCOL_VERSION,
|
||||
active,
|
||||
recordingId,
|
||||
startedAt,
|
||||
count: trace.count,
|
||||
droppedCount: trace.droppedCount,
|
||||
retainedCallCount: handles.size,
|
||||
retainedCallBytes: handles.retainedBytes,
|
||||
retainedCallDroppedCount: handles.droppedCount,
|
||||
options: startedAt ? { ...options } : undefined,
|
||||
events: trace.events as RecordingEvent[],
|
||||
callables: callableMetadata(),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizedBytes(value: unknown): Uint8Array | undefined {
|
||||
const direct = asBytes(value);
|
||||
if (direct) return direct;
|
||||
if (!value || typeof value !== 'object') return undefined;
|
||||
const record = value as Record<string, unknown>;
|
||||
if (record.type !== 'bytes' || typeof record.base64 !== 'string') return undefined;
|
||||
const binary = nativeAtob(record.base64);
|
||||
return Uint8Array.from(binary, (character) => character.charCodeAt(0));
|
||||
}
|
||||
|
||||
function bytesForInput(value: unknown): Uint8Array | undefined {
|
||||
return normalizedBytes(value) || (typeof value === 'string' ? encoder.encode(value) : undefined);
|
||||
}
|
||||
|
||||
function defaultAdaptInput(value: unknown, originalInput: unknown): unknown {
|
||||
if (typeof originalInput === 'string') {
|
||||
const bytes = normalizedBytes(value);
|
||||
return bytes ? decoder.decode(bytes) : typeof value === 'string' ? value : nativeStringify(value);
|
||||
}
|
||||
const bytes = bytesForInput(value);
|
||||
if (!bytes) return value;
|
||||
if (originalInput instanceof ArrayBuffer) return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
|
||||
if (ArrayBuffer.isView(originalInput)) return bytes;
|
||||
return value;
|
||||
}
|
||||
|
||||
function createRecordedCallable(handle: RecordedCallHandle, name: string): PageCallableMetadata {
|
||||
const id = unique('callable');
|
||||
const metadata: PageCallableMetadata = {
|
||||
id,
|
||||
name: name.trim().slice(0, 120) || handle.operation,
|
||||
kind: 'recorded-call',
|
||||
operation: handle.operation,
|
||||
algorithm: handle.crypto.algorithm,
|
||||
crypto: handle.crypto,
|
||||
origin: location.origin,
|
||||
lifecycle: 'document',
|
||||
execution: callableExecutionPolicy(handle.resultMode),
|
||||
inputSlots: [{
|
||||
id: 'data',
|
||||
name: 'data',
|
||||
index: 0,
|
||||
role: 'data',
|
||||
dataType: dataType(handle.originalInput),
|
||||
required: true,
|
||||
retained: false,
|
||||
}],
|
||||
output: {
|
||||
dataType: handle.outputDataType || 'unknown',
|
||||
encoding: handle.outputEncoding || 'auto',
|
||||
shape: 'value',
|
||||
paths: [],
|
||||
},
|
||||
provenance: {
|
||||
recordingId: handle.recordingId,
|
||||
traceId: handle.traceId,
|
||||
eventId: handle.eventId,
|
||||
sourceUrl: handle.sourceUrl,
|
||||
functionName: handle.original.name || undefined,
|
||||
},
|
||||
createdAt: Date.now(),
|
||||
};
|
||||
pageCallableRegistry().set(id, {
|
||||
metadata,
|
||||
invoke(values) {
|
||||
if (!values.length) throw new Error('页面函数缺少 data 参数');
|
||||
const args = [...handle.args];
|
||||
args[handle.inputIndex] = handle.adaptInput(values[0]);
|
||||
return Reflect.apply(handle.original, handle.thisArg, args);
|
||||
},
|
||||
});
|
||||
return metadata;
|
||||
}
|
||||
|
||||
async function executePageCallable(callableId: string, values: unknown[]): Promise<unknown> {
|
||||
const entry = pageCallableRegistry().get(callableId);
|
||||
if (!entry) throw new Error('页面函数已经失效,页面可能已经刷新');
|
||||
const started = performance.now();
|
||||
const result = entry.metadata.kind === 'request-transaction'
|
||||
? await executeRequestTransaction({
|
||||
transaction: entry.metadata.transaction || (() => { throw new Error('请求事务缺少边界配置'); })(),
|
||||
logicalInput: values[0],
|
||||
invoke: (context) => entry.invoke(values, context),
|
||||
timeoutMs: entry.metadata.execution.timeoutMs,
|
||||
})
|
||||
: entry.metadata.kind === 'business-closure' || entry.metadata.kind === 'global-function'
|
||||
? await executeSideEffectFreeCallable(() => entry.invoke(values), entry.metadata.execution)
|
||||
: await settleCallableResult(entry.invoke(values), entry.metadata.execution);
|
||||
const seen = new WeakSet<object>();
|
||||
let nodes = 0;
|
||||
const maxBytes = 8 * 1024 * 1024;
|
||||
const normalize = (value: unknown, depth = 0): unknown => {
|
||||
nodes += 1;
|
||||
if (nodes > 100_000) throw new Error('页面函数结果包含过多节点');
|
||||
if (value === null || value === undefined || typeof value === 'boolean' || typeof value === 'number') return value;
|
||||
if (typeof value === 'string') {
|
||||
if (encoder.encode(value).byteLength > maxBytes) throw new Error('页面函数字符串结果超过 8 MiB');
|
||||
return value;
|
||||
}
|
||||
if (typeof value === 'bigint') return value.toString();
|
||||
if (typeof value === 'function' || typeof value === 'symbol') throw new Error(`页面函数返回了不可序列化的 ${typeof value}`);
|
||||
if (depth >= 32) throw new Error('页面函数结果嵌套超过 32 层');
|
||||
const bytes = asBytes(value);
|
||||
if (bytes) {
|
||||
if (bytes.byteLength > maxBytes) throw new Error('页面函数字节结果超过 8 MiB');
|
||||
return { type: 'bytes', byteLength: bytes.byteLength, base64: bytesToBase64(bytes) };
|
||||
}
|
||||
if (value instanceof Date) return value.toISOString();
|
||||
if (value instanceof URLSearchParams) return value.toString();
|
||||
if (typeof Response !== 'undefined' && value instanceof Response) {
|
||||
return { type: 'Response', status: value.status, statusText: value.statusText, url: value.url, headers: Object.fromEntries(value.headers) };
|
||||
}
|
||||
if (value && typeof value === 'object') {
|
||||
const cryptoValue = value as { sigBytes?: unknown; ciphertext?: unknown; toString?: unknown };
|
||||
if ((typeof cryptoValue.sigBytes === 'number' || cryptoValue.ciphertext) && typeof cryptoValue.toString === 'function') {
|
||||
const text = Reflect.apply(cryptoValue.toString as Function, value, []);
|
||||
if (typeof text === 'string' && text !== '[object Object]') return text;
|
||||
}
|
||||
if (seen.has(value)) throw new Error('页面函数结果包含循环引用');
|
||||
seen.add(value);
|
||||
try {
|
||||
if (Array.isArray(value)) return value.map((item) => normalize(item, depth + 1));
|
||||
const output: Record<string, unknown> = {};
|
||||
for (const [key, item] of Object.entries(value as Record<string, unknown>)) output[key] = normalize(item, depth + 1);
|
||||
return output;
|
||||
} finally {
|
||||
seen.delete(value);
|
||||
}
|
||||
}
|
||||
throw new Error(`页面函数返回了不可序列化的 ${typeof value}`);
|
||||
};
|
||||
const value = normalize(result);
|
||||
let preview: string;
|
||||
try { preview = typeof value === 'string' ? value : nativeStringify(value); } catch { preview = String(value); }
|
||||
return {
|
||||
callableId,
|
||||
type: dataType(result).toLowerCase(),
|
||||
preview: preview.slice(0, 8_192),
|
||||
value,
|
||||
byteLength: encoder.encode(preview).byteLength,
|
||||
durationMs: Math.max(0, performance.now() - started),
|
||||
};
|
||||
}
|
||||
|
||||
const controller: RecorderController = {
|
||||
version: PAGE_RECORDER_PROTOCOL_VERSION,
|
||||
command(command, input = {}) {
|
||||
if (command === 'start') {
|
||||
stop();
|
||||
options = {
|
||||
captureValues: input.captureValues === true,
|
||||
maxEntries: Math.max(20, Math.min(Number(input.maxEntries) || 200, 500)),
|
||||
maxValueBytes: Math.max(256, Math.min(Number(input.maxValueBytes) || 2_048, 8_192)),
|
||||
expiresAt: typeof input.expiresAt === 'number' ? input.expiresAt : undefined,
|
||||
};
|
||||
handles.clear();
|
||||
clearRecordedCallables();
|
||||
traceRuntime.reset(Number.isSafeInteger(input.sequenceStart) && Number(input.sequenceStart) >= 0
|
||||
? Number(input.sequenceStart)
|
||||
: 0);
|
||||
recordingId = typeof input.recordingId === 'string' && input.recordingId.trim()
|
||||
? input.recordingId.trim().slice(0, 160)
|
||||
: unique('recording');
|
||||
startedAt = typeof input.startedAt === 'number' && Number.isFinite(input.startedAt)
|
||||
? input.startedAt
|
||||
: Date.now();
|
||||
reseedFingerprints();
|
||||
active = true;
|
||||
installObservers();
|
||||
if (options.expiresAt) expiryTimer = window.setTimeout(stop, Math.max(0, options.expiresAt - Date.now()));
|
||||
return snapshot();
|
||||
}
|
||||
if (command === 'resume') {
|
||||
if (Number.isSafeInteger(input.sequenceStart)) traceRuntime.advanceSequenceStart(Number(input.sequenceStart));
|
||||
resumeRecording();
|
||||
return snapshot();
|
||||
}
|
||||
if (command === 'navigation.record') {
|
||||
const navigation = input.navigation as BrowserRecordingNavigation | undefined;
|
||||
if (!navigation || typeof navigation.toUrl !== 'string') throw new Error('页面跳转事件无效');
|
||||
record({
|
||||
kind: 'navigation',
|
||||
source: 'browser',
|
||||
documentId: typeof input.documentId === 'string' ? input.documentId.slice(0, 160) : undefined,
|
||||
operation: String(input.operation || 'navigate').slice(0, 160),
|
||||
label: String(input.label || '页面跳转').slice(0, 240),
|
||||
url: navigation.toUrl.slice(0, 8_192),
|
||||
navigation,
|
||||
});
|
||||
return snapshot();
|
||||
}
|
||||
if (command === 'stop') { stop(); return snapshot(); }
|
||||
if (command === 'deep.arm') {
|
||||
if (!startedAt) throw new Error('请先录制一次页面操作,再进入深度捕获');
|
||||
restoreAfterDeepBreak = !active;
|
||||
resumeRecording();
|
||||
const matcherKind = input.kind === 'boundary' ? 'boundary' : 'crypto';
|
||||
const adapterId = String(input.adapterId || '').trim().slice(0, 64);
|
||||
const eventKind = String(input.eventKind || '').trim().slice(0, 32);
|
||||
const operation = String(input.operation || '').trim().slice(0, 240);
|
||||
const wrapperHandleId = String(input.wrapperHandleId || '').trim().slice(0, 160);
|
||||
if (!operation || !wrapperHandleId || (matcherKind === 'crypto' ? !adapterId : !['beacon', 'worker', 'message'].includes(eventKind))) {
|
||||
throw new Error('深度捕获目标、操作或函数句柄不完整');
|
||||
}
|
||||
if (!deepCaptureFunction(wrapperHandleId)) {
|
||||
const shouldRestore = restoreAfterDeepBreak;
|
||||
restoreAfterDeepBreak = false;
|
||||
if (shouldRestore) stop();
|
||||
throw new Error('目标密码函数已经失效,请重新录制一次当前页面操作');
|
||||
}
|
||||
deepBreakMatcher = {
|
||||
wrapperHandleId,
|
||||
operation,
|
||||
scriptUrl: typeof input.scriptUrl === 'string' ? input.scriptUrl.slice(0, 2_048) : undefined,
|
||||
};
|
||||
return { armed: true, kind: matcherKind, adapterId: adapterId || undefined, eventKind: eventKind || undefined, operation, wrapperHandleId };
|
||||
}
|
||||
if (command === 'deep.function') return deepCaptureFunction(String(input.wrapperHandleId || ''));
|
||||
if (command === 'deep.disarm') {
|
||||
const shouldRestore = restoreAfterDeepBreak;
|
||||
deepBreakMatcher = undefined;
|
||||
restoreAfterDeepBreak = false;
|
||||
if (shouldRestore) stop();
|
||||
return { armed: false };
|
||||
}
|
||||
if (command === 'clear') {
|
||||
stop();
|
||||
traceRuntime.reset();
|
||||
handles.clear();
|
||||
clearRecordedCallables();
|
||||
recordingId = undefined;
|
||||
startedAt = undefined;
|
||||
return snapshot();
|
||||
}
|
||||
if (command === 'status' || command === 'get') return snapshot(typeof input.limit === 'number' ? input.limit : options.maxEntries);
|
||||
if (command === 'callable.create') {
|
||||
const callHandleId = String(input.callHandleId || '');
|
||||
const handle = handles.get(callHandleId);
|
||||
if (!handle) throw new Error('加解密调用句柄不存在或已经失效');
|
||||
return createRecordedCallable(handle, String(input.name || handle.operation));
|
||||
}
|
||||
if (command === 'callable.list') return callableMetadata();
|
||||
if (command === 'callable.execute') {
|
||||
return executePageCallable(String(input.callableId || ''), Array.isArray(input.args) ? input.args : []);
|
||||
}
|
||||
if (command === 'callable.delete') {
|
||||
pageCallableRegistry().delete(String(input.callableId || ''));
|
||||
return callableMetadata();
|
||||
}
|
||||
if (command === 'transform.execute') {
|
||||
const directionName = String(input.directionName) as BrowserTransformDirectionName;
|
||||
return executeTransformDirection(
|
||||
String(input.profileId || ''),
|
||||
directionName,
|
||||
input.direction as unknown as BrowserTransformDirection,
|
||||
input.packet as unknown as BrowserTransformPacket,
|
||||
async (callableId, args) => await executePageCallable(callableId, args) as BrowserPageCallableExecution,
|
||||
).then(
|
||||
(value) => ({ ok: true, value }),
|
||||
(error: unknown) => ({
|
||||
ok: false,
|
||||
error: {
|
||||
code: error instanceof ExtensionError ? error.code : 'transform_page_execution_failed',
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
throw new Error(`不支持的录制命令: ${command}`);
|
||||
},
|
||||
};
|
||||
|
||||
Object.defineProperty(registry, REGISTRY_KEY, { value: controller, configurable: true, enumerable: false, writable: false });
|
||||
});
|
||||
@@ -0,0 +1,214 @@
|
||||
.popup-shell { position: relative; width: 390px; height: 600px; min-height: 600px; display: flex; flex-direction: column; overflow: hidden; background: var(--surface); }
|
||||
|
||||
/* Header */
|
||||
.popup-header { padding: 9px 13px; border-bottom: 1px solid var(--border); color: var(--foreground); background: var(--surface); }
|
||||
.popup-header-main { min-height: 42px; display: grid; grid-template-columns: 32px minmax(0, 1fr) auto; align-items: center; gap: 10px; }
|
||||
.popup-brand-mark { width: 32px; height: 32px; padding: 1px; display: grid; place-items: center; border-radius: 9px; background: transparent; cursor: help; }
|
||||
.popup-brand-mark:hover, .popup-brand-mark:focus-visible { background: var(--surface-subtle); outline: none; }
|
||||
.popup-brand-mark .yak-mark { width: 28px; height: 28px; object-fit: contain; }
|
||||
.popup-target { min-width: 0; display: grid; gap: 1px; }
|
||||
.popup-target-title { min-width: 0; display: flex; align-items: center; gap: 6px; }
|
||||
.popup-target-title strong { min-width: 0; overflow: hidden; font-size: var(--text-sm); line-height: 17px; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.popup-target-host { overflow: hidden; color: var(--muted); font-size: var(--text-xs); line-height: 14px; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.popup-brand-actions { display: flex; align-items: center; gap: 3px; }
|
||||
.popup-brand-actions .ui-button { color: var(--muted-strong); }
|
||||
.popup-brand-actions .ui-button:hover { background: var(--surface-subtle); color: var(--foreground); }
|
||||
.popup-engine-status { height: 26px; padding: 0 9px; display: inline-flex; align-items: center; gap: 6px; border: 1px solid var(--border); border-radius: 999px; background: var(--surface-subtle); color: var(--muted-strong); font-size: var(--text-xs); font-weight: 600; white-space: nowrap; cursor: pointer; transition: background-color .15s ease, border-color .15s ease, box-shadow .15s ease; }
|
||||
.popup-engine-status:hover { background: var(--border); }
|
||||
.popup-engine-status:focus-visible { outline: none; box-shadow: 0 0 0 3px var(--focus); }
|
||||
.popup-engine-status:disabled { opacity: .6; cursor: not-allowed; }
|
||||
.popup-engine-status i { width: 7px; height: 7px; border-radius: 50%; background: var(--muted); }
|
||||
.popup-engine-status.connected { border-color: color-mix(in srgb, var(--success) 40%, var(--surface)); background: var(--success-soft); color: var(--success); }
|
||||
.popup-engine-status.connected i { background: var(--success); }
|
||||
.popup-engine-status.connecting i, .popup-engine-status.negotiating i { background: var(--warning); animation: pulse 1.3s infinite; }
|
||||
.popup-engine-status.error { border-color: color-mix(in srgb, var(--danger) 35%, var(--surface)); background: var(--danger-soft); color: var(--danger); }
|
||||
.popup-engine-status.error i { background: var(--danger); }
|
||||
.popup-favicon { width: 16px; height: 16px; flex: 0 0 auto; display: grid; place-items: center; color: var(--muted); }
|
||||
.popup-favicon img { width: 16px; height: 16px; object-fit: contain; }
|
||||
|
||||
/* Icon rail and workspace */
|
||||
.popup-body { min-height: 0; flex: 1; display: grid; grid-template-columns: 50px minmax(0, 1fr); background: var(--background); }
|
||||
.popup-rail { min-height: 0; padding: 9px 7px; display: flex; flex-direction: column; justify-content: space-between; border-right: 1px solid var(--border); background: var(--surface-subtle); }
|
||||
.popup-rail-main, .popup-rail-bottom { display: grid; justify-items: center; gap: 6px; }
|
||||
.popup-rail-bottom { padding-top: 9px; border-top: 1px solid var(--border); }
|
||||
.popup-rail button { width: 36px; height: 36px; padding: 0; display: grid; place-items: center; border: 1px solid transparent; border-radius: 9px; background: transparent; color: var(--muted-strong); cursor: pointer; transition: background-color .14s ease, border-color .14s ease, color .14s ease, box-shadow .14s ease; }
|
||||
.popup-rail button:hover { background: var(--border); color: var(--foreground); }
|
||||
.popup-rail button:focus-visible { outline: none; box-shadow: 0 0 0 3px var(--focus); }
|
||||
.popup-rail button.is-active { border-color: color-mix(in srgb, var(--primary) 25%, var(--border)); background: var(--surface); color: var(--primary-strong); box-shadow: var(--shadow-sm); }
|
||||
.popup-workspace { min-width: 0; min-height: 0; display: flex; flex-direction: column; overflow: hidden; background: var(--background); }
|
||||
.popup-overview-view { min-height: 0; flex: 1; display: flex; flex-direction: column; overflow: hidden; }
|
||||
.popup-overview-lead { padding: 7px 15px; border-bottom: 1px solid var(--border); background: var(--surface); }
|
||||
.popup-overview-lead__meta { display: flex; align-items: center; justify-content: space-between; gap: 10px; font-size: var(--text-xs); line-height: 16px; }
|
||||
.popup-overview-lead__meta > span { overflow: hidden; color: var(--muted); white-space: nowrap; text-overflow: ellipsis; }
|
||||
.popup-overview-lead__meta strong { display: inline-flex; align-items: center; gap: 5px; color: var(--success); font-weight: 600; white-space: nowrap; }
|
||||
.popup-overview-lead__meta strong.is-unavailable { color: var(--muted-strong); }
|
||||
.popup-overview-lead__meta i { width: 6px; height: 6px; border-radius: 50%; background: currentColor; }
|
||||
.popup-overview-summary { min-height: 0; flex: 1; padding: 0 12px; overflow-y: auto; scrollbar-width: thin; background: var(--surface); }
|
||||
.popup-overview-summary > button { width: 100%; min-height: 55px; padding: 8px 2px; display: grid; grid-template-columns: 28px minmax(0, 1fr) 16px; align-items: center; gap: 9px; border: 0; border-bottom: 1px solid var(--border); background: transparent; color: var(--foreground); text-align: left; cursor: pointer; transition: background-color .14s ease, padding-left .14s ease; }
|
||||
.popup-overview-summary > button:hover { padding-left: 5px; background: var(--surface-subtle); }
|
||||
.popup-overview-summary > button:focus-visible { outline: none; box-shadow: 0 0 0 3px var(--focus); }
|
||||
.popup-overview-summary > button > span:nth-child(2) { min-width: 0; display: grid; gap: 2px; }
|
||||
.popup-overview-summary small, .popup-overview-summary strong { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.popup-overview-summary small { color: var(--muted); font-size: var(--text-xs); line-height: 14px; }
|
||||
.popup-overview-summary strong { font-size: var(--text-sm); line-height: 17px; }
|
||||
.popup-overview-summary > button > svg { color: var(--muted); }
|
||||
.popup-overview-icon { width: 27px; height: 27px; display: grid; place-items: center; border: 1px solid var(--border); border-radius: 8px; background: var(--surface); color: var(--muted-strong); }
|
||||
.popup-overview-summary > button:hover .popup-overview-icon { background: var(--primary-soft); color: var(--primary); }
|
||||
|
||||
/* 人工接管 —— 内嵌警告卡 */
|
||||
.popup-handoff { margin: 10px 12px; display: grid; grid-template-columns: 20px minmax(0, 1fr); gap: 8px 10px; align-items: start; padding: 12px 14px 12px 13px; border-left: 3px solid var(--warning); border-radius: var(--radius-md); background: var(--warning-soft); }
|
||||
.popup-handoff > svg { margin-top: 1px; color: var(--warning); }
|
||||
.popup-handoff__copy { min-width: 0; }
|
||||
.popup-handoff__copy strong, .popup-handoff__copy span, .popup-handoff__copy small { display: block; }
|
||||
.popup-handoff__copy strong { font-size: var(--text-md); font-weight: 600; line-height: 18px; }
|
||||
.popup-handoff__copy span { margin-top: 3px; font-size: var(--text-sm); line-height: 16px; overflow-wrap: anywhere; }
|
||||
.popup-handoff__copy small { margin-top: 4px; overflow: hidden; color: var(--muted); font-size: var(--text-sm); line-height: 16px; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.popup-handoff__actions { grid-column: 2; display: flex; gap: 6px; align-items: center; }
|
||||
.popup-handoff__actions .ui-button { white-space: nowrap; }
|
||||
.popup-handoff__actions .ui-button--icon { width: 30px; height: 30px; }
|
||||
|
||||
/* 共享会话 */
|
||||
.popup-share { padding: 12px 16px; display: flex; align-items: center; justify-content: space-between; gap: 14px; border-bottom: 1px solid var(--border); transition: background-color .16s ease; }
|
||||
.popup-share.is-active { background: var(--success-soft); }
|
||||
.popup-share-copy { min-width: 0; display: flex; align-items: flex-start; gap: 10px; }
|
||||
.popup-share-copy > svg { width: 18px; height: 18px; margin-top: 1px; flex: 0 0 auto; color: var(--muted-strong); }
|
||||
.popup-share.is-active .popup-share-copy > svg { color: var(--success); }
|
||||
.popup-share-copy strong, .popup-share-copy span { display: block; }
|
||||
.popup-share-copy strong { font-size: var(--text-md); font-weight: 600; line-height: 18px; }
|
||||
.popup-share-copy span { margin-top: 2px; color: var(--muted); font-size: var(--text-sm); line-height: 16px; }
|
||||
.popup-share.is-active .popup-share-copy span { color: var(--success); }
|
||||
|
||||
/* 代理:站点路由与全局模式 */
|
||||
.popup-proxy-view { min-height: 0; }
|
||||
.popup-site-router { padding: 10px 12px 9px; display: grid; gap: 7px; border-bottom: 1px solid var(--border); background: var(--surface); }
|
||||
.popup-site-router__heading { min-width: 0; display: flex; align-items: center; justify-content: space-between; gap: 10px; }
|
||||
.popup-site-router__heading > div { min-width: 0; display: flex; align-items: center; gap: 8px; }
|
||||
.popup-site-router__heading > div > svg { flex: 0 0 auto; color: var(--primary); }
|
||||
.popup-site-router__heading span { min-width: 0; }
|
||||
.popup-site-router__heading small, .popup-site-router__heading strong { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.popup-site-router__heading small { color: var(--muted); font-size: var(--text-xs); line-height: 13px; }
|
||||
.popup-site-router__heading strong { max-width: 215px; margin-top: 1px; font-size: var(--text-sm); line-height: 17px; }
|
||||
.popup-site-router__heading > i { flex: 0 0 auto; padding: 2px 6px; border-radius: 4px; background: var(--surface-subtle); color: var(--muted-strong); font-size: var(--text-xs); font-style: normal; font-weight: 600; }
|
||||
.popup-site-router__heading > i.manual { background: var(--primary-soft); color: var(--primary-text); }
|
||||
.popup-site-router__heading > i.source { background: var(--success-soft); color: var(--success); }
|
||||
.popup-site-router__heading > i.global { background: var(--warning-soft); color: var(--warning); }
|
||||
.popup-site-decision { min-width: 0; min-height: 27px; padding: 5px 8px; display: grid; grid-template-columns: minmax(0, 1fr) 12px minmax(0, .8fr); align-items: center; gap: 5px; border-left: 2px solid var(--primary); background: var(--surface-subtle); }
|
||||
.popup-site-decision span, .popup-site-decision strong { overflow: hidden; font-size: var(--text-xs); text-overflow: ellipsis; white-space: nowrap; }
|
||||
.popup-site-decision span { color: var(--muted-strong); }
|
||||
.popup-site-decision i { color: var(--muted); font-size: var(--text-xs); font-style: normal; text-align: center; }
|
||||
.popup-site-decision strong { color: var(--foreground); }
|
||||
.popup-site-picker { display: grid; gap: 5px; }
|
||||
.popup-site-picker > label { display: flex; align-items: center; justify-content: space-between; gap: 8px; color: var(--muted-strong); font-size: var(--text-xs); font-weight: 600; }
|
||||
.popup-site-picker > label span { color: var(--muted); font-weight: 400; }
|
||||
.popup-site-picker select { min-width: 0; height: 32px; padding: 0 9px; font-size: var(--text-xs); }
|
||||
.popup-site-status { min-width: 0; height: 15px; display: flex; align-items: center; gap: 5px; color: var(--muted); }
|
||||
.popup-site-status svg { flex: 0 0 auto; }
|
||||
.popup-site-status small { overflow: hidden; font-size: var(--text-xs); line-height: 15px; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.popup-site-status.is-applying { color: var(--primary-text); }
|
||||
.popup-site-status.is-success { color: var(--success); }
|
||||
.popup-site-status.is-error { color: var(--danger); }
|
||||
.popup-proxy-unavailable { min-height: 118px; padding: 18px 14px; display: flex; align-items: center; justify-content: center; gap: 9px; border-bottom: 1px solid var(--border); color: var(--muted); text-align: left; }
|
||||
.popup-proxy-unavailable strong, .popup-proxy-unavailable small { display: block; }
|
||||
.popup-proxy-unavailable strong { color: var(--foreground); font-size: var(--text-sm); }
|
||||
.popup-proxy-unavailable small { margin-top: 2px; font-size: var(--text-xs); }
|
||||
.popup-mode-heading { min-height: 39px; padding: 6px 12px; display: flex; align-items: center; justify-content: space-between; gap: 10px; border-bottom: 1px solid var(--border); background: var(--surface-subtle); }
|
||||
.popup-mode-heading > span { min-width: 0; }
|
||||
.popup-mode-heading strong, .popup-mode-heading small { display: block; }
|
||||
.popup-mode-heading strong { font-size: var(--text-sm); line-height: 16px; }
|
||||
.popup-mode-heading small { margin-top: 1px; color: var(--muted); font-size: var(--text-xs); line-height: 13px; }
|
||||
.popup-mode-heading > i { max-width: 110px; overflow: hidden; color: var(--muted-strong); font-size: var(--text-xs); font-style: normal; font-weight: 600; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.popup-proxy-list { overflow-y: auto; display: grid; align-content: start; gap: 2px; scrollbar-width: thin; }
|
||||
.popup-proxy-list--view { min-height: 0; flex: 1; padding: 5px 8px; background: var(--surface); }
|
||||
.popup-proxy-list > button { width: 100%; min-height: 43px; padding: 5px 8px; display: grid; grid-template-columns: 28px minmax(0, 1fr) auto; align-items: center; gap: 8px; border: 1px solid transparent; border-radius: var(--radius-md); background: transparent; color: var(--foreground); text-align: left; cursor: pointer; transition: background-color .13s ease, border-color .13s ease, color .13s ease; }
|
||||
.popup-proxy-list > button:hover { background: var(--surface-subtle); }
|
||||
.popup-proxy-list > button:focus-visible { outline: none; box-shadow: 0 0 0 3px var(--focus); }
|
||||
.popup-proxy-list > button.is-active { border-color: color-mix(in srgb, var(--primary) 20%, var(--border)); background: var(--primary-soft); }
|
||||
.popup-proxy-list > button.is-active strong { color: var(--primary-text); }
|
||||
.popup-proxy-list > button > span:nth-child(2) { min-width: 0; }
|
||||
.popup-proxy-list strong, .popup-proxy-list small { display: block; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.popup-proxy-list strong { font-size: var(--text-sm); font-weight: 600; line-height: 16px; }
|
||||
.popup-proxy-list small { margin-top: 1px; color: var(--muted); font-size: var(--text-xs); line-height: 14px; }
|
||||
.popup-proxy-list > button > svg { color: var(--primary); }
|
||||
.popup-mode-icon { width: 28px; height: 28px; display: grid; place-items: center; border: 1px solid var(--border); border-radius: 7px; background: var(--surface); color: var(--muted-strong); }
|
||||
.popup-proxy-list > button.is-active .popup-mode-icon { border-color: color-mix(in srgb, var(--primary) 28%, var(--border)); color: var(--primary); }
|
||||
.popup-proxy-list em { padding: 2px 5px; border-radius: 4px; background: var(--warning-soft); color: var(--warning); font-size: var(--text-xs); font-style: normal; white-space: nowrap; }
|
||||
.popup-proxy-view .popup-tool-footer > button { color: var(--primary-text); }
|
||||
|
||||
/* 专注子页面 */
|
||||
.popup-view { min-height: 0; flex: 1; color: var(--foreground); }
|
||||
.popup-tool-view { display: flex; flex-direction: column; overflow: hidden; animation: popup-view-in .16s ease-out; }
|
||||
.popup-tool-context { min-height: 34px; padding: 0 14px; display: grid; grid-template-columns: 16px minmax(0, 1fr) auto; align-items: center; gap: 7px; border-bottom: 1px solid var(--border); background: var(--surface-subtle); color: var(--muted-strong); font-size: var(--text-xs); }
|
||||
.popup-tool-context span { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.popup-tool-context strong { padding: 2px 7px; border-radius: 999px; background: var(--surface-subtle); color: var(--foreground); font-size: var(--text-xs); }
|
||||
.popup-view-enter { animation: popup-content-in .16s ease-out; }
|
||||
.popup-tool-toolbar { min-height: 46px; padding: 7px 12px; display: flex; align-items: center; gap: 7px; border-bottom: 1px solid var(--border); background: var(--surface); }
|
||||
.popup-tool-toolbar > label { min-width: 0; flex: 1; height: 32px; padding: 0 9px; display: flex; align-items: center; gap: 7px; border: 1px solid var(--border); border-radius: var(--radius-md); background: var(--background); color: var(--muted); }
|
||||
.popup-tool-toolbar input { min-width: 0; flex: 1; border: 0; background: transparent; color: var(--foreground); outline: 0; font-size: var(--text-sm); }
|
||||
.popup-tool-empty { min-height: 150px; padding: 24px; display: grid; place-items: center; color: var(--muted); font-size: var(--text-sm); text-align: center; }
|
||||
.popup-tool-footer { min-height: 38px; padding: 6px 14px; display: flex; align-items: center; justify-content: space-between; gap: 10px; border-top: 1px solid var(--border); color: var(--muted); font-size: var(--text-xs); }
|
||||
.popup-tool-footer > button { display: inline-flex; align-items: center; gap: 5px; border: 0; background: transparent; color: var(--danger); font-size: var(--text-xs); cursor: pointer; }
|
||||
.popup-tool-footer > button:disabled { opacity: .45; cursor: not-allowed; }
|
||||
|
||||
/* Popup Cookie Editor */
|
||||
.popup-cookie-list { min-height: 0; flex: 1; overflow-y: auto; background: var(--surface); scrollbar-width: thin; }
|
||||
.popup-cookie-row { min-height: 70px; padding: 9px 10px 8px 14px; display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 5px 8px; border-bottom: 1px solid var(--border); transition: background-color .13s ease; }
|
||||
.popup-cookie-row:hover { background: var(--surface-subtle); }
|
||||
.popup-cookie-main { min-width: 0; padding: 0; display: grid; gap: 2px; border: 0; background: transparent; color: var(--foreground); text-align: left; cursor: pointer; }
|
||||
.popup-cookie-main > span { min-width: 0; display: flex; align-items: center; gap: 6px; }
|
||||
.popup-cookie-main strong { overflow: hidden; font-size: var(--text-sm); text-overflow: ellipsis; white-space: nowrap; }
|
||||
.popup-cookie-main > span i { padding: 1px 5px; border-radius: 999px; background: var(--surface-subtle); color: var(--muted-strong); font-size: var(--text-xs); font-style: normal; }
|
||||
.popup-cookie-main code, .popup-cookie-main small { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.popup-cookie-main code { color: var(--muted-strong); font-size: var(--text-xs); }
|
||||
.popup-cookie-main small { color: var(--muted); font-size: var(--text-xs); }
|
||||
.popup-cookie-meta { min-height: 15px; display: flex; align-items: center; gap: 4px; }
|
||||
.popup-cookie-meta i { padding: 1px 4px; border-radius: 3px; background: var(--surface-subtle); color: var(--muted); font-size: var(--text-xs); font-style: normal; }
|
||||
.popup-cookie-actions { grid-column: 2; grid-row: 1 / 3; display: flex; align-items: center; }
|
||||
.popup-cookie-actions button { width: 28px; height: 28px; display: grid; place-items: center; border: 0; border-radius: 5px; background: transparent; color: var(--muted); cursor: pointer; }
|
||||
.popup-cookie-actions button:hover { background: var(--border); color: var(--foreground); }
|
||||
.popup-cookie-actions button.danger:hover { color: var(--danger); }
|
||||
.popup-cookie-editor, .popup-ua-custom { min-height: 0; flex: 1; padding: 13px 16px 15px; overflow-y: auto; display: grid; gap: 11px; align-content: start; }
|
||||
.popup-editor-title { display: flex; align-items: flex-start; justify-content: space-between; gap: 10px; }
|
||||
.popup-editor-title strong, .popup-editor-title span { display: block; }
|
||||
.popup-editor-title strong { font-size: var(--text-md); }
|
||||
.popup-editor-title span { margin-top: 2px; color: var(--muted); font-size: var(--text-xs); }
|
||||
.popup-cookie-editor > label, .popup-ua-custom > label, .popup-editor-grid label { display: grid; gap: 5px; color: var(--muted-strong); font-size: var(--text-xs); }
|
||||
.popup-cookie-editor input, .popup-cookie-editor select, .popup-ua-custom input, .popup-ua-custom textarea { width: 100%; min-width: 0; }
|
||||
.popup-editor-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
|
||||
.popup-cookie-flags { display: flex; align-items: center; gap: 18px; }
|
||||
.popup-cookie-flags label { display: flex; align-items: center; gap: 6px; color: var(--muted-strong); font-size: var(--text-xs); }
|
||||
.popup-inline-warning { padding: 8px 10px; border-left: 3px solid var(--warning); background: var(--warning-soft); color: var(--warning); font-size: var(--text-xs); line-height: 16px; }
|
||||
|
||||
/* Popup User-Agent */
|
||||
.popup-ua-current { padding: 9px 14px; display: grid; gap: 2px; border-bottom: 1px solid var(--border); background: var(--surface); }
|
||||
.popup-ua-current > span { color: var(--muted); font-size: var(--text-xs); }
|
||||
.popup-ua-current > strong { font-size: var(--text-md); }
|
||||
.popup-ua-current > code { overflow: hidden; color: var(--muted-strong); font-size: var(--text-xs); white-space: nowrap; text-overflow: ellipsis; }
|
||||
.popup-ua-current > small { margin-top: 3px; color: var(--muted); font-size: var(--text-xs); }
|
||||
.popup-ua-list { min-height: 0; flex: 1; padding: 5px 8px; overflow-y: auto; background: var(--surface); scrollbar-width: thin; }
|
||||
.popup-ua-list > button { width: 100%; min-height: 43px; padding: 5px 8px; display: grid; grid-template-columns: 30px minmax(0, 1fr) 15px; align-items: center; gap: 8px; border: 0; border-radius: var(--radius-md); background: transparent; color: var(--foreground); text-align: left; cursor: pointer; }
|
||||
.popup-ua-list > button:hover { background: var(--surface-subtle); }
|
||||
.popup-ua-list > button.is-selected { background: var(--primary-soft); }
|
||||
.popup-ua-list > button > span:nth-child(2) { min-width: 0; }
|
||||
.popup-ua-list strong, .popup-ua-list small { display: block; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.popup-ua-list strong { font-size: var(--text-sm); }
|
||||
.popup-ua-list small { margin-top: 1px; color: var(--muted); font-size: var(--text-xs); }
|
||||
.popup-ua-list > button > i { width: 15px; height: 15px; flex: 0 0 auto; padding: 2.5px; border: 1.5px solid var(--border-strong); border-radius: 50%; background-clip: content-box; transition: border-color .13s ease; }
|
||||
.popup-ua-list > button.is-selected > i { border-color: var(--primary); background-color: var(--primary); }
|
||||
.popup-ua-icon { width: 28px; height: 28px; display: grid; place-items: center; border-radius: 7px; background: var(--surface-subtle); color: var(--muted-strong); }
|
||||
.popup-ua-list > button.is-selected .popup-ua-icon { background: var(--surface); color: var(--primary); }
|
||||
.popup-ua-actions { min-height: 52px; padding: 8px 12px; display: flex; justify-content: flex-end; gap: 7px; border-top: 1px solid var(--border); }
|
||||
|
||||
@keyframes popup-view-in { from { opacity: 0; transform: translateX(10px); } to { opacity: 1; transform: translateX(0); } }
|
||||
@keyframes popup-content-in { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: translateY(0); } }
|
||||
@media (prefers-reduced-motion: reduce) { .popup-tool-view, .popup-view-enter { animation: none; } }
|
||||
|
||||
/* Footer CTA */
|
||||
.popup-footer { margin-top: auto; padding: 10px 14px 12px; border-top: 1px solid var(--border); background: var(--surface); }
|
||||
.popup-capture { width: 100%; height: 36px; border-radius: 7px; font-size: var(--text-md); box-shadow: 0 1px 0 color-mix(in srgb, var(--primary-strong) 55%, transparent); }
|
||||
.popup-notice { display: block; margin-top: 6px; overflow: hidden; color: var(--muted); font-size: var(--text-sm); line-height: 16px; text-align: center; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.popup-global-notice { position: absolute; z-index: 20; left: 50%; bottom: 54px; max-width: calc(100% - 28px); padding: 7px 11px; overflow: hidden; border: 1px solid var(--border); border-radius: 999px; background: var(--foreground); color: var(--surface); box-shadow: var(--shadow-md); font-size: var(--text-xs); line-height: 16px; text-overflow: ellipsis; white-space: nowrap; pointer-events: none; transform: translateX(-50%); animation: popup-content-in .16s ease-out; }
|
||||
|
||||
.popup-loading { width: 390px; height: 230px; display: flex; align-items: center; justify-content: center; gap: 9px; color: var(--muted); background: var(--background); font-size: var(--text-md); }
|
||||
.spin { animation: spin .8s linear infinite; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
@keyframes pulse { 50% { opacity: .35; } }
|
||||
@@ -0,0 +1,215 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import {
|
||||
AlertTriangle, Braces, Check, Cookie, ExternalLink, Gauge, Network, Radio, RefreshCw, UserRoundCog, X,
|
||||
} from 'lucide-react';
|
||||
import { browser } from 'wxt/browser';
|
||||
import { YakMark } from '@/components/brand/Brand';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Tooltip, TooltipProvider } from '@/components/ui/tooltip';
|
||||
import { HANDOFF_REASON_LABELS, waitingHandoff } from '@/features/handoff/presentation';
|
||||
import { isStateStorageChange } from '@/protocol/storage';
|
||||
import type { ActiveTabInfo, BridgeStatus, ExtensionState, UserAgentResolution } from '@/types/models';
|
||||
import { errorMessage, request } from '@/platform/messaging/runtime';
|
||||
import { CookieQuickView } from './views/CookieQuickView';
|
||||
import { OverviewQuickView } from './views/OverviewQuickView';
|
||||
import { ProxyQuickView } from './views/ProxyQuickView';
|
||||
import { UserAgentQuickView } from './views/UserAgentQuickView';
|
||||
import './App.css';
|
||||
|
||||
type PopupView = 'home' | 'proxy' | 'cookies' | 'user-agent';
|
||||
|
||||
const FULL_VIEW_TARGETS: Record<PopupView, { section: string; label: string }> = {
|
||||
home: { section: 'overview', label: '打开完整工作台' },
|
||||
proxy: { section: 'rules', label: '打开代理策略' },
|
||||
cookies: { section: 'cookies', label: '打开完整 Cookie Editor' },
|
||||
'user-agent': { section: 'user-agent', label: '打开 User-Agent 管理' },
|
||||
};
|
||||
|
||||
function engineStatusLabel(state: ExtensionState, bridge: BridgeStatus): string {
|
||||
if (bridge.state === 'connected') return '引擎在线';
|
||||
if (bridge.state === 'connecting') return '正在连接引擎';
|
||||
if (bridge.state === 'negotiating') return '正在验证引擎身份';
|
||||
if (bridge.state === 'error') return bridge.message || '引擎连接失败';
|
||||
return state.bridge.pairedEngine ? bridge.message || '引擎离线' : '尚未配对引擎';
|
||||
}
|
||||
|
||||
function App() {
|
||||
const [state, setState] = useState<ExtensionState>();
|
||||
const [tab, setTab] = useState<ActiveTabInfo>();
|
||||
const [bridge, setBridge] = useState<BridgeStatus>({ state: 'disconnected', message: '未连接引擎' });
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [notice, setNotice] = useState('');
|
||||
const [view, setView] = useState<PopupView>('home');
|
||||
const [cookieCount, setCookieCount] = useState(0);
|
||||
const [uaResolution, setUaResolution] = useState<UserAgentResolution>();
|
||||
|
||||
const load = useCallback(async () => {
|
||||
const [nextState, nextTab, nextBridge] = await Promise.all([
|
||||
request('state.get'),
|
||||
request('tab.active').catch(() => undefined),
|
||||
request('bridge.status'),
|
||||
]);
|
||||
setState(nextState);
|
||||
setTab(nextTab);
|
||||
setBridge(nextBridge);
|
||||
if (nextTab?.url?.startsWith('http')) {
|
||||
const [cookies, resolution] = await Promise.all([
|
||||
request('cookie.list', { url: nextTab.url, tabId: nextTab.id }).catch(() => []),
|
||||
request('ua.resolve', { url: nextTab.url }).catch(() => undefined),
|
||||
]);
|
||||
setCookieCount(cookies.length);
|
||||
setUaResolution(resolution);
|
||||
} else {
|
||||
setCookieCount(0);
|
||||
setUaResolution(undefined);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
const listener = (message: { action?: string; payload?: BridgeStatus }) => {
|
||||
if (message.action === 'bridge.status.changed' && message.payload) setBridge(message.payload);
|
||||
};
|
||||
browser.runtime.onMessage.addListener(listener);
|
||||
const onStorageChange = (changes: Record<string, unknown>) => {
|
||||
if (isStateStorageChange(changes)) void load();
|
||||
};
|
||||
browser.storage.onChanged.addListener(onStorageChange);
|
||||
return () => {
|
||||
browser.runtime.onMessage.removeListener(listener);
|
||||
browser.storage.onChanged.removeListener(onStorageChange);
|
||||
};
|
||||
}, [load]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!notice) return undefined;
|
||||
const timer = globalThis.setTimeout(() => setNotice(''), 2_400);
|
||||
return () => globalThis.clearTimeout(timer);
|
||||
}, [notice]);
|
||||
|
||||
const grantActive = Boolean(state?.activeGrant && state.activeGrant.expiresAt > Date.now() && tab && state.activeGrant.targets.some((target) => target.tabId === tab.id));
|
||||
const handoff = waitingHandoff(state?.handoff);
|
||||
|
||||
const run = async (task: () => Promise<void>, success?: string) => {
|
||||
setBusy(true);
|
||||
setNotice('');
|
||||
try {
|
||||
await task();
|
||||
if (success) setNotice(success);
|
||||
} catch (error) {
|
||||
setNotice(errorMessage(error));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const openTool = (tool: string) => {
|
||||
const target = tab ? `?tabId=${tab.id}` : '';
|
||||
return browser.tabs.create({ url: browser.runtime.getURL(`/options.html${target}#${tool}`) });
|
||||
};
|
||||
|
||||
const toggleEngine = () => run(async () => {
|
||||
if (!state!.bridge.pairedEngine) {
|
||||
await request('bridge.pair');
|
||||
await openTool('engine');
|
||||
return;
|
||||
}
|
||||
if (bridge.state === 'connected') await request('bridge.disconnect'); else await request('bridge.connect');
|
||||
setBridge(await request('bridge.status'));
|
||||
});
|
||||
|
||||
const capture = () => run(async () => {
|
||||
const context = await request('context.capture', {
|
||||
includeDom: true,
|
||||
includeStorage: true,
|
||||
includeCookies: true,
|
||||
tabId: tab?.id,
|
||||
});
|
||||
await navigator.clipboard.writeText(JSON.stringify(context, null, 2));
|
||||
setNotice('页面上下文已复制');
|
||||
});
|
||||
|
||||
if (!state) {
|
||||
return <div className="popup-loading"><RefreshCw size={18} className="spin" />正在读取浏览器状态</div>;
|
||||
}
|
||||
|
||||
const engineBusy = bridge.state === 'connecting' || bridge.state === 'negotiating';
|
||||
const currentHost = (() => { try { return tab?.url ? new URL(tab.url).host : ''; } catch { return ''; } })();
|
||||
const statusLabel = engineStatusLabel(state, bridge);
|
||||
const statusActionLabel = bridge.state === 'connected'
|
||||
? `${statusLabel},点击断开`
|
||||
: state.bridge.pairedEngine ? `${statusLabel},点击连接` : `${statusLabel},点击配对`;
|
||||
const fullViewTarget = FULL_VIEW_TARGETS[view];
|
||||
|
||||
return (
|
||||
<TooltipProvider delayDuration={350}>
|
||||
<main className="popup-shell">
|
||||
<header className="popup-header">
|
||||
<div className="popup-header-main">
|
||||
<Tooltip label="Yakit Browser Agent" side="bottom">
|
||||
<span className="popup-brand-mark" role="img" aria-label="Yakit Browser Agent">
|
||||
<YakMark />
|
||||
</span>
|
||||
</Tooltip>
|
||||
<div className="popup-target">
|
||||
<div className="popup-target-title">
|
||||
<span className="popup-favicon">{tab?.favIconUrl ? <img src={tab.favIconUrl} alt="" /> : <Radio size={12} />}</span>
|
||||
<strong title={tab?.title}>{tab?.title || '当前页面不可访问'}</strong>
|
||||
</div>
|
||||
<span className="popup-target-host" title={tab?.url}>{currentHost || '无法读取当前标签页'}</span>
|
||||
</div>
|
||||
<div className="popup-brand-actions">
|
||||
<Tooltip label={statusActionLabel} side="bottom">
|
||||
<button className={`popup-engine-status ${bridge.state}`} aria-label={statusLabel} disabled={busy || engineBusy} onClick={() => void toggleEngine()}>
|
||||
<i aria-hidden="true" />
|
||||
<span>{bridge.state === 'connected' ? '在线' : engineBusy ? '连接中' : state.bridge.pairedEngine ? '离线' : '配对'}</span>
|
||||
</button>
|
||||
</Tooltip>
|
||||
<Tooltip label={fullViewTarget.label} side="bottom">
|
||||
<Button size="icon" variant="ghost" aria-label={fullViewTarget.label} onClick={() => void openTool(fullViewTarget.section)}>
|
||||
<ExternalLink size={16} />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="popup-body">
|
||||
<nav className="popup-rail" aria-label="Popup 工具导航">
|
||||
<div className="popup-rail-main">
|
||||
<Tooltip label="运行概览" side="right"><button className={view === 'home' ? 'is-active' : ''} aria-label="运行概览" aria-current={view === 'home' ? 'page' : undefined} onClick={() => setView('home')}><Gauge size={18} /></button></Tooltip>
|
||||
<Tooltip label="代理" side="right"><button className={view === 'proxy' ? 'is-active' : ''} aria-label="代理" aria-current={view === 'proxy' ? 'page' : undefined} onClick={() => setView('proxy')}><Network size={18} /></button></Tooltip>
|
||||
<Tooltip label="Cookie Editor" side="right"><button className={view === 'cookies' ? 'is-active' : ''} aria-label="Cookie Editor" aria-current={view === 'cookies' ? 'page' : undefined} onClick={() => setView('cookies')}><Cookie size={18} /></button></Tooltip>
|
||||
<Tooltip label="User-Agent" side="right"><button className={view === 'user-agent' ? 'is-active' : ''} aria-label="User-Agent" aria-current={view === 'user-agent' ? 'page' : undefined} onClick={() => setView('user-agent')}><UserRoundCog size={18} /></button></Tooltip>
|
||||
</div>
|
||||
<div className="popup-rail-bottom">
|
||||
<Tooltip label="登录态工作区" side="right"><button aria-label="打开登录态工作区" onClick={() => void openTool('context')}><Braces size={18} /></button></Tooltip>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<section className="popup-workspace">
|
||||
{handoff && <section className="popup-handoff" aria-live="assertive">
|
||||
<AlertTriangle size={18} />
|
||||
<div className="popup-handoff__copy">
|
||||
<strong>{HANDOFF_REASON_LABELS[handoff.reason]}</strong>
|
||||
<span>{handoff.message}</span>
|
||||
<small title={handoff.target.title}>{handoff.target.title}</small>
|
||||
</div>
|
||||
<div className="popup-handoff__actions">
|
||||
<Button size="sm" variant="primary" disabled={busy} onClick={() => void run(async () => setState(await request('handoff.resolve', { id: handoff.id, outcome: 'completed' })))}><Check size={14} />完成</Button>
|
||||
<Button size="icon" variant="ghost" disabled={busy} aria-label="取消人工接管" title="取消人工接管" onClick={() => void run(async () => setState(await request('handoff.resolve', { id: handoff.id, outcome: 'cancelled' })))}><X size={15} /></Button>
|
||||
</div>
|
||||
</section>}
|
||||
{view === 'home' && <OverviewQuickView state={state} tab={tab} grantActive={grantActive} busy={busy} run={run} setState={setState} cookieCount={cookieCount} uaResolution={uaResolution} onNavigate={setView} onOpenContext={() => void openTool('context')} onCapture={() => void capture()} />}
|
||||
{view === 'proxy' && <ProxyQuickView state={state} setState={setState} busy={busy} run={run} tab={tab} onOpenFull={() => void openTool('rules')} />}
|
||||
{view === 'cookies' && <CookieQuickView tab={tab} busy={busy} run={run} onCountChange={setCookieCount} />}
|
||||
{view === 'user-agent' && <UserAgentQuickView tab={tab} state={state} setState={setState} busy={busy} run={run} onResolutionChange={setUaResolution} />}
|
||||
</section>
|
||||
</div>
|
||||
{notice && <span className="popup-global-notice" role="status">{notice}</span>}
|
||||
</main>
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Yakit Browser Agent</title>
|
||||
<meta name="manifest.type" content="browser_action" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="./main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,14 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import App from './App.tsx';
|
||||
import { watchTheme } from '@/platform/storage/appearance';
|
||||
import '@/styles/global.css';
|
||||
import './style.css';
|
||||
|
||||
watchTheme();
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
@@ -0,0 +1 @@
|
||||
html, body, #root { width: 390px; height: 600px; margin: 0; overflow: hidden; }
|
||||
@@ -0,0 +1,113 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Check, Cookie, Copy, Plus, Search, Trash2, X } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { cookieKey, cookieRemovalInput } from '@/features/cookies/presentation';
|
||||
import { request } from '@/platform/messaging/runtime';
|
||||
import type { ActiveTabInfo, BrowserCookie, CookieInput } from '@/types/models';
|
||||
|
||||
type RunTask = (task: () => Promise<void>, success?: string) => Promise<void>;
|
||||
|
||||
interface CookieQuickViewProps {
|
||||
tab?: ActiveTabInfo;
|
||||
busy: boolean;
|
||||
run: RunTask;
|
||||
onCountChange: (count: number) => void;
|
||||
}
|
||||
|
||||
function emptyDraft(url = ''): Omit<CookieInput, 'url'> {
|
||||
return {
|
||||
name: '', value: '', path: '/', secure: url.startsWith('https:'), httpOnly: false, sameSite: 'unspecified',
|
||||
};
|
||||
}
|
||||
|
||||
export function CookieQuickView({ tab, busy, run, onCountChange }: CookieQuickViewProps) {
|
||||
const url = tab?.url?.startsWith('http') ? tab.url : '';
|
||||
const [cookies, setCookies] = useState<BrowserCookie[]>([]);
|
||||
const [query, setQuery] = useState('');
|
||||
const [draft, setDraft] = useState<Omit<CookieInput, 'url'>>(emptyDraft(url));
|
||||
const [editing, setEditing] = useState<BrowserCookie>();
|
||||
const [editorOpen, setEditorOpen] = useState(false);
|
||||
const [loadError, setLoadError] = useState('');
|
||||
|
||||
const reload = useCallback(async () => {
|
||||
if (!url || !tab?.id) {
|
||||
setCookies([]);
|
||||
onCountChange(0);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const next = await request('cookie.list', { url, tabId: tab.id });
|
||||
setCookies(next);
|
||||
onCountChange(next.length);
|
||||
setLoadError('');
|
||||
} catch (error) {
|
||||
setLoadError(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
}, [onCountChange, tab?.id, url]);
|
||||
|
||||
useEffect(() => { void reload(); }, [reload]);
|
||||
|
||||
const visibleCookies = useMemo(() => {
|
||||
const needle = query.trim().toLowerCase();
|
||||
return cookies.filter((cookie) => !needle || [cookie.name, cookie.domain, cookie.path]
|
||||
.some((value) => value.toLowerCase().includes(needle)));
|
||||
}, [cookies, query]);
|
||||
|
||||
const startNew = () => {
|
||||
setEditing(undefined);
|
||||
setDraft(emptyDraft(url));
|
||||
setEditorOpen(true);
|
||||
};
|
||||
const startEdit = (cookie: BrowserCookie) => {
|
||||
setEditing(cookie);
|
||||
setDraft({
|
||||
name: cookie.name, value: cookie.value, domain: cookie.hostOnly ? undefined : cookie.domain,
|
||||
path: cookie.path, secure: cookie.secure, httpOnly: cookie.httpOnly,
|
||||
sameSite: cookie.sameSite as CookieInput['sameSite'], expirationDate: cookie.expirationDate,
|
||||
storeId: cookie.storeId, firstPartyDomain: cookie.firstPartyDomain, partitionKey: cookie.partitionKey,
|
||||
});
|
||||
setEditorOpen(true);
|
||||
};
|
||||
const closeEditor = () => {
|
||||
setEditorOpen(false);
|
||||
setEditing(undefined);
|
||||
setDraft(emptyDraft(url));
|
||||
};
|
||||
|
||||
const saveCookie = () => run(async () => {
|
||||
if (!url || !tab?.id || !draft.name) throw new Error('Cookie 名称不能为空');
|
||||
await request('cookie.set', { url, tabId: tab.id, ...draft });
|
||||
await reload();
|
||||
closeEditor();
|
||||
}, editing ? 'Cookie 已更新' : 'Cookie 已创建');
|
||||
|
||||
return <section className="popup-view popup-tool-view popup-cookie-view">
|
||||
<div className="popup-tool-context"><Cookie size={14} /><span title={url}>{url ? new URL(url).host : '当前页面不可访问'}</span><strong>{cookies.length}</strong></div>
|
||||
|
||||
{editorOpen ? <div className="popup-cookie-editor popup-view-enter">
|
||||
<div className="popup-editor-title"><div><strong>{editing ? '编辑 Cookie' : '新增 Cookie'}</strong><span>{editing ? `${editing.domain}${editing.path}` : '默认创建 HostOnly Cookie'}</span></div><Button size="icon" variant="ghost" aria-label="关闭 Cookie 编辑器" onClick={closeEditor}><X size={15} /></Button></div>
|
||||
<label><span>名称</span><input autoFocus={!editing} disabled={Boolean(editing)} value={draft.name} onChange={(event) => setDraft({ ...draft, name: event.target.value })} placeholder="session_id" /></label>
|
||||
<label><span>值</span><input value={draft.value} onChange={(event) => setDraft({ ...draft, value: event.target.value })} /></label>
|
||||
<div className="popup-editor-grid"><label><span>Path</span><input disabled={Boolean(editing)} value={draft.path || '/'} onChange={(event) => setDraft({ ...draft, path: event.target.value || '/' })} /></label><label><span>SameSite</span><select value={draft.sameSite} onChange={(event) => setDraft({ ...draft, sameSite: event.target.value as CookieInput['sameSite'] })}><option value="unspecified">Unspecified</option><option value="lax">Lax</option><option value="strict">Strict</option><option value="no_restriction">None</option></select></label></div>
|
||||
<div className="popup-cookie-flags"><label><input type="checkbox" checked={draft.secure || false} onChange={(event) => setDraft({ ...draft, secure: event.target.checked })} />Secure</label><label><input type="checkbox" checked={draft.httpOnly || false} onChange={(event) => setDraft({ ...draft, httpOnly: event.target.checked })} />HttpOnly</label></div>
|
||||
{editing?.partitionKey && <div className="popup-inline-warning">Partitioned Cookie 将保留现有 top-level site;修改分区请打开完整编辑器。</div>}
|
||||
<Button variant="primary" disabled={busy || !url || !draft.name} onClick={() => void saveCookie()}><Check size={15} />{editing ? '保存修改' : '创建 Cookie'}</Button>
|
||||
</div> : <>
|
||||
<div className="popup-tool-toolbar"><label><Search size={14} /><input aria-label="搜索当前页面 Cookie" value={query} onChange={(event) => setQuery(event.target.value)} placeholder="搜索名称、Domain 或 Path" /></label><Button size="icon" variant="ghost" aria-label="新增 Cookie" title="新增 Cookie" disabled={!url} onClick={startNew}><Plus size={16} /></Button></div>
|
||||
<div className="popup-cookie-list popup-view-enter">
|
||||
{loadError && <div className="popup-tool-empty">{loadError}</div>}
|
||||
{!loadError && visibleCookies.length === 0 && <div className="popup-tool-empty">{cookies.length ? '没有匹配的 Cookie' : '当前页面没有可用 Cookie'}</div>}
|
||||
{visibleCookies.map((cookie) => {
|
||||
const key = cookieKey(cookie);
|
||||
const authRelated = /(auth|token|jwt|session|login|csrf|sid)/i.test(cookie.name);
|
||||
return <article className="popup-cookie-row" key={key}>
|
||||
<button className="popup-cookie-main" onClick={() => startEdit(cookie)}><span><strong>{cookie.name}</strong>{authRelated && <i>认证</i>}</span><code title={cookie.value}>{cookie.value}</code><small>{cookie.domain}{cookie.path}</small></button>
|
||||
<div className="popup-cookie-meta">{cookie.httpOnly && <i>HttpOnly</i>}{cookie.secure && <i>Secure</i>}{cookie.partitionKey && <i>CHIPS</i>}</div>
|
||||
<div className="popup-cookie-actions"><button aria-label={`复制 ${cookie.name}`} onClick={() => void run(async () => navigator.clipboard.writeText(`${cookie.name}=${cookie.value}`), 'Cookie 已复制')}><Copy size={14} /></button><button className="danger" aria-label={`删除 ${cookie.name}`} onClick={() => void run(async () => { await request('cookie.remove', cookieRemovalInput(cookie)); await reload(); }, 'Cookie 已删除')}><Trash2 size={14} /></button></div>
|
||||
</article>;
|
||||
})}
|
||||
</div>
|
||||
<div className="popup-tool-footer"><button disabled={!cookies.length || busy} onClick={() => { if (window.confirm(`删除当前页面可用的 ${cookies.length} 个 Cookie?`)) void run(async () => { await request('cookie.removeMany', { cookies: cookies.map(cookieRemovalInput) }); await reload(); }, '当前页面 Cookie 已清理'); }}><Trash2 size={14} />清理当前页面</button></div>
|
||||
</>}
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { Braces, ChevronRight, Cookie, Network, Radio, ShieldCheck, UserRoundCog } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { request } from '@/platform/messaging/runtime';
|
||||
import { READ_CAPABILITY_SCOPES } from '@/protocol/capabilities';
|
||||
import type { ActiveTabInfo, ExtensionState, UserAgentResolution } from '@/types/models';
|
||||
|
||||
type PopupView = 'home' | 'proxy' | 'cookies' | 'user-agent';
|
||||
type RunTask = (task: () => Promise<void>, success?: string) => Promise<void>;
|
||||
|
||||
interface OverviewQuickViewProps {
|
||||
state: ExtensionState;
|
||||
tab?: ActiveTabInfo;
|
||||
grantActive: boolean;
|
||||
busy: boolean;
|
||||
run: RunTask;
|
||||
setState: (state: ExtensionState) => void;
|
||||
cookieCount: number;
|
||||
uaResolution?: UserAgentResolution;
|
||||
onNavigate: (view: PopupView) => void;
|
||||
onOpenContext: () => void;
|
||||
onCapture: () => void;
|
||||
}
|
||||
|
||||
export function OverviewQuickView({
|
||||
state, tab, grantActive, busy, run, setState, cookieCount, uaResolution, onNavigate, onOpenContext, onCapture,
|
||||
}: OverviewQuickViewProps) {
|
||||
const activeProxy = state.activeProxyId === 'auto'
|
||||
? '自动切换'
|
||||
: state.proxyProfiles.find((profile) => profile.id === state.activeProxyId)?.name || '未选择';
|
||||
const targetAvailable = Boolean(tab?.url?.startsWith('http'));
|
||||
|
||||
return <section className="popup-overview-view">
|
||||
<section className={`popup-share ${grantActive ? 'is-active' : ''}`}>
|
||||
<div className="popup-share-copy">
|
||||
<ShieldCheck size={18} />
|
||||
<div>
|
||||
<strong>共享当前标签页</strong>
|
||||
<span>{grantActive ? `只读会话 ${new Date(state.activeGrant!.expiresAt).toLocaleTimeString()} 到期` : '创建 30 分钟只读会话'}</span>
|
||||
</div>
|
||||
</div>
|
||||
<Switch checked={grantActive} disabled={!tab || busy} aria-label="共享当前浏览器上下文" onCheckedChange={(checked) => void run(async () => {
|
||||
const updated = checked
|
||||
? await request('grant.create', { targets: [{ tabId: tab!.id, frameId: 0 }], scopes: READ_CAPABILITY_SCOPES, durationMinutes: 30 })
|
||||
: await request('grant.revoke');
|
||||
setState(updated);
|
||||
})} />
|
||||
</section>
|
||||
|
||||
<div className="popup-overview-lead">
|
||||
<div className="popup-overview-lead__meta"><strong className={targetAvailable ? '' : 'is-unavailable'}><i />{targetAvailable ? '页面已就绪' : '页面不可访问'}</strong><span>{targetAvailable ? '从这里快速查看和调整当前标签页' : '切换到 HTTP(S) 页面后可使用浏览器工具'}</span></div>
|
||||
</div>
|
||||
|
||||
<section className="popup-overview-summary" aria-label="当前页面状态">
|
||||
<button onClick={() => onNavigate('proxy')}>
|
||||
<span className="popup-overview-icon"><Network size={16} /></span>
|
||||
<span><small>当前代理</small><strong>{activeProxy}</strong></span>
|
||||
<ChevronRight size={15} />
|
||||
</button>
|
||||
<button onClick={() => onNavigate('user-agent')}>
|
||||
<span className="popup-overview-icon"><UserRoundCog size={16} /></span>
|
||||
<span><small>当前 User-Agent</small><strong>{uaResolution?.profile?.name || '浏览器默认'}</strong></span>
|
||||
<ChevronRight size={15} />
|
||||
</button>
|
||||
<button onClick={() => onNavigate('cookies')}>
|
||||
<span className="popup-overview-icon"><Cookie size={16} /></span>
|
||||
<span><small>当前页面 Cookie</small><strong>{targetAvailable ? `${cookieCount} 个可用 Cookie` : '当前页面不可用'}</strong></span>
|
||||
<ChevronRight size={15} />
|
||||
</button>
|
||||
<button onClick={onOpenContext}>
|
||||
<span className="popup-overview-icon"><Braces size={16} /></span>
|
||||
<span><small>登录态工作区</small><strong>Storage、数据库与页面上下文</strong></span>
|
||||
<ChevronRight size={15} />
|
||||
</button>
|
||||
</section>
|
||||
|
||||
<footer className="popup-footer">
|
||||
<Button className="popup-capture" variant="primary" disabled={busy || !targetAvailable} onClick={onCapture}>
|
||||
{busy ? <Radio className="spin" size={15} /> : <Radio size={15} />}采集并复制上下文
|
||||
</Button>
|
||||
</footer>
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { AlertCircle, Check, ExternalLink, Globe2, LoaderCircle, Network, Route } from 'lucide-react';
|
||||
import { request } from '@/platform/messaging/runtime';
|
||||
import type { ActiveTabInfo, ExtensionState, ProxyProfile, ProxyRulePreview } from '@/types/models';
|
||||
|
||||
type RunTask = (task: () => Promise<void>, success?: string) => Promise<void>;
|
||||
|
||||
interface ProxyQuickViewProps {
|
||||
state: ExtensionState;
|
||||
setState: (state: ExtensionState) => void;
|
||||
busy: boolean;
|
||||
run: RunTask;
|
||||
tab?: ActiveTabInfo;
|
||||
onOpenFull: () => void;
|
||||
}
|
||||
|
||||
const AUTOMATIC_TARGET = '__automatic__';
|
||||
const CURRENT_GLOBAL_TARGET = '__current_global__';
|
||||
|
||||
type SiteApplyStatus = 'idle' | 'applying' | 'success' | 'error';
|
||||
|
||||
const PROXY_KIND_LABELS: Record<ProxyProfile['kind'], string> = {
|
||||
fixed_servers: '固定代理',
|
||||
pac_script: 'PAC Script',
|
||||
direct: '直连',
|
||||
system: '系统代理',
|
||||
};
|
||||
|
||||
function proxyDetail(profile: ProxyProfile): string {
|
||||
return profile.kind === 'fixed_servers'
|
||||
? `${profile.scheme}://${profile.host}:${profile.port}`
|
||||
: PROXY_KIND_LABELS[profile.kind];
|
||||
}
|
||||
|
||||
function hostname(url?: string): string {
|
||||
try { return url ? new URL(url).hostname.toLowerCase() : ''; } catch { return ''; }
|
||||
}
|
||||
|
||||
function routeKindLabel(preview?: ProxyRulePreview): string {
|
||||
if (preview?.matchedKind === 'manual') return '站点覆盖';
|
||||
if (preview?.matchedKind === 'source') return '规则订阅';
|
||||
return '自动判断';
|
||||
}
|
||||
|
||||
export function ProxyQuickView({ state, setState, busy, run, tab, onOpenFull }: ProxyQuickViewProps) {
|
||||
const [preview, setPreview] = useState<ProxyRulePreview>();
|
||||
const currentHostname = hostname(tab?.url);
|
||||
const autoActive = state.activeProxyId === 'auto';
|
||||
const activeProfile = state.proxyProfiles.find((profile) => profile.id === state.activeProxyId);
|
||||
const routableProfiles = useMemo(
|
||||
() => state.proxyProfiles.filter((profile) => profile.kind === 'direct' || profile.kind === 'fixed_servers'),
|
||||
[state.proxyProfiles],
|
||||
);
|
||||
const siteRule = useMemo(() => [...state.proxyRules]
|
||||
.sort((left, right) => left.order - right.order)
|
||||
.find((rule) => rule.enabled && rule.condition.type === 'host_exact'
|
||||
&& rule.condition.value.toLowerCase() === currentHostname), [currentHostname, state.proxyRules]);
|
||||
const persistedTarget = siteRule?.proxyProfileId || AUTOMATIC_TARGET;
|
||||
const [siteTarget, setSiteTarget] = useState(autoActive ? persistedTarget : CURRENT_GLOBAL_TARGET);
|
||||
const [siteApplyStatus, setSiteApplyStatus] = useState<SiteApplyStatus>('idle');
|
||||
const [siteApplyMessage, setSiteApplyMessage] = useState('');
|
||||
const sourceRuleCount = state.proxyRuleSources
|
||||
.filter((source) => source.enabled && source.revision)
|
||||
.reduce((total, source) => total + source.supportedRuleCount, 0);
|
||||
|
||||
useEffect(() => {
|
||||
setSiteTarget(autoActive
|
||||
? routableProfiles.some((profile) => profile.id === persistedTarget) ? persistedTarget : AUTOMATIC_TARGET
|
||||
: CURRENT_GLOBAL_TARGET);
|
||||
}, [autoActive, persistedTarget, routableProfiles]);
|
||||
|
||||
useEffect(() => {
|
||||
setSiteApplyStatus('idle');
|
||||
setSiteApplyMessage('');
|
||||
}, [currentHostname]);
|
||||
|
||||
useEffect(() => {
|
||||
if (siteApplyStatus !== 'success' && siteApplyStatus !== 'error') return undefined;
|
||||
const timer = globalThis.setTimeout(() => {
|
||||
setSiteApplyStatus('idle');
|
||||
setSiteApplyMessage('');
|
||||
}, 2_400);
|
||||
return () => globalThis.clearTimeout(timer);
|
||||
}, [siteApplyStatus]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!tab?.url?.startsWith('http')) {
|
||||
setPreview(undefined);
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
void request('proxy.rules.preview', { url: tab.url })
|
||||
.then((result) => { if (!cancelled) setPreview(result); })
|
||||
.catch(() => { if (!cancelled) setPreview(undefined); });
|
||||
return () => { cancelled = true; };
|
||||
}, [tab?.url, state.proxyRuntime.revision, state.proxyRuntime.dirty]);
|
||||
|
||||
const switchAuto = () => run(async () => {
|
||||
setState(await request('proxy.auto.apply'));
|
||||
if (tab?.url) setPreview(await request('proxy.rules.preview', { url: tab.url }));
|
||||
}, '自动切换已启用');
|
||||
|
||||
const applySiteRoute = (nextTarget: string) => {
|
||||
if (!tab?.url || nextTarget === CURRENT_GLOBAL_TARGET) return Promise.resolve();
|
||||
const previousTarget = autoActive ? persistedTarget : CURRENT_GLOBAL_TARGET;
|
||||
const nextProfile = routableProfiles.find((profile) => profile.id === nextTarget);
|
||||
setSiteTarget(nextTarget);
|
||||
setSiteApplyStatus('applying');
|
||||
setSiteApplyMessage(nextTarget === AUTOMATIC_TARGET
|
||||
? '正在恢复自动判断…'
|
||||
: `正在切换到 ${nextProfile?.name || '所选出口'}…`);
|
||||
return run(async () => {
|
||||
try {
|
||||
const updated = nextTarget === AUTOMATIC_TARGET
|
||||
? await request('proxy.site.route.clear', { url: tab.url! })
|
||||
: await request('proxy.site.route', { url: tab.url!, profileId: nextTarget });
|
||||
setState(updated);
|
||||
setPreview(await request('proxy.rules.preview', { url: tab.url! }).catch(() => undefined));
|
||||
setSiteApplyStatus('success');
|
||||
setSiteApplyMessage(nextTarget === AUTOMATIC_TARGET
|
||||
? '已恢复自动判断'
|
||||
: `已应用 · ${nextProfile?.name || '所选出口'}`);
|
||||
} catch (error) {
|
||||
setSiteTarget(previousTarget);
|
||||
setSiteApplyStatus('error');
|
||||
setSiteApplyMessage('切换失败,已恢复原设置');
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const effectiveProfile = state.proxyProfiles.find((profile) => profile.id === preview?.effectiveProfileId);
|
||||
const activeModeName = autoActive ? '自动切换' : activeProfile?.name || '未选择';
|
||||
const siteHint = !autoActive
|
||||
? `当前使用“${activeModeName}”;选择网站出口后将启用自动切换。`
|
||||
: siteTarget === AUTOMATIC_TARGET
|
||||
? '不创建手动覆盖,由订阅源和默认出口决定。'
|
||||
: `最高优先级的精确主机规则,只影响 ${currentHostname}。`;
|
||||
const routeLabel = autoActive ? preview?.matchedName || '正在解析路由' : '当前全局模式';
|
||||
const routeProfile = autoActive ? effectiveProfile : activeProfile;
|
||||
const routeKind = autoActive ? preview?.matchedKind || 'default' : 'global';
|
||||
const routeKindText = autoActive ? routeKindLabel(preview) : '全局模式';
|
||||
|
||||
return <section className="popup-view popup-tool-view popup-proxy-view">
|
||||
{currentHostname ? <section className="popup-site-router" aria-label="当前站点路由">
|
||||
<div className="popup-site-router__heading">
|
||||
<div><Globe2 size={16} /><span><small>当前站点</small><strong title={currentHostname}>{currentHostname}</strong></span></div>
|
||||
<i className={routeKind}>{routeKindText}</i>
|
||||
</div>
|
||||
<div className="popup-site-decision" title={autoActive ? preview?.matchedCondition : activeModeName}>
|
||||
<span>{routeLabel}</span><i>→</i><strong>{routeProfile?.name || '—'}</strong>
|
||||
</div>
|
||||
<div className="popup-site-picker">
|
||||
<label htmlFor="popup-site-proxy">网站出口 <span>选择后立即生效</span></label>
|
||||
<select id="popup-site-proxy" aria-label="当前站点代理出口" value={siteTarget} disabled={busy} aria-busy={siteApplyStatus === 'applying'} onChange={(event) => void applySiteRoute(event.target.value)}>
|
||||
{!autoActive && <option value={CURRENT_GLOBAL_TARGET}>当前全局模式 · {activeModeName}</option>}
|
||||
<option value={AUTOMATIC_TARGET}>跟随自动规则 · 清除站点覆盖</option>
|
||||
{routableProfiles.map((profile) => <option value={profile.id} key={profile.id}>{profile.name} · {proxyDetail(profile)}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div className={`popup-site-status is-${siteApplyStatus}`} role="status" aria-live="polite">
|
||||
{siteApplyStatus === 'applying' && <LoaderCircle size={13} className="spin" />}
|
||||
{siteApplyStatus === 'success' && <Check size={13} />}
|
||||
{siteApplyStatus === 'error' && <AlertCircle size={13} />}
|
||||
<small>{siteApplyMessage || siteHint}</small>
|
||||
</div>
|
||||
</section> : <div className="popup-proxy-unavailable"><Globe2 size={17} /><span><strong>当前页面无法设置站点路由</strong><small>请切换到 HTTP(S) 页面。</small></span></div>}
|
||||
|
||||
<div className="popup-mode-heading"><span><strong>浏览器模式</strong><small>全局切换,不会创建站点规则</small></span><i>{activeModeName}</i></div>
|
||||
<div className="popup-proxy-list popup-proxy-list--view" role="radiogroup" aria-label="浏览器代理模式">
|
||||
<button role="radio" aria-checked={autoActive} className={autoActive ? 'is-active' : ''} disabled={busy} onClick={() => void switchAuto()}>
|
||||
<span className="popup-mode-icon"><Route size={15} /></span>
|
||||
<span><strong>自动切换</strong><small>{state.proxyRules.filter((rule) => rule.enabled).length} 条手动 · {sourceRuleCount.toLocaleString()} 条订阅</small></span>
|
||||
{state.proxyRuntime.dirty ? <em>待应用</em> : autoActive ? <Check size={14} /> : null}
|
||||
</button>
|
||||
{state.proxyProfiles.map((profile) => {
|
||||
const active = state.activeProxyId === profile.id;
|
||||
return <button key={profile.id} role="radio" aria-checked={active} className={active ? 'is-active' : ''} disabled={busy} onClick={() => void run(async () => setState(await request('proxy.switch', { id: profile.id })), `${profile.name} 已作为全局模式启用`)}>
|
||||
<span className="popup-mode-icon"><Network size={15} /></span>
|
||||
<span><strong>{profile.name}</strong><small>{proxyDetail(profile)}</small></span>
|
||||
{active && <Check size={14} />}
|
||||
</button>;
|
||||
})}
|
||||
</div>
|
||||
<div className="popup-tool-footer"><span>{state.proxyProfiles.length} 个出口 · {state.proxyRuleSources.length} 个订阅</span><button onClick={onOpenFull}><ExternalLink size={13} />管理策略</button></div>
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { Bot, Laptop, RefreshCw, Save, Smartphone, UserRoundCog, X } from 'lucide-react';
|
||||
import { browser } from 'wxt/browser';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { request } from '@/platform/messaging/runtime';
|
||||
import type {
|
||||
ActiveTabInfo, ExtensionState, UserAgentProfile, UserAgentProfileCategory, UserAgentResolution,
|
||||
} from '@/types/models';
|
||||
|
||||
const BROWSER_DEFAULT = '__browser_default__';
|
||||
type RunTask = (task: () => Promise<void>, success?: string) => Promise<void>;
|
||||
|
||||
interface UserAgentQuickViewProps {
|
||||
tab?: ActiveTabInfo;
|
||||
state: ExtensionState;
|
||||
setState: (state: ExtensionState) => void;
|
||||
busy: boolean;
|
||||
run: RunTask;
|
||||
onResolutionChange: (resolution?: UserAgentResolution) => void;
|
||||
}
|
||||
|
||||
function categoryIcon(category: UserAgentProfileCategory) {
|
||||
if (category === 'mobile') return <Smartphone size={15} />;
|
||||
if (category === 'bot') return <Bot size={15} />;
|
||||
if (category === 'custom') return <UserRoundCog size={15} />;
|
||||
return <Laptop size={15} />;
|
||||
}
|
||||
|
||||
export function UserAgentQuickView({ tab, state, setState, busy, run, onResolutionChange }: UserAgentQuickViewProps) {
|
||||
const url = tab?.url?.startsWith('http') ? tab.url : '';
|
||||
const [profiles, setProfiles] = useState<UserAgentProfile[]>([]);
|
||||
const [resolution, setResolution] = useState<UserAgentResolution>();
|
||||
const [selectedProfileId, setSelectedProfileId] = useState(BROWSER_DEFAULT);
|
||||
const [customOpen, setCustomOpen] = useState(false);
|
||||
const [customName, setCustomName] = useState('');
|
||||
const [customValue, setCustomValue] = useState('');
|
||||
const [loadError, setLoadError] = useState('');
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (!url) {
|
||||
setProfiles(await request('ua.catalog'));
|
||||
setResolution(undefined);
|
||||
onResolutionChange(undefined);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const [nextProfiles, nextResolution] = await Promise.all([request('ua.catalog'), request('ua.resolve', { url })]);
|
||||
setProfiles(nextProfiles);
|
||||
setResolution(nextResolution);
|
||||
setSelectedProfileId(nextResolution.profile?.id || BROWSER_DEFAULT);
|
||||
onResolutionChange(nextResolution);
|
||||
setLoadError('');
|
||||
} catch (error) {
|
||||
setLoadError(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
}, [onResolutionChange, url]);
|
||||
useEffect(() => { void load(); }, [load, state.customUserAgentProfiles, state.userAgentAssignments]);
|
||||
|
||||
const applyAndReload = () => run(async () => {
|
||||
if (!tab || !url) throw new Error('当前页面不能修改 User-Agent');
|
||||
const next = selectedProfileId === BROWSER_DEFAULT
|
||||
? await request('ua.site.reset', { url })
|
||||
: await request('ua.site.apply', { url, profileId: selectedProfileId });
|
||||
setState(next);
|
||||
const resolved = await request('ua.resolve', { url });
|
||||
setResolution(resolved);
|
||||
onResolutionChange(resolved);
|
||||
await browser.tabs.reload(tab.id);
|
||||
}, selectedProfileId === BROWSER_DEFAULT ? '已恢复浏览器默认 UA 并刷新页面' : 'User-Agent 已应用并刷新页面');
|
||||
|
||||
const saveCustomAndApply = () => run(async () => {
|
||||
if (!tab || !url) throw new Error('当前页面不能修改 User-Agent');
|
||||
const profile = await request('ua.profile.save', { name: customName, userAgent: customValue });
|
||||
const next = await request('ua.site.apply', { url, profileId: profile.id });
|
||||
setState(next);
|
||||
setProfiles(await request('ua.catalog'));
|
||||
setSelectedProfileId(profile.id);
|
||||
const resolved = await request('ua.resolve', { url });
|
||||
setResolution(resolved);
|
||||
onResolutionChange(resolved);
|
||||
setCustomOpen(false);
|
||||
setCustomName('');
|
||||
setCustomValue('');
|
||||
await browser.tabs.reload(tab.id);
|
||||
}, '自定义 User-Agent 已保存、应用并刷新页面');
|
||||
|
||||
return <section className="popup-view popup-tool-view popup-ua-view">
|
||||
<div className="popup-tool-context"><UserRoundCog size={14} /><span>{resolution?.hostname || (url ? new URL(url).hostname : '当前页面不可访问')}</span><strong>{resolution?.mode === 'override' ? '已覆盖' : '默认'}</strong></div>
|
||||
<div className="popup-ua-current"><span>当前生效</span><strong>{resolution?.profile?.name || '浏览器默认'}</strong><code title={resolution?.userAgent}>{resolution?.userAgent || navigator.userAgent}</code><small>仅修改网络请求头,不等于完整设备指纹伪装。</small></div>
|
||||
{customOpen ? <div className="popup-ua-custom popup-view-enter"><div className="popup-editor-title"><div><strong>自定义 User-Agent</strong><span>保存为预设并应用到当前 hostname</span></div><Button size="icon" variant="ghost" aria-label="关闭自定义 UA" onClick={() => setCustomOpen(false)}><X size={15} /></Button></div><label><span>预设名称</span><input autoFocus value={customName} onChange={(event) => setCustomName(event.target.value)} placeholder="API Client" /></label><label><span>User-Agent</span><textarea rows={5} value={customValue} onChange={(event) => setCustomValue(event.target.value)} placeholder="Custom-Agent/1.0" /></label><Button variant="primary" disabled={busy || !customName.trim() || !customValue.trim()} onClick={() => void saveCustomAndApply()}><Save size={15} />保存、应用并刷新</Button></div> : <>
|
||||
<div className="popup-ua-list popup-view-enter" role="radiogroup" aria-label="User-Agent 预设">
|
||||
<button role="radio" aria-checked={selectedProfileId === BROWSER_DEFAULT} className={selectedProfileId === BROWSER_DEFAULT ? 'is-selected' : ''} onClick={() => setSelectedProfileId(BROWSER_DEFAULT)}><span className="popup-ua-icon"><RefreshCw size={15} /></span><span><strong>浏览器默认</strong><small>移除当前站点覆盖</small></span><i /></button>
|
||||
{profiles.map((profile) => <button role="radio" aria-checked={selectedProfileId === profile.id} className={selectedProfileId === profile.id ? 'is-selected' : ''} key={profile.id} onClick={() => setSelectedProfileId(profile.id)}><span className="popup-ua-icon">{categoryIcon(profile.category)}</span><span><strong>{profile.name}</strong><small>{profile.builtin ? profile.category === 'mobile' ? '移动设备模板' : profile.category === 'bot' ? '爬虫模板' : '桌面设备模板' : '自定义预设'}</small></span><i /></button>)}
|
||||
</div>
|
||||
{loadError && <div className="popup-inline-warning">{loadError}</div>}
|
||||
<div className="popup-ua-actions"><Button variant="ghost" disabled={!url || busy} onClick={() => setCustomOpen(true)}>自定义…</Button><Button variant="primary" disabled={!url || busy || selectedProfileId === (resolution?.profile?.id || BROWSER_DEFAULT)} onClick={() => void applyAndReload()}><RefreshCw size={15} />应用并刷新</Button></div>
|
||||
</>}
|
||||
</section>;
|
||||
}
|
||||