mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-05 22:12:31 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ba045c8e7 | ||
|
|
8b0b7706a3 | ||
|
|
fa34a5602e | ||
|
|
d14591b36a | ||
|
|
2bb7baebde | ||
|
|
aa597135b1 | ||
|
|
42b8e2f347 | ||
|
|
9c312b7b98 | ||
|
|
05e4bf69f7 |
No files matched your search
@@ -0,0 +1,72 @@
|
||||
name: Forward issue events to Grok Bot
|
||||
|
||||
on:
|
||||
issues:
|
||||
types: [opened, reopened, edited]
|
||||
issue_comment:
|
||||
types: [created, edited]
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
forward:
|
||||
# PR comments are handled elsewhere; only forward real issues.
|
||||
if: github.event_name == 'issues' || github.event.issue.pull_request == null
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 2
|
||||
steps:
|
||||
- name: Forward minimal event to Grok Bot webhook
|
||||
env:
|
||||
WEBHOOK_URL: ${{ secrets.GROKBOT_WEBHOOK_URL }}
|
||||
WEBHOOK_KEY: ${{ secrets.GROKBOT_WEBHOOK_KEY }}
|
||||
run: |
|
||||
if [ -z "$WEBHOOK_URL" ] || [ -z "$WEBHOOK_KEY" ]; then
|
||||
echo "Grok Bot webhook secrets not set; skipping."
|
||||
exit 0
|
||||
fi
|
||||
jq --arg event "$GITHUB_EVENT_NAME" '
|
||||
def clip:
|
||||
if type == "string" then .[0:4000] else . end;
|
||||
{
|
||||
event: $event,
|
||||
action: .action,
|
||||
repository: .repository.full_name,
|
||||
sender: .sender.login,
|
||||
issue: (
|
||||
{
|
||||
number: .issue.number,
|
||||
title: .issue.title,
|
||||
author: .issue.user.login,
|
||||
url: .issue.html_url
|
||||
} + (
|
||||
if $event == "issues" then {
|
||||
author_association: .issue.author_association,
|
||||
body: (.issue.body | clip)
|
||||
} else {} end
|
||||
)
|
||||
),
|
||||
comment: (
|
||||
if .comment then
|
||||
{
|
||||
id: .comment.id,
|
||||
author: .comment.user.login,
|
||||
url: .comment.html_url,
|
||||
node_id: .comment.node_id,
|
||||
author_association: .comment.author_association,
|
||||
user_type: .comment.user.type,
|
||||
created_at: .comment.created_at,
|
||||
updated_at: .comment.updated_at,
|
||||
body: (.comment.body | clip)
|
||||
} + (
|
||||
if .action == "edited" then {
|
||||
previous_body: (.changes.body.from | clip)
|
||||
} else {} end
|
||||
)
|
||||
else null end
|
||||
)
|
||||
}
|
||||
' "$GITHUB_EVENT_PATH" \
|
||||
| curl -fsS --max-time 20 -X POST \
|
||||
-H "Authorization: Bearer $WEBHOOK_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
--data @- "$WEBHOOK_URL"
|
||||
@@ -2,7 +2,7 @@ name: spam-comments
|
||||
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
types: [created, edited]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -10,13 +10,13 @@ permissions:
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
delete-spam:
|
||||
hide-spam:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout filter rules
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Delete suspected malware spam
|
||||
- name: Hide suspected malware spam
|
||||
uses: actions/github-script@v9
|
||||
with:
|
||||
script: |
|
||||
@@ -25,26 +25,59 @@ jobs:
|
||||
path.join(process.env.GITHUB_WORKSPACE, 'scripts/spam-comment-filter.cjs')
|
||||
);
|
||||
|
||||
const comment = context.payload.comment;
|
||||
const comment = context.payload.comment || {};
|
||||
const issue = context.payload.issue || {};
|
||||
const login = (comment.user && comment.user.login) || 'unknown';
|
||||
const result = detectSpamComment({
|
||||
body: comment.body || '',
|
||||
authorAssociation: comment.author_association,
|
||||
userType: comment.user && comment.user.type,
|
||||
commentAuthor: comment.user && comment.user.login,
|
||||
issueAuthor: issue.user && issue.user.login,
|
||||
});
|
||||
|
||||
core.info(JSON.stringify(result, null, 2));
|
||||
|
||||
if (!result.spam) {
|
||||
core.info('Comment did not match the zip/dangerous-file spam filter.');
|
||||
core.info('Comment did not match the risky-download spam filter.');
|
||||
return;
|
||||
}
|
||||
|
||||
await github.rest.issues.deleteComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
comment_id: comment.id,
|
||||
});
|
||||
const matchedUrl = result.matchedUrls.join(', ');
|
||||
if (!comment.node_id) {
|
||||
core.setFailed(
|
||||
`Comment ${comment.id} by @${login} on #${issue.number} matched ${matchedUrl} but has no node_id.`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await github.graphql(
|
||||
`mutation($input: MinimizeCommentInput!) {
|
||||
minimizeComment(input: $input) {
|
||||
minimizedComment {
|
||||
isMinimized
|
||||
}
|
||||
}
|
||||
}`,
|
||||
{
|
||||
input: {
|
||||
subjectId: comment.node_id,
|
||||
classifier: 'SPAM',
|
||||
},
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
const message = String((error && error.message) || error);
|
||||
if (/already minimized/i.test(message)) {
|
||||
core.info(
|
||||
`Comment ${comment.id} by @${login} on #${issue.number} is already minimized. Matched URL: ${matchedUrl}`
|
||||
);
|
||||
return;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
core.notice(
|
||||
`Deleted comment with zip/dangerous attachment by @${comment.user.login} on #${context.payload.issue.number}: ${result.reasons.join('; ')}`
|
||||
`Hid comment ${comment.id} by @${login} on #${issue.number} as spam. Matched URL: ${matchedUrl}`
|
||||
);
|
||||
@@ -0,0 +1,138 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import React from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
import { I18nProvider } from "../application/i18n/I18nProvider";
|
||||
import type { Host, PortForwardingRule, PortForwardingType } from "../domain/models";
|
||||
import { EditPanel } from "./port-forwarding/EditPanel";
|
||||
import { NewFormPanel } from "./port-forwarding/NewFormPanel";
|
||||
import { WizardContent } from "./port-forwarding/WizardContent";
|
||||
import { TooltipProvider } from "./ui/tooltip";
|
||||
|
||||
const baseHost: Omit<Host, "os"> = {
|
||||
id: "host-1",
|
||||
label: "Forwarding host",
|
||||
hostname: "example.com",
|
||||
username: "user",
|
||||
tags: [],
|
||||
};
|
||||
|
||||
const baseRule: PortForwardingRule = {
|
||||
id: "rule-1",
|
||||
label: "Test forwarding rule",
|
||||
type: "local",
|
||||
hostId: baseHost.id,
|
||||
localPort: 8080,
|
||||
bindAddress: "127.0.0.1",
|
||||
remoteHost: "localhost",
|
||||
remotePort: 80,
|
||||
status: "inactive",
|
||||
createdAt: 1,
|
||||
};
|
||||
|
||||
const noop = () => undefined;
|
||||
const panelRenderers = {
|
||||
edit: (hosts: Host[], draft: PortForwardingRule) => (
|
||||
<EditPanel
|
||||
rule={draft}
|
||||
draft={draft}
|
||||
hosts={hosts}
|
||||
onDraftChange={noop}
|
||||
onSave={noop}
|
||||
onClose={noop}
|
||||
onDuplicate={noop}
|
||||
onDelete={noop}
|
||||
onOpenHostSelector={noop}
|
||||
/>
|
||||
),
|
||||
new: (hosts: Host[], draft: PortForwardingRule) => (
|
||||
<NewFormPanel
|
||||
draft={draft}
|
||||
hosts={hosts}
|
||||
onDraftChange={noop}
|
||||
onSave={noop}
|
||||
onClose={noop}
|
||||
onOpenHostSelector={noop}
|
||||
onOpenWizard={noop}
|
||||
isValid={false}
|
||||
/>
|
||||
),
|
||||
"remote-host-selection": (hosts: Host[], draft: PortForwardingRule) => (
|
||||
<WizardContent
|
||||
step="remote-host-selection"
|
||||
type={draft.type}
|
||||
draft={draft}
|
||||
hosts={hosts}
|
||||
onTypeChange={noop}
|
||||
onDraftChange={noop}
|
||||
onOpenHostSelector={noop}
|
||||
/>
|
||||
),
|
||||
"host-selection": (hosts: Host[], draft: PortForwardingRule) => (
|
||||
<WizardContent
|
||||
step="host-selection"
|
||||
type={draft.type}
|
||||
draft={draft}
|
||||
hosts={hosts}
|
||||
onTypeChange={noop}
|
||||
onDraftChange={noop}
|
||||
onOpenHostSelector={noop}
|
||||
/>
|
||||
),
|
||||
};
|
||||
|
||||
const hostCases: { name: string; fields: { os?: Host["os"] | "" | null } }[] = [
|
||||
{ name: "missing OS", fields: {} },
|
||||
{ name: "undefined OS", fields: { os: undefined } },
|
||||
{ name: "null OS", fields: { os: null } },
|
||||
{ name: "empty OS", fields: { os: "" } },
|
||||
{ name: "Linux", fields: { os: "linux" } },
|
||||
{ name: "Windows", fields: { os: "windows" } },
|
||||
{ name: "macOS", fields: { os: "macos" } },
|
||||
];
|
||||
|
||||
function render(panel: React.ReactNode): string {
|
||||
return renderToStaticMarkup(
|
||||
<I18nProvider locale="en">
|
||||
<TooltipProvider>{panel}</TooltipProvider>
|
||||
</I18nProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
for (const [panelName, renderPanel] of Object.entries(panelRenderers)) {
|
||||
for (const type of ["local", "remote", "dynamic"] as PortForwardingType[]) {
|
||||
for (const { name, fields } of hostCases) {
|
||||
test(`${panelName} renders ${type} forwarding with ${name}`, () => {
|
||||
// Persisted legacy records can violate the required Host.os type at runtime.
|
||||
const host = { ...baseHost, ...fields } as unknown as Host;
|
||||
const markup = render(renderPanel([host], { ...baseRule, type }));
|
||||
|
||||
assert.match(markup, /Forwarding host/);
|
||||
assert.match(markup, /lucide-server/);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
test(`${panelName} preserves the selected host's distro icon`, () => {
|
||||
const host: Host = { ...baseHost, os: "linux", distro: "ubuntu" };
|
||||
const markup = render(renderPanel([host], baseRule));
|
||||
|
||||
assert.match(markup, /Forwarding host/);
|
||||
assert.match(markup, /src="\/distro\/ubuntu\.svg"/);
|
||||
});
|
||||
|
||||
test(`${panelName} renders the host picker when no host is selected`, () => {
|
||||
const markup = render(renderPanel([], { ...baseRule, hostId: undefined }));
|
||||
|
||||
assert.match(markup, /Select a host/);
|
||||
assert.doesNotMatch(markup, /Forwarding host/);
|
||||
});
|
||||
|
||||
test(`${panelName} renders the host picker when the selected host is unavailable`, () => {
|
||||
const markup = render(renderPanel([], baseRule));
|
||||
|
||||
assert.match(markup, /Select a host/);
|
||||
assert.doesNotMatch(markup, /Forwarding host/);
|
||||
});
|
||||
}
|
||||
@@ -134,7 +134,7 @@ export const EditPanel: React.FC<EditPanelProps> = ({
|
||||
<div className="flex items-center gap-2">
|
||||
<DistroAvatar
|
||||
host={selectedHost}
|
||||
fallback={selectedHost.os[0].toUpperCase()}
|
||||
fallback={(selectedHost.os || 'unknown').charAt(0).toUpperCase()}
|
||||
size="tree"
|
||||
/>
|
||||
<span>{selectedHost.label}</span>
|
||||
|
||||
@@ -134,7 +134,7 @@ export const NewFormPanel: React.FC<NewFormPanelProps> = ({
|
||||
<div className="flex items-center gap-2">
|
||||
<DistroAvatar
|
||||
host={selectedHost}
|
||||
fallback={selectedHost.os[0].toUpperCase()}
|
||||
fallback={(selectedHost.os || 'unknown').charAt(0).toUpperCase()}
|
||||
size="tree"
|
||||
/>
|
||||
<span>{selectedHost.label}</span>
|
||||
|
||||
@@ -123,7 +123,11 @@ export const WizardContent: React.FC<WizardContentProps> = ({
|
||||
>
|
||||
{selectedHost ? (
|
||||
<div className="flex items-center gap-2 w-full">
|
||||
<DistroAvatar host={selectedHost} fallback={selectedHost.os[0].toUpperCase()} size="sm" />
|
||||
<DistroAvatar
|
||||
host={selectedHost}
|
||||
fallback={(selectedHost.os || 'unknown').charAt(0).toUpperCase()}
|
||||
size="sm"
|
||||
/>
|
||||
<span>{selectedHost.label}</span>
|
||||
<Check size={14} className="ml-auto" />
|
||||
</div>
|
||||
@@ -228,7 +232,11 @@ export const WizardContent: React.FC<WizardContentProps> = ({
|
||||
>
|
||||
{selectedHost ? (
|
||||
<div className="flex items-center gap-2 w-full">
|
||||
<DistroAvatar host={selectedHost} fallback={selectedHost.os[0].toUpperCase()} size="sm" />
|
||||
<DistroAvatar
|
||||
host={selectedHost}
|
||||
fallback={(selectedHost.os || 'unknown').charAt(0).toUpperCase()}
|
||||
size="sm"
|
||||
/>
|
||||
<span>{selectedHost.label}</span>
|
||||
<Check size={14} className="ml-auto" />
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
# Agent Note: Keep port forwarding usable when host OS metadata is missing
|
||||
|
||||
Status: implemented
|
||||
|
||||
## Problem
|
||||
|
||||
[Issue #3748](https://github.com/binaricat/Netcatty/issues/3748) reports that the
|
||||
port-forwarding page displays `Port forwarding could not load.` when rendering
|
||||
a selected host whose legacy `os` value is absent, null, or an empty string.
|
||||
|
||||
`EditPanel`, `NewFormPanel`, and both host-selection steps in `WizardContent`
|
||||
evaluate `selectedHost.os[0].toUpperCase()` while constructing `DistroAvatar`
|
||||
props. Missing or null values fail on indexing; an empty string fails on
|
||||
`toUpperCase`. This happens before the avatar can render its generic icon.
|
||||
Although `Host.os` is required by TypeScript, persisted runtime records can lack
|
||||
that metadata. The original source of the affected records is not established.
|
||||
|
||||
## Decision
|
||||
|
||||
The four call sites use `(selectedHost.os || 'unknown').charAt(0).toUpperCase()`
|
||||
to keep the required string fallback safe without changing the shared avatar
|
||||
API. Valid OS values retain their existing initials. Missing and empty values
|
||||
use the explicit unknown fallback, and the avatar keeps its existing generic
|
||||
icon behavior.
|
||||
|
||||
The fix stays in the affected presentation code. It does not change host data,
|
||||
normalization, persistence, or tunnel lifecycle behavior. A shared helper for a
|
||||
single short expression would add indirection without a separate responsibility,
|
||||
so the four call sites use the same expression directly.
|
||||
|
||||
## Validation
|
||||
|
||||
`components/PortForwardingPanels.test.tsx` renders the real components with
|
||||
`react-dom/server`, the existing i18n provider, and the tooltip provider. It does
|
||||
not mock the panels or avatar and does not inspect their source text.
|
||||
|
||||
The table-driven cases cover all four entry points, all three forwarding types,
|
||||
and missing, undefined, null, empty, Linux, Windows, and macOS values. Separate
|
||||
checks preserve distro icons and host-picker behavior when no host is selected
|
||||
or the selected host is no longer available. Invalid legacy fixture shapes use
|
||||
one explicit type assertion rather than weakening the production `Host` type.
|
||||
|
||||
Before the fix, 48 of the 96 new cases fail with the reported TypeError; the
|
||||
other 48 pass. After the fix, all 96 pass. Together with the existing avatar,
|
||||
port-forwarding toolbar, and utility tests, the focused run passes 109 tests:
|
||||
|
||||
```sh
|
||||
node --test --import tsx components/PortForwardingPanels.test.tsx \
|
||||
components/PortForwardingNew.test.ts components/portForwardingUtils.test.ts \
|
||||
components/DistroAvatar.test.tsx --test-concurrency=2
|
||||
```
|
||||
|
||||
These are rendering regression tests, not SSH or network end-to-end tests.
|
||||
|
||||
Additional checks against upstream commit `786a317`:
|
||||
|
||||
- `npm run build` succeeds.
|
||||
- `npm run lint` succeeds with the same eight existing warnings as upstream.
|
||||
The four changed TypeScript/TSX files also pass lint with `--max-warnings=0`.
|
||||
- `LC_ALL=C npm test -- --test-concurrency=1` runs 13,986 tests: 13,944 pass,
|
||||
four fail, and 38 are skipped. An unmodified upstream worktree runs 13,890
|
||||
tests with the same four failures and 38 skips, so this change adds 96 passing
|
||||
cases without adding a failing case. The baseline failures are the SFTP
|
||||
large-directory persistence timing test, two Bash OSC 7 setup tests, and the
|
||||
README clipboard-paste screenshot-dimension assertion. The SFTP timing test
|
||||
passes in isolated runs on both checkouts but fails in these full-suite runs.
|
||||
A non-English locale additionally causes the existing fish error-message
|
||||
assertion to fail; both comparison runs use the C locale.
|
||||
- The full-project `tsc --noEmit --pretty false` check has 759 existing errors.
|
||||
Its complete output matches the unmodified upstream output after normalizing
|
||||
checkout paths; none of the changed files has a diagnostic. This is not a
|
||||
claim that full-project type checking passes.
|
||||
|
||||
### Upstream CI follow-up
|
||||
|
||||
The original PR CI run [39215269619, attempt 2](https://github.com/binaricat/Netcatty/actions/runs/39215269619/attempts/2)
|
||||
passes all 96 new regression cases and fails only the existing README paste
|
||||
assertion. Upstream commit `b366967` fixes that assertion by removing its
|
||||
coupling to changing screenshot dimensions. The branch incorporates this fix
|
||||
through a normal merge of upstream `main` at `42b8e2f`, without rewriting the
|
||||
original fix commit or adding an independent change to the unrelated test.
|
||||
|
||||
After synchronization, the focused run including the entire clipboard-paste
|
||||
test file passes 149 tests. Lint and the production build also pass; lint keeps
|
||||
the same eight existing warnings. The earlier full-suite and type-check
|
||||
comparison above describes the original `786a317` baseline, not the updated
|
||||
base. Current remote CI results are tracked on the PR.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
- Remove the unused fallback prop from the four calls: the shared avatar still
|
||||
requires it in its TypeScript contract. Changing that API and cleaning up all
|
||||
callers is unnecessary for this targeted bug fix.
|
||||
- Normalize or rewrite stored host records: broadens the persistence scope,
|
||||
obscures the rendering assumption, and cannot replace guarding optional
|
||||
runtime metadata at the point of use.
|
||||
- Add a new avatar wrapper or fallback utility: unnecessary for this small
|
||||
expression and would expand the production change without improving the
|
||||
boundary being fixed.
|
||||
|
||||
## Consequences
|
||||
|
||||
Incomplete host OS metadata no longer prevents new/edit panels or wizard
|
||||
host-selection steps from rendering. Existing icons, component contracts, and
|
||||
host records remain unchanged. The guard is local to port forwarding; auditing
|
||||
unrelated callers or redesigning the unused fallback API remains out of scope.
|
||||
@@ -5,6 +5,12 @@ const { StringDecoder } = require("node:string_decoder");
|
||||
const DEFAULT_CODEX_CLI_TIMEOUT_MS = 10_000;
|
||||
const CODEX_AUTH_VALIDATION_TIMEOUT_MS = 10_000;
|
||||
const MAX_AGENT_CLI_BUFFER_CHARS = 10 * 1024 * 1024;
|
||||
// Bun-compiled OpenCode-family CLIs start slowly: `mimo --version` takes
|
||||
// 3.9–5.1s warm (6s+ cold) and `opencode --version` can exceed 5s on a cold
|
||||
// cache, so a 5s timeout killed healthy CLIs and dropped them from discovery.
|
||||
// 15s only affects CLIs that exist but are slow to answer — a missing command
|
||||
// fails spawn immediately.
|
||||
const VERSION_PROBE_TIMEOUT_MS = 15_000;
|
||||
|
||||
function createAgentCliHelpers(ctx) {
|
||||
with (ctx) {
|
||||
@@ -120,7 +126,7 @@ function createAgentCliHelpers(ctx) {
|
||||
|
||||
async function probeCliVersion(probeCmd, probeArgs, env) {
|
||||
try {
|
||||
const result = await runCommand(probeCmd, probeArgs, { env, timeoutMs: 5000 });
|
||||
const result = await runCommand(probeCmd, probeArgs, { env, timeoutMs: VERSION_PROBE_TIMEOUT_MS });
|
||||
return {
|
||||
launched: true,
|
||||
exitCode: result.exitCode,
|
||||
@@ -430,4 +436,5 @@ module.exports = {
|
||||
CODEX_AUTH_VALIDATION_TIMEOUT_MS,
|
||||
DEFAULT_CODEX_CLI_TIMEOUT_MS,
|
||||
MAX_AGENT_CLI_BUFFER_CHARS,
|
||||
VERSION_PROBE_TIMEOUT_MS,
|
||||
};
|
||||
@@ -10,6 +10,7 @@ const {
|
||||
CODEX_AUTH_VALIDATION_TIMEOUT_MS,
|
||||
DEFAULT_CODEX_CLI_TIMEOUT_MS,
|
||||
MAX_AGENT_CLI_BUFFER_CHARS,
|
||||
VERSION_PROBE_TIMEOUT_MS,
|
||||
} = require("./agentCliHelpers.cjs");
|
||||
|
||||
function createHungChild() {
|
||||
@@ -55,6 +56,37 @@ test("runCodexCli applies a default timeout to short status commands", async ()
|
||||
assert.deepEqual(child.kills, ["SIGTERM", "SIGKILL"]);
|
||||
});
|
||||
|
||||
test("probeCliVersion allows slow-starting CLIs beyond the old 5s probe limit", async () => {
|
||||
const child = createHungChild();
|
||||
const scheduled = [];
|
||||
const helpers = createAgentCliHelpers({
|
||||
prepareCommandForSpawn: (command, args) => ({ command, args, shell: false }),
|
||||
spawn: () => {
|
||||
queueMicrotask(() => {
|
||||
child.stdout.emit("data", Buffer.from("0.1.15\n"));
|
||||
child.emit("close", 0);
|
||||
});
|
||||
return child;
|
||||
},
|
||||
stripAnsi: (value) => value,
|
||||
getShellEnv: async () => ({}),
|
||||
normalizeCliPathForPlatform: (value) => value,
|
||||
resolveCliFromPathAsync: async () => "/fake/mimo",
|
||||
setTimeout: (callback, delay) => {
|
||||
scheduled.push(delay);
|
||||
return { unref() {} };
|
||||
},
|
||||
clearTimeout() {},
|
||||
});
|
||||
|
||||
const result = await helpers.probeCliVersion("/fake/mimo", ["--version"], {});
|
||||
assert.equal(result.launched, true);
|
||||
assert.equal(result.exitCode, 0);
|
||||
assert.equal(result.version, "0.1.15");
|
||||
assert.equal(scheduled[0], VERSION_PROBE_TIMEOUT_MS);
|
||||
assert.ok(scheduled[0] > 5000, "version probe timeout must exceed 5s for bun-compiled OpenCode-family CLIs");
|
||||
});
|
||||
|
||||
test("runCodexCli slices a single oversized output chunk to the hard limit", async () => {
|
||||
const child = createHungChild();
|
||||
const helpers = createAgentCliHelpers({
|
||||
|
||||
+2
-1
@@ -42,7 +42,7 @@
|
||||
"pack:linux": "npm run build && cross-env NODE_OPTIONS=--disable-warning=DEP0190 electron-builder --config electron-builder.config.cjs --linux --publish=never",
|
||||
"pack:linux-x64": "npm run build && cross-env npm_config_arch=x64 NODE_OPTIONS=--disable-warning=DEP0190 electron-builder --config electron-builder.config.cjs --linux --x64 --publish=never",
|
||||
"pack:linux-arm64": "npm run build && cross-env npm_config_arch=arm64 NODE_OPTIONS=--disable-warning=DEP0190 electron-builder --config electron-builder.config.cjs --linux --arm64 --publish=never",
|
||||
"postinstall": "patch-package && node scripts/patch-xterm-macos-column-selection.cjs && node scripts/patch-xterm-foreground-intense.cjs && electron-builder install-app-deps && node scripts/rebuildPatchedNodePty.cjs && node scripts/patch-xterm-webgl-atlas.cjs",
|
||||
"postinstall": "patch-package && node scripts/patch-xterm-macos-column-selection.cjs && node scripts/patch-xterm-foreground-intense.cjs && node scripts/patch-xterm-image-tile-stride.cjs && electron-builder install-app-deps && node scripts/rebuildPatchedNodePty.cjs && node scripts/patch-xterm-webgl-atlas.cjs",
|
||||
"rebuild": "electron-builder install-app-deps",
|
||||
"tool:cli": "node electron/cli/netcatty-tool-cli.cjs",
|
||||
"generate:capability-tools": "node scripts/generate-capability-tools.cjs",
|
||||
@@ -68,6 +68,7 @@
|
||||
"test:ssh-mfa-models:live": "SSH_MFA_LIVE=1 node --test electron/bridges/sshMfaModels.live.test.cjs",
|
||||
"test:local-file-drag:electron": "electron scripts/local-file-drag.live.test.cjs",
|
||||
"test:tray-panel-layout": "electron scripts/tray-panel-layout.live.test.cjs",
|
||||
"test:xterm-image-resize": "electron scripts/xterm-image-resize.live.test.cjs",
|
||||
"test:xterm-foreground-intense": "electron scripts/xterm-foreground-intense.live.test.cjs",
|
||||
"test:terminal-background-rendering": "electron scripts/terminal-background-rendering.live.test.cjs",
|
||||
"test:xterm-webgl-overflow": "electron scripts/xterm-webgl-atlas-overflow.live.test.cjs",
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
#!/usr/bin/env node
|
||||
/* global process, console */
|
||||
"use strict";
|
||||
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
|
||||
const EXPECTED_VERSION = "0.10.0-beta.292";
|
||||
|
||||
// ImageStorage.addImage assigns tile IDs using ceil(orig.width/origCellSize.width).
|
||||
// Keep that stride for draw, extractTile and viewportResize. Recomputing it from
|
||||
// the rescaled canvas can add a column: ceil(400 * 9.51 / 10) / 9.51 > 40.
|
||||
// DOM cell widths can change fractionally on window resize, shifting each image
|
||||
// row one more tile and producing diagonal corruption (Netcatty #3746).
|
||||
// Local pinned-version workaround pending an upstream release, not a merged
|
||||
// upstream backport. The open draft uses the same original-grid principle:
|
||||
// https://github.com/xtermjs/xterm.js/issues/5861
|
||||
// https://github.com/xtermjs/xterm.js/pull/6145
|
||||
// Patch both runtime bundles using the existing install-time patch pattern.
|
||||
const PATCHES = [
|
||||
{
|
||||
file: "lib/addon-image.js",
|
||||
original: "const n=e.actual,h=Math.ceil(n.width/o),",
|
||||
replacement: "const n=e.actual,h=Math.ceil(e.orig.width/e.origCellSize.width),",
|
||||
},
|
||||
{
|
||||
file: "lib/addon-image.js",
|
||||
original: "const s=e.actual,o=Math.ceil(s.width/A),",
|
||||
replacement: "const s=e.actual,o=Math.ceil(e.orig.width/e.origCellSize.width),",
|
||||
},
|
||||
{
|
||||
file: "lib/addon-image.js",
|
||||
original: "const h=Math.ceil(((null===(t=n.actual)||void 0===t?void 0:t.width)||0)/n.actualCellSize.width);",
|
||||
replacement: "const h=Math.ceil(((null===(t=n.orig)||void 0===t?void 0:t.width)||0)/n.origCellSize.width);",
|
||||
},
|
||||
{
|
||||
file: "lib/addon-image.mjs",
|
||||
original: "let h=t.actual,g=Math.ceil(h.width/o),",
|
||||
replacement: "let h=t.actual,g=Math.ceil(t.orig.width/t.origCellSize.width),",
|
||||
},
|
||||
{
|
||||
file: "lib/addon-image.mjs",
|
||||
original: "let a=t.actual,n=Math.ceil(a.width/A),",
|
||||
replacement: "let a=t.actual,n=Math.ceil(t.orig.width/t.origCellSize.width),",
|
||||
},
|
||||
{
|
||||
file: "lib/addon-image.mjs",
|
||||
original: "let h=Math.ceil((d.actual?.width||0)/d.actualCellSize.width);",
|
||||
replacement: "let h=Math.ceil((d.orig?.width||0)/d.origCellSize.width);",
|
||||
},
|
||||
];
|
||||
|
||||
function patchImageSource(source, patch) {
|
||||
const originalCount = source.split(patch.original).length - 1;
|
||||
const patchedCount = source.split(patch.replacement).length - 1;
|
||||
if (originalCount === 1 && patchedCount === 0) {
|
||||
return { source: source.replace(patch.original, patch.replacement), changed: true };
|
||||
}
|
||||
if (originalCount === 0 && patchedCount === 1) return { source, changed: false };
|
||||
throw new Error(
|
||||
`${patch.file}: unexpected image-tile-stride patch shape ` +
|
||||
`(original=${originalCount}, patched=${patchedCount})`,
|
||||
);
|
||||
}
|
||||
|
||||
function patchInstalledImage(root = process.cwd()) {
|
||||
const base = path.resolve(root, "node_modules/@xterm/addon-image");
|
||||
const version = JSON.parse(fs.readFileSync(path.join(base, "package.json"), "utf8")).version;
|
||||
if (version !== EXPECTED_VERSION) {
|
||||
throw new Error(`unsupported @xterm/addon-image version ${version}; expected ${EXPECTED_VERSION}`);
|
||||
}
|
||||
// Validate both complete bundles before writing either one.
|
||||
const files = new Map();
|
||||
let changed = 0;
|
||||
for (const patch of PATCHES) {
|
||||
const source = files.get(patch.file) ?? fs.readFileSync(path.join(base, patch.file), "utf8");
|
||||
const result = patchImageSource(source, patch);
|
||||
files.set(patch.file, result.source);
|
||||
if (result.changed) changed++;
|
||||
}
|
||||
if (changed) {
|
||||
for (const [file, source] of files) fs.writeFileSync(path.join(base, file), source);
|
||||
fs.rmSync(path.resolve(root, "node_modules/.vite"), { recursive: true, force: true });
|
||||
}
|
||||
return { changed, checked: PATCHES.length };
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
try {
|
||||
const result = patchInstalledImage();
|
||||
console.log(`[patch-xterm-image-tile-stride] changed=${result.changed} checked=${result.checked}`);
|
||||
} catch (error) {
|
||||
console.error(`[patch-xterm-image-tile-stride] ERROR: ${error.message}`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { EXPECTED_VERSION, PATCHES, patchImageSource, patchInstalledImage };
|
||||
@@ -0,0 +1,148 @@
|
||||
"use strict";
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const os = require("node:os");
|
||||
const path = require("node:path");
|
||||
const test = require("node:test");
|
||||
const { pathToFileURL } = require("node:url");
|
||||
const { EXPECTED_VERSION, PATCHES, patchImageSource, patchInstalledImage } = require("./patch-xterm-image-tile-stride.cjs");
|
||||
|
||||
for (const patch of PATCHES) {
|
||||
test(`${patch.file}: ${patch.original.slice(0, 24)} patches once and rejects drift`, () => {
|
||||
const first = patchImageSource(`before;${patch.original}after`, patch);
|
||||
assert.equal(first.changed, true);
|
||||
assert.equal(first.source, `before;${patch.replacement}after`);
|
||||
assert.deepEqual(patchImageSource(first.source, patch), { source: first.source, changed: false });
|
||||
for (const source of ["upstream changed", patch.original.repeat(2), patch.replacement.repeat(2), patch.original + patch.replacement]) {
|
||||
assert.throws(() => patchImageSource(source, patch), /unexpected image-tile-stride patch shape/);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function fixture(t) {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-image-stride-"));
|
||||
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
|
||||
const base = path.join(root, "node_modules/@xterm/addon-image");
|
||||
fs.mkdirSync(path.join(base, "lib"), { recursive: true });
|
||||
fs.writeFileSync(path.join(base, "package.json"), JSON.stringify({ version: EXPECTED_VERSION }));
|
||||
for (const file of new Set(PATCHES.map(p => p.file))) {
|
||||
fs.writeFileSync(path.join(base, file), PATCHES.filter(p => p.file === file).map(p => p.original).join("\n"));
|
||||
}
|
||||
return { root, base };
|
||||
}
|
||||
|
||||
test("install patches both bundles, invalidates Vite cache and is idempotent", t => {
|
||||
const { root, base } = fixture(t);
|
||||
const cache = path.join(root, "node_modules/.vite");
|
||||
fs.mkdirSync(cache);
|
||||
assert.deepEqual(patchInstalledImage(root), { changed: 6, checked: 6 });
|
||||
assert.equal(fs.existsSync(cache), false);
|
||||
for (const patch of PATCHES) assert.ok(fs.readFileSync(path.join(base, patch.file), "utf8").includes(patch.replacement));
|
||||
assert.deepEqual(patchInstalledImage(root), { changed: 0, checked: 6 });
|
||||
});
|
||||
|
||||
test("install fails closed on a changed version or bundle before writing anything", t => {
|
||||
const { root, base } = fixture(t);
|
||||
const cjs = path.join(base, "lib/addon-image.js");
|
||||
const original = fs.readFileSync(cjs, "utf8");
|
||||
fs.writeFileSync(path.join(base, "package.json"), JSON.stringify({ version: "future" }));
|
||||
assert.throws(() => patchInstalledImage(root), /unsupported @xterm\/addon-image version/);
|
||||
assert.equal(fs.readFileSync(cjs, "utf8"), original);
|
||||
fs.writeFileSync(path.join(base, "package.json"), JSON.stringify({ version: EXPECTED_VERSION }));
|
||||
fs.writeFileSync(path.join(base, "lib/addon-image.mjs"), "upstream changed");
|
||||
assert.throws(() => patchInstalledImage(root), /unexpected image-tile-stride patch shape/);
|
||||
assert.equal(fs.readFileSync(cjs, "utf8"), original);
|
||||
});
|
||||
|
||||
// Exercise the installed addon itself, not a copy of its stride expression.
|
||||
// Canvas calls are captured so these regressions also run in the normal Node suite.
|
||||
function canvas(width, height) {
|
||||
const calls = [];
|
||||
const element = { width, height, calls, remove() {} };
|
||||
element.getContext = () => ({ canvas: element, drawImage: (...args) => calls.push(args), clearRect() {} });
|
||||
return element;
|
||||
}
|
||||
|
||||
function setup(ImageAddon, { imageWidth = 400, cellWidth = 10, cols = 80, layer = "top" } = {}) {
|
||||
const event = () => ({ dispose() {} });
|
||||
const lines = Array.from({ length: 24 }, () => ({
|
||||
_data: new Uint32Array(100 * 3), _extendedAttrs: {},
|
||||
getBg(x) { return this._data[x * 3 + 2]; },
|
||||
}));
|
||||
const cell = { width: cellWidth, height: 20 };
|
||||
const buffer = { x: 0, y: 0, ybase: 0, lines: { get: y => lines[y], length: lines.length } };
|
||||
const term = {
|
||||
cols, rows: 24, dimensions: { css: { cell } },
|
||||
_core: {
|
||||
open() {}, buffer,
|
||||
_coreBrowserService: { window: { document: { createElement: () => canvas(0, 0) } } },
|
||||
optionsService: { onOptionChange: event },
|
||||
_inputHandler: { onRequestReset: event, _dirtyRowTracker: { markDirty() {} }, lineFeed: () => buffer.y++ },
|
||||
},
|
||||
parser: { registerCsiHandler: event, registerEscHandler: event },
|
||||
buffer: { active: { type: "normal" }, onBufferChange: event },
|
||||
onRender: event, onResize: event,
|
||||
registerMarker: () => ({ onDispose() {}, dispose() {} }),
|
||||
};
|
||||
const addon = new ImageAddon({ enableSizeReports: false, sixelSupport: false, iipSupport: false, kittySupport: false });
|
||||
addon.activate(term);
|
||||
const image = canvas(imageWidth, 400);
|
||||
const imageId = addon._storage.addImage(image, { scrolling: true, layer, zIndex: 0, cursorPos: "vt340" });
|
||||
const spec = addon._storage._images.get(imageId);
|
||||
const output = canvas(1000, 480);
|
||||
addon._renderer._layers.set(layer, output.getContext("2d"));
|
||||
return { addon, cell, spec, output, lines };
|
||||
}
|
||||
|
||||
for (const format of ["js", "mjs"]) {
|
||||
const loadAddon = async () => {
|
||||
const file = path.resolve(__dirname, `../node_modules/@xterm/addon-image/lib/addon-image.${format}`);
|
||||
return format === "js" ? require(file) : import(pathToFileURL(file).href);
|
||||
};
|
||||
for (const layer of ["top", "bottom"]) {
|
||||
test(`${format}: ${layer} image rows and extracted tiles keep their original stride through repeated resizes`, async () => {
|
||||
const { ImageAddon } = await loadAddon();
|
||||
for (const options of [{}, { imageWidth: 397 }, { imageWidth: 384, cellWidth: 9.6 }]) {
|
||||
const { addon, cell, spec, output, lines } = setup(ImageAddon, { ...options, layer });
|
||||
const stride = Math.ceil(spec.orig.width / spec.origCellSize.width);
|
||||
assert.equal(stride, 40);
|
||||
assert.equal(lines[1]._extendedAttrs[0].tileId, stride);
|
||||
const originalWidth = cell.width;
|
||||
for (const width of [originalWidth, 9.51, 10.02, 12, 8.73, originalWidth]) {
|
||||
cell.width = width;
|
||||
for (const tileId of [40, 41, 79, 80, 799]) {
|
||||
addon._renderer.draw(spec, tileId, 3, 2);
|
||||
const [, sx, sy, , , dx, dy] = output.calls.at(-1);
|
||||
assert.equal(sx, Math.floor((tileId % stride) * width), `draw x: tile=${tileId}, width=${width}`);
|
||||
assert.equal(sy, Math.floor(tileId / stride) * cell.height, `draw y: tile=${tileId}, width=${width}`);
|
||||
assert.equal(dx, Math.floor(3 * width));
|
||||
assert.equal(dy, 2 * cell.height);
|
||||
const tile = addon._renderer.extractTile(spec, tileId);
|
||||
assert.equal(tile.calls[0][1], sx, "extractTile uses the same source column as draw");
|
||||
assert.equal(tile.calls[0][2], sy, "extractTile uses the same source row as draw");
|
||||
}
|
||||
addon._renderer.draw(spec, stride, 0, 1, stride);
|
||||
assert.equal(output.calls.at(-1)[1], 0, "batched second row starts at the left edge");
|
||||
assert.equal(output.calls.at(-1)[2], cell.height);
|
||||
}
|
||||
assert.equal(spec.actual, spec.orig, "restoring cell metrics restores the original image");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test(`${format}: viewport growth after rescaling does not append the next image row`, async () => {
|
||||
const { ImageAddon } = await loadAddon();
|
||||
for (const cols of [20, 40]) {
|
||||
const { addon, cell, spec, lines } = setup(ImageAddon, { cols });
|
||||
cell.width = 9.51;
|
||||
addon._renderer.draw(spec, 0, 0, 0);
|
||||
assert.equal(spec.actual.width, 381, "rescaled integer canvas would incorrectly imply 41 columns");
|
||||
addon._storage.viewportResize({ cols: 50, rows: 24 });
|
||||
for (let row = 0; row < 20; row++) {
|
||||
for (let col = 0; col < 40; col++) assert.equal(lines[row]._extendedAttrs[col].tileId, row * 40 + col);
|
||||
assert.equal(lines[row]._extendedAttrs[40], undefined, "must stop at the original row boundary");
|
||||
}
|
||||
assert.equal(spec.tileCount, 800);
|
||||
}
|
||||
});
|
||||
}
|
||||
+103
-50
@@ -6,21 +6,32 @@ const TRUSTED_AUTHOR_ASSOCIATIONS = new Set([
|
||||
"COLLABORATOR",
|
||||
]);
|
||||
|
||||
const DANGEROUS_FILE_EXTENSION =
|
||||
"(?:zip|7z|rar|tar\\.gz|tgz|exe|msi|dmg|pkg|deb|rpm|appimage|bat|cmd|ps1|scr|vbs)";
|
||||
const RISKY_EXTENSIONS = [
|
||||
".tar.gz",
|
||||
".tar.xz",
|
||||
".appimage",
|
||||
".msix",
|
||||
".zip",
|
||||
".7z",
|
||||
".rar",
|
||||
".tgz",
|
||||
".exe",
|
||||
".msi",
|
||||
".dmg",
|
||||
".pkg",
|
||||
".deb",
|
||||
".rpm",
|
||||
".bat",
|
||||
".cmd",
|
||||
".ps1",
|
||||
".scr",
|
||||
".vbs",
|
||||
".jar",
|
||||
".iso",
|
||||
".lnk",
|
||||
];
|
||||
|
||||
const dangerousFilePattern = new RegExp(
|
||||
`(?:^|[\\s([<"'=])([^\\s()[\\]<>\"']+\\.${DANGEROUS_FILE_EXTENSION})(?=$|[\\s)\\]>\"']|[.,!?;:](?:$|\\s))`,
|
||||
"gi"
|
||||
);
|
||||
|
||||
const zipFilePattern = new RegExp(
|
||||
`(?:^|[\\s([<"'=])([^\\s()[\\]<>\"']+\\.zip)(?=$|[\\s)\\]>\"']|[.,!?;:](?:$|\\s))`,
|
||||
"gi"
|
||||
);
|
||||
|
||||
const githubUserAttachmentPattern =
|
||||
/^https:\/\/github\.com\/user-attachments\/files\/\d+\//i;
|
||||
const URL_PATTERN = /https?:\/\/[^\s<>"'`]+/gi;
|
||||
|
||||
function normalizeAssociation(authorAssociation) {
|
||||
return String(authorAssociation || "").trim().toUpperCase();
|
||||
@@ -30,65 +41,107 @@ function isTrustedAuthor(authorAssociation) {
|
||||
return TRUSTED_AUTHOR_ASSOCIATIONS.has(normalizeAssociation(authorAssociation));
|
||||
}
|
||||
|
||||
function extractMatches(body, pattern) {
|
||||
const files = [];
|
||||
for (const match of body.matchAll(pattern)) {
|
||||
files.push(match[1]);
|
||||
function isSameLogin(left, right) {
|
||||
const a = String(left || "").trim().toLowerCase();
|
||||
const b = String(right || "").trim().toLowerCase();
|
||||
return a.length > 0 && a === b;
|
||||
}
|
||||
|
||||
function trimUrlCandidate(raw) {
|
||||
let value = String(raw || "");
|
||||
while (value.length > 0) {
|
||||
const last = value[value.length - 1];
|
||||
if (".,;:!?\"']".includes(last)) {
|
||||
value = value.slice(0, -1);
|
||||
continue;
|
||||
}
|
||||
if (last === ")") {
|
||||
const opens = (value.match(/\(/g) || []).length;
|
||||
const closes = (value.match(/\)/g) || []).length;
|
||||
if (closes > opens) {
|
||||
value = value.slice(0, -1);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
return [...new Set(files)];
|
||||
return value;
|
||||
}
|
||||
|
||||
function extractDangerousFiles(body) {
|
||||
return extractMatches(body, dangerousFilePattern);
|
||||
function hasRiskyExtension(segment) {
|
||||
const name = String(segment || "").toLowerCase();
|
||||
if (!name || name === "." || name === "..") return false;
|
||||
return RISKY_EXTENSIONS.some((extension) => name.endsWith(extension));
|
||||
}
|
||||
|
||||
function extractZipFiles(body) {
|
||||
return extractMatches(body, zipFilePattern);
|
||||
function urlHasRiskyPath(raw) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = new URL(raw);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false;
|
||||
|
||||
let pathname = parsed.pathname || "";
|
||||
try {
|
||||
pathname = decodeURIComponent(pathname);
|
||||
} catch {
|
||||
// Keep the raw pathname when it is not valid percent-encoding.
|
||||
}
|
||||
|
||||
return pathname.split("/").some((segment) => hasRiskyExtension(segment));
|
||||
}
|
||||
|
||||
function isGitHubUserAttachment(file) {
|
||||
return githubUserAttachmentPattern.test(file);
|
||||
function extractRiskyUrls(body) {
|
||||
const text = String(body || "");
|
||||
const found = [];
|
||||
const seen = new Set();
|
||||
for (const match of text.matchAll(URL_PATTERN)) {
|
||||
const raw = trimUrlCandidate(match[0]);
|
||||
if (!raw || seen.has(raw) || !urlHasRiskyPath(raw)) continue;
|
||||
seen.add(raw);
|
||||
found.push(raw);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
function detectSpamComment({ body, authorAssociation, userType } = {}) {
|
||||
const normalizedBody = String(body || "").replace(/\s+/g, " ").trim();
|
||||
const dangerousFiles = extractDangerousFiles(normalizedBody);
|
||||
const zipFiles = extractZipFiles(normalizedBody);
|
||||
function detectSpamComment({
|
||||
body,
|
||||
authorAssociation,
|
||||
userType,
|
||||
commentAuthor,
|
||||
issueAuthor,
|
||||
} = {}) {
|
||||
const trustedAuthor = isTrustedAuthor(authorAssociation);
|
||||
const botAuthor = String(userType || "").toLowerCase() === "bot";
|
||||
const botAuthor = String(userType || "").trim().toLowerCase() === "bot";
|
||||
const authorIsIssueAuthor = isSameLogin(commentAuthor, issueAuthor);
|
||||
const matchedUrls = extractRiskyUrls(body);
|
||||
|
||||
const reasons = [];
|
||||
let score = 0;
|
||||
|
||||
if (zipFiles.length > 0) {
|
||||
score += 10;
|
||||
reasons.push(`zip attachment or link: ${zipFiles.join(", ")}`);
|
||||
} else if (dangerousFiles.length > 0) {
|
||||
score += 10;
|
||||
reasons.push(`dangerous downloadable file: ${dangerousFiles.join(", ")}`);
|
||||
}
|
||||
|
||||
// Hard rule: any zip (or other dangerous downloadable) from an untrusted
|
||||
// human is deleted. Maintainers and bots are exempt.
|
||||
// Hard rule: hide when an untrusted human who is not the issue author posts
|
||||
// an http(s) URL whose path contains a risky archive or executable.
|
||||
// Maintainers, bots, and the issue author are exempt. Bare filenames and
|
||||
// local paths are not links, so they do not match.
|
||||
const spam =
|
||||
!trustedAuthor &&
|
||||
!botAuthor &&
|
||||
(zipFiles.length > 0 || dangerousFiles.length > 0);
|
||||
!authorIsIssueAuthor &&
|
||||
matchedUrls.length > 0;
|
||||
|
||||
return {
|
||||
spam,
|
||||
score: spam ? score : 0,
|
||||
reasons: spam ? reasons : [],
|
||||
dangerousFiles: zipFiles.length > 0 ? zipFiles : dangerousFiles,
|
||||
score: spam ? 10 : 0,
|
||||
reasons: spam ? [`risky download URL: ${matchedUrls.join(", ")}`] : [],
|
||||
matchedUrls,
|
||||
trustedAuthor,
|
||||
botAuthor,
|
||||
authorIsIssueAuthor,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
detectSpamComment,
|
||||
extractDangerousFiles,
|
||||
extractZipFiles,
|
||||
isGitHubUserAttachment,
|
||||
extractRiskyUrls,
|
||||
isTrustedAuthor,
|
||||
RISKY_EXTENSIONS,
|
||||
};
|
||||
@@ -2,113 +2,164 @@
|
||||
|
||||
const assert = require("node:assert/strict");
|
||||
const test = require("node:test");
|
||||
const {
|
||||
detectSpamComment,
|
||||
extractDangerousFiles,
|
||||
extractZipFiles,
|
||||
isGitHubUserAttachment,
|
||||
} = require("./spam-comment-filter.cjs");
|
||||
const { detectSpamComment, extractRiskyUrls } = require("./spam-comment-filter.cjs");
|
||||
|
||||
test("flags the fake Netcatty patch spam pattern", () => {
|
||||
test("issue author pasting a local SecureCRT.exe path is not hidden", () => {
|
||||
const result = detectSpamComment({
|
||||
authorAssociation: "NONE",
|
||||
userType: "User",
|
||||
body: "[netcatty_patch.zip](https://example.com/netcatty_patch.zip)\n\nMan, that terminal rendering bug is such a pain. It looks like the sftp module is tripping over the encoding when it tries to sync the current path. I found a quick patch that fixes the character mapping in the backend so those black boxes finally disappear.",
|
||||
});
|
||||
|
||||
assert.equal(result.spam, true);
|
||||
});
|
||||
|
||||
test("flags fake patch spam when the filename ends a sentence", () => {
|
||||
const result = detectSpamComment({
|
||||
authorAssociation: "NONE",
|
||||
userType: "User",
|
||||
body: "Download this patch.zip. It fixes the backend encoding so the terminal rendering black boxes disappear.",
|
||||
});
|
||||
|
||||
assert.equal(result.spam, true);
|
||||
assert.deepEqual(result.dangerousFiles, ["patch.zip"]);
|
||||
});
|
||||
|
||||
test("flags any zip from an outside user, including hash-named soft bait", () => {
|
||||
const result = detectSpamComment({
|
||||
authorAssociation: "NONE",
|
||||
userType: "User",
|
||||
body: "[63bf1862b52422e38b8cb170.zip](https://github.com/user-attachments/files/29784176/63bf1862b52422e38b8cb170.zip)\nI'd start with the docs inside",
|
||||
});
|
||||
|
||||
assert.equal(result.spam, true);
|
||||
assert.ok(
|
||||
result.dangerousFiles.some((file) => file.includes("63bf1862b52422e38b8cb170.zip"))
|
||||
);
|
||||
});
|
||||
|
||||
test("flags ordinary zip log attachments from outside users", () => {
|
||||
const result = detectSpamComment({
|
||||
authorAssociation: "FIRST_TIME_CONTRIBUTOR",
|
||||
userType: "User",
|
||||
body: "[debug-logs.zip](https://github.com/user-attachments/files/29784176/debug-logs.zip)\nI attached logs from a failed connection. The app hangs after I click connect, and the logs show the SSH handshake timing out.",
|
||||
});
|
||||
|
||||
assert.equal(result.spam, true);
|
||||
});
|
||||
|
||||
test("flags other dangerous archives from outside users", () => {
|
||||
const result = detectSpamComment({
|
||||
authorAssociation: "NONE",
|
||||
userType: "User",
|
||||
body: "See hotfix.dmg for the workaround.",
|
||||
});
|
||||
|
||||
assert.equal(result.spam, true);
|
||||
assert.deepEqual(result.dangerousFiles, ["hotfix.dmg"]);
|
||||
});
|
||||
|
||||
test("does not flag trusted maintainers even when sharing zip archives", () => {
|
||||
const result = detectSpamComment({
|
||||
authorAssociation: "OWNER",
|
||||
userType: "User",
|
||||
body: "Try this temporary netcatty_patch.zip while I prepare the signed release. It fixes the rendering issue.",
|
||||
commentAuthor: "reporter",
|
||||
issueAuthor: "reporter",
|
||||
body: "It crashes here: C:\\Program Files\\SecureCRT\\SecureCRT.exe",
|
||||
});
|
||||
|
||||
assert.equal(result.spam, false);
|
||||
assert.deepEqual(result.matchedUrls, []);
|
||||
});
|
||||
|
||||
test("does not flag bot comments that mention zip files", () => {
|
||||
const result = detectSpamComment({
|
||||
authorAssociation: "NONE",
|
||||
userType: "Bot",
|
||||
body: "Uploaded build-artifacts.zip for CI.",
|
||||
});
|
||||
|
||||
assert.equal(result.spam, false);
|
||||
});
|
||||
|
||||
test("does not flag comments without downloadable archives", () => {
|
||||
test("bare Windows path without a URL is not hidden even from a third party", () => {
|
||||
const result = detectSpamComment({
|
||||
authorAssociation: "NONE",
|
||||
userType: "User",
|
||||
body: "I attached screenshots of the hang after connect. The SSH handshake times out.",
|
||||
commentAuthor: "mallory",
|
||||
issueAuthor: "reporter",
|
||||
body: "Try Files\\SecureCRT\\SecureCRT.exe and also hotfix.dmg.",
|
||||
});
|
||||
|
||||
assert.equal(result.spam, false);
|
||||
assert.deepEqual(result.matchedUrls, []);
|
||||
});
|
||||
|
||||
test("extracts risky file names from markdown links and plain text", () => {
|
||||
assert.deepEqual(
|
||||
extractDangerousFiles("[fix.zip](https://example.com/fix.zip) also hotfix.dmg."),
|
||||
["fix.zip", "https://example.com/fix.zip", "hotfix.dmg"]
|
||||
);
|
||||
assert.deepEqual(extractZipFiles("[fix.zip](https://example.com/fix.zip) also hotfix.dmg."), [
|
||||
"fix.zip",
|
||||
"https://example.com/fix.zip",
|
||||
test("third party github user-attachments zip URL is hidden", () => {
|
||||
const result = detectSpamComment({
|
||||
authorAssociation: "NONE",
|
||||
userType: "User",
|
||||
commentAuthor: "mallory",
|
||||
issueAuthor: "reporter",
|
||||
body: "Grab https://github.com/user-attachments/files/123/fix.zip and run it.",
|
||||
});
|
||||
|
||||
assert.equal(result.spam, true);
|
||||
assert.deepEqual(result.matchedUrls, [
|
||||
"https://github.com/user-attachments/files/123/fix.zip",
|
||||
]);
|
||||
});
|
||||
|
||||
test("identifies GitHub user attachment URLs", () => {
|
||||
assert.equal(
|
||||
isGitHubUserAttachment("https://github.com/user-attachments/files/29784176/netcatty_fix.zip"),
|
||||
true
|
||||
test("third party mediafire zip URL is hidden when the extension is a path segment", () => {
|
||||
const result = detectSpamComment({
|
||||
authorAssociation: "NONE",
|
||||
userType: "User",
|
||||
commentAuthor: "mallory",
|
||||
issueAuthor: "reporter",
|
||||
body: "Download https://www.mediafire.com/file/abc/netcatty_fix.zip/file",
|
||||
});
|
||||
|
||||
assert.equal(result.spam, true);
|
||||
assert.deepEqual(result.matchedUrls, [
|
||||
"https://www.mediafire.com/file/abc/netcatty_fix.zip/file",
|
||||
]);
|
||||
});
|
||||
|
||||
test("maintainer posting a release dmg link is not hidden", () => {
|
||||
const result = detectSpamComment({
|
||||
authorAssociation: "OWNER",
|
||||
userType: "User",
|
||||
commentAuthor: "maintainer",
|
||||
issueAuthor: "reporter",
|
||||
body: "Signed build: https://github.com/binaricat/Netcatty/releases/download/v1.2.3/Netcatty.dmg",
|
||||
});
|
||||
|
||||
assert.equal(result.spam, false);
|
||||
assert.equal(result.trustedAuthor, true);
|
||||
assert.deepEqual(result.matchedUrls, [
|
||||
"https://github.com/binaricat/Netcatty/releases/download/v1.2.3/Netcatty.dmg",
|
||||
]);
|
||||
});
|
||||
|
||||
test("issue author uploading their own repro zip is not hidden", () => {
|
||||
const result = detectSpamComment({
|
||||
authorAssociation: "NONE",
|
||||
userType: "User",
|
||||
commentAuthor: "Reporter",
|
||||
issueAuthor: "reporter",
|
||||
body: "[repro.zip](https://github.com/user-attachments/files/99/repro.zip)",
|
||||
});
|
||||
|
||||
assert.equal(result.spam, false);
|
||||
assert.equal(result.authorIsIssueAuthor, true);
|
||||
assert.deepEqual(result.matchedUrls, [
|
||||
"https://github.com/user-attachments/files/99/repro.zip",
|
||||
]);
|
||||
});
|
||||
|
||||
test("query strings do not block a risky path, and a query-only filename does not match", () => {
|
||||
assert.deepEqual(
|
||||
extractRiskyUrls("https://example.com/dropper.exe?download=1&arch=win"),
|
||||
["https://example.com/dropper.exe?download=1&arch=win"]
|
||||
);
|
||||
assert.equal(isGitHubUserAttachment("https://example.com/netcatty_fix.zip"), false);
|
||||
assert.deepEqual(
|
||||
extractRiskyUrls("https://example.com/download?file=fix.zip"),
|
||||
[]
|
||||
);
|
||||
});
|
||||
|
||||
test("matches newly added extensions and ignores non-risky links", () => {
|
||||
const body = [
|
||||
"https://example.com/a.jar",
|
||||
"https://example.com/b.iso",
|
||||
"https://example.com/c.msix",
|
||||
"https://example.com/d.lnk",
|
||||
"https://example.com/e.tar.xz",
|
||||
"https://example.com/f.tar.gz",
|
||||
"https://github.com/user-attachments/assets/e1302660-dece-46be-9857-1678a9b13d00",
|
||||
"https://example.com/package.json",
|
||||
"https://example.com/notes.zip.txt",
|
||||
].join("\n");
|
||||
|
||||
assert.deepEqual(extractRiskyUrls(body), [
|
||||
"https://example.com/a.jar",
|
||||
"https://example.com/b.iso",
|
||||
"https://example.com/c.msix",
|
||||
"https://example.com/d.lnk",
|
||||
"https://example.com/e.tar.xz",
|
||||
"https://example.com/f.tar.gz",
|
||||
]);
|
||||
});
|
||||
|
||||
test("member and collaborator exemptions still apply to http links", () => {
|
||||
for (const authorAssociation of ["MEMBER", "COLLABORATOR"]) {
|
||||
const result = detectSpamComment({
|
||||
authorAssociation,
|
||||
userType: "User",
|
||||
commentAuthor: "maintainer",
|
||||
issueAuthor: "reporter",
|
||||
body: "Mirror: http://example.com/setup.msi",
|
||||
});
|
||||
assert.equal(result.spam, false);
|
||||
assert.deepEqual(result.matchedUrls, ["http://example.com/setup.msi"]);
|
||||
}
|
||||
});
|
||||
|
||||
test("does not flag bot comments that include a risky URL", () => {
|
||||
const result = detectSpamComment({
|
||||
authorAssociation: "NONE",
|
||||
userType: "Bot",
|
||||
commentAuthor: "netcatty[bot]",
|
||||
issueAuthor: "reporter",
|
||||
body: "Uploaded https://example.com/build-artifacts.zip for CI.",
|
||||
});
|
||||
|
||||
assert.equal(result.spam, false);
|
||||
assert.equal(result.botAuthor, true);
|
||||
});
|
||||
|
||||
test("strips markdown and sentence punctuation around the URL", () => {
|
||||
assert.deepEqual(
|
||||
extractRiskyUrls("See [patch](https://example.com/patch.zip). Thanks!"),
|
||||
["https://example.com/patch.zip"]
|
||||
);
|
||||
assert.deepEqual(
|
||||
extractRiskyUrls("<https://example.com/tool.EXE>"),
|
||||
["https://example.com/tool.EXE"]
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
"use strict";
|
||||
/* global process, __dirname, console, document, requestAnimationFrame */
|
||||
if (!process.versions.electron) {
|
||||
require("node:test")("inline image pixels stay aligned across terminal resizes", {
|
||||
skip: "run with Electron to exercise real DOM and canvas rendering",
|
||||
}, () => {});
|
||||
} else {
|
||||
const { app, BrowserWindow } = require("electron");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const esbuild = require("esbuild");
|
||||
const temp = require("../electron/bridges/tempDirBridge.cjs");
|
||||
const root = path.resolve(__dirname, "..");
|
||||
const userData = fs.mkdtempSync(`${temp.getTempFilePath("image-resize")}-`);
|
||||
app.setPath("userData", userData);
|
||||
app.on("window-all-closed", () => {});
|
||||
let win;
|
||||
const cleanup = code => {
|
||||
win?.destroy();
|
||||
fs.rmSync(userData, { recursive: true, force: true });
|
||||
app.exit(code);
|
||||
};
|
||||
|
||||
async function exercise({ Terminal, ImageAddon }) {
|
||||
const check = (actual, expected, label) => {
|
||||
if (JSON.stringify(actual) !== JSON.stringify(expected)) {
|
||||
throw new Error(`${label}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`);
|
||||
}
|
||||
};
|
||||
const host = document.createElement("div");
|
||||
document.body.appendChild(host);
|
||||
const term = new Terminal({ cols: 40, rows: 18, fontFamily: "monospace", fontSize: 16, cursorBlink: false, allowProposedApi: true });
|
||||
term.open(host);
|
||||
const addon = new ImageAddon({ sixelSupport: false, iipSupport: false, kittySupport: false });
|
||||
term.loadAddon(addon);
|
||||
const render = async () => {
|
||||
term.refresh(0, term.rows - 1);
|
||||
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
||||
};
|
||||
await render();
|
||||
const originalCell = { ...addon._renderer.cellSize };
|
||||
const source = document.createElement("canvas");
|
||||
source.width = Math.round(originalCell.width * 40);
|
||||
source.height = Math.round(originalCell.height * 8);
|
||||
check(Math.ceil(source.width / originalCell.width), 40, "fixture covers 40 image columns");
|
||||
const context = source.getContext("2d");
|
||||
const color = (col, row) => [32 + (col % 7) * 32, 32 + row * 24, 192, 255];
|
||||
for (let row = 0; row < 8; row++) {
|
||||
for (let col = 0; col < 40; col++) {
|
||||
const [r, g, b] = color(col, row);
|
||||
context.fillStyle = `rgb(${r},${g},${b})`;
|
||||
context.fillRect(Math.floor(col * originalCell.width), Math.floor(row * originalCell.height), Math.ceil(originalCell.width), Math.ceil(originalCell.height));
|
||||
}
|
||||
}
|
||||
// Insert once into the real terminal buffer. All subsequent frames must use
|
||||
// the original tile IDs, just like an image already printed by any protocol.
|
||||
const id = addon._storage.addImage(source, { scrolling: true, layer: "top", zIndex: 0, cursorPos: "vt340" });
|
||||
const spec = addon._storage._images.get(id);
|
||||
const samples = [];
|
||||
let roundedStrideChanged = false;
|
||||
for (const cols of [40, 53, 67, 91, 40, 53, 40]) {
|
||||
term.resize(cols, 18);
|
||||
await render();
|
||||
const cell = addon._renderer.cellSize;
|
||||
const badStride = Math.ceil(spec.actual.width / cell.width);
|
||||
roundedStrideChanged ||= badStride !== 40;
|
||||
const output = host.querySelector(".xterm-image-layer-top").getContext("2d");
|
||||
for (const row of [0, 1, 2, 7]) {
|
||||
for (const col of [0, 1, 5, 20, 38]) {
|
||||
const pixel = [...output.getImageData(Math.floor((col + 0.5) * cell.width), Math.floor((row + 0.5) * cell.height), 1, 1).data];
|
||||
check(pixel, color(col, row), `canvas pixel at cols=${cols}, cell=${col},${row}`);
|
||||
const tile = addon.extractTileAtBufferCell(col, row);
|
||||
const extracted = [...tile.getContext("2d").getImageData(Math.floor(tile.width / 2), Math.floor(tile.height / 2), 1, 1).data];
|
||||
check(extracted, color(col, row), `extracted tile at cols=${cols}, cell=${col},${row}`);
|
||||
}
|
||||
}
|
||||
samples.push({ cols, cellWidth: cell.width, canvasWidth: spec.actual.width, roundedStride: badStride });
|
||||
}
|
||||
check(roundedStrideChanged, true, "exercise fractional cell widths that triggered the regression");
|
||||
term.dispose();
|
||||
host.remove();
|
||||
return { samples, pixelChecks: 280, repeatedResizes: true };
|
||||
}
|
||||
|
||||
void app.whenReady().then(async () => {
|
||||
const bundle = esbuild.buildSync({
|
||||
stdin: {
|
||||
contents: 'export { Terminal } from "@xterm/xterm"; export { ImageAddon } from "@xterm/addon-image";',
|
||||
resolveDir: root,
|
||||
},
|
||||
bundle: true, format: "iife", globalName: "ImageResizeTest", platform: "browser", write: false,
|
||||
}).outputFiles[0].text;
|
||||
win = new BrowserWindow({ show: true, width: 1000, height: 600, webPreferences: { backgroundThrottling: false } });
|
||||
await win.loadURL("data:text/html,<body style='margin:0;background:black'>");
|
||||
await win.webContents.insertCSS(fs.readFileSync(require.resolve("@xterm/xterm/css/xterm.css"), "utf8"));
|
||||
const result = await win.webContents.executeJavaScript(`${bundle}\n(${exercise.toString()})(ImageResizeTest)`);
|
||||
console.log("IMAGE_RESIZE_RENDERING_OK", JSON.stringify(result));
|
||||
cleanup(0);
|
||||
}).catch(error => { console.error(error); cleanup(1); });
|
||||
}
|
||||
Reference in new issue
Block a user