Group core utility modules into util, skill, and update
Move duration, redact, runtime, secure-file, and semver under core/util; embedded-skill and skill-version under core/skill; update-cache under core/update. Move the dev-override test next to the script it covers, and update the embedded-skill generator output path and regenerated manifest. No behavior change.
This commit is contained in:
1 parent
666a12c676
commit
a189f49223
44 files changed
+146
-145
No files matched your search
@@ -0,0 +1,79 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import {
|
||||
durationSeconds,
|
||||
expireSeconds,
|
||||
parseDurationMs,
|
||||
tokenizeDuration
|
||||
} from "./duration.js";
|
||||
|
||||
describe("tokenizeDuration", () => {
|
||||
test("splits magnitude from unit and accepts every alias", () => {
|
||||
expect(tokenizeDuration("7d")).toEqual({ value: 7, unit: "d" });
|
||||
expect(tokenizeDuration("24h")).toEqual({ value: 24, unit: "h" });
|
||||
expect(tokenizeDuration("90m")).toEqual({ value: 90, unit: "m" });
|
||||
expect(tokenizeDuration("7200s")).toEqual({ value: 7200, unit: "s" });
|
||||
expect(tokenizeDuration("1.5h")).toEqual({ value: 1.5, unit: "h" });
|
||||
expect(tokenizeDuration("2 hours")).toEqual({ value: 2, unit: "h" });
|
||||
expect(tokenizeDuration("500ms")).toEqual({ value: 500, unit: "ms" });
|
||||
expect(tokenizeDuration(" 300 ")).toEqual({ value: 300, unit: undefined });
|
||||
expect(tokenizeDuration(168)).toEqual({ value: 168, unit: undefined });
|
||||
});
|
||||
|
||||
test("rejects unparseable input instead of guessing", () => {
|
||||
expect(tokenizeDuration("invalid")).toBeUndefined();
|
||||
expect(tokenizeDuration("")).toBeUndefined();
|
||||
expect(tokenizeDuration("-5m")).toBeUndefined();
|
||||
expect(tokenizeDuration("5parsecs")).toBeUndefined();
|
||||
expect(tokenizeDuration(Number.NaN)).toBeUndefined();
|
||||
expect(tokenizeDuration(true as unknown as string)).toBeUndefined();
|
||||
expect(tokenizeDuration("9".repeat(309))).toBeUndefined();
|
||||
expect(tokenizeDuration("9".repeat(309) + "s")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("expireSeconds", () => {
|
||||
test("reads a unitless number at most 168 as hours and a larger one as seconds", () => {
|
||||
// Both --expire paths used to reimplement this rule separately, and they
|
||||
// disagreed at the boundary; 300 now means 5 minutes everywhere.
|
||||
expect(expireSeconds({ value: 168, unit: undefined })).toBe(168 * 3600);
|
||||
expect(expireSeconds({ value: 169, unit: undefined })).toBe(169);
|
||||
expect(expireSeconds({ value: 300, unit: undefined })).toBe(300);
|
||||
expect(expireSeconds({ value: 86400, unit: undefined })).toBe(86_400);
|
||||
});
|
||||
|
||||
test("converts explicit units regardless of magnitude", () => {
|
||||
expect(expireSeconds({ value: 7, unit: "d" })).toBe(604_800);
|
||||
expect(expireSeconds({ value: 7200, unit: "s" })).toBe(7200);
|
||||
expect(expireSeconds({ value: 30, unit: "m" })).toBe(1800);
|
||||
});
|
||||
});
|
||||
|
||||
describe("durationSeconds", () => {
|
||||
test("uses the caller's unitless policy when none is written", () => {
|
||||
expect(durationSeconds({ value: 5, unit: undefined }, "s")).toBe(5);
|
||||
expect(durationSeconds({ value: 5, unit: undefined }, "h")).toBe(18_000);
|
||||
expect(durationSeconds({ value: 5, unit: "ms" }, "h")).toBe(0.005);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseDurationMs", () => {
|
||||
test("converts simulation windows to milliseconds", () => {
|
||||
expect(parseDurationMs("2s")).toBe(2000);
|
||||
expect(parseDurationMs("10m")).toBe(600_000);
|
||||
expect(parseDurationMs("5m")).toBe(300_000);
|
||||
expect(parseDurationMs("500ms")).toBe(500);
|
||||
expect(parseDurationMs("1h")).toBe(3_600_000);
|
||||
expect(parseDurationMs("1d")).toBe(86_400_000);
|
||||
});
|
||||
|
||||
test("reads unitless input as seconds, matching the flag's defaults", () => {
|
||||
expect(parseDurationMs("30")).toBe(30_000);
|
||||
});
|
||||
|
||||
test("falls back rather than failing a batch over a bad poll interval", () => {
|
||||
expect(parseDurationMs("soon")).toBe(600_000);
|
||||
expect(parseDurationMs("soon", 1000)).toBe(1000);
|
||||
expect(parseDurationMs("9".repeat(309) + "s", 1000)).toBe(1000);
|
||||
expect(parseDurationMs("9".repeat(308) + "d", 1000)).toBe(1000);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,145 @@
|
||||
/**
|
||||
* Duration tokenizing shared by every flag that accepts `7d` / `1.5h` / `300`.
|
||||
*
|
||||
* The tokenizer owns exactly one job: turning the written form into a magnitude
|
||||
* plus a canonical unit. Interpretation stays with each caller, because the
|
||||
* three consumers genuinely disagree — Seal delegation links take whole hours
|
||||
* in 1..168, Hose assistance links take seconds, simulation windows take
|
||||
* milliseconds. Sharing the grammar (and the unitless heuristic) is what stops
|
||||
* `--expire 300` from parsing two different ways in two files.
|
||||
*/
|
||||
|
||||
export type DurationUnit = "ms" | "s" | "m" | "h" | "d";
|
||||
|
||||
export interface DurationToken {
|
||||
/** The magnitude exactly as written, before any unit conversion. */
|
||||
value: number;
|
||||
/** `undefined` when the input carried no unit, e.g. `300`. */
|
||||
unit: DurationUnit | undefined;
|
||||
}
|
||||
|
||||
const UNIT_ALIASES: Record<string, DurationUnit> = {
|
||||
ms: "ms",
|
||||
s: "s",
|
||||
sec: "s",
|
||||
secs: "s",
|
||||
second: "s",
|
||||
seconds: "s",
|
||||
m: "m",
|
||||
min: "m",
|
||||
mins: "m",
|
||||
minute: "m",
|
||||
minutes: "m",
|
||||
h: "h",
|
||||
hr: "h",
|
||||
hrs: "h",
|
||||
hour: "h",
|
||||
hours: "h",
|
||||
d: "d",
|
||||
day: "d",
|
||||
days: "d"
|
||||
};
|
||||
|
||||
const DURATION_PATTERN = /^(\d+(?:\.\d+)?)\s*([a-z]+)?$/i;
|
||||
|
||||
export interface TokenizeDurationOptions {
|
||||
/**
|
||||
* Units this caller accepts. Restricting the set keeps a shared tokenizer
|
||||
* from quietly widening a flag's grammar: sub-second input was a usage error
|
||||
* for `--expire` before the parsers were unified, and must stay one.
|
||||
*/
|
||||
units?: readonly DurationUnit[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a duration literal. Returns `undefined` when the input cannot be read
|
||||
* at all — callers decide whether that is a usage error or a default.
|
||||
*
|
||||
* A unitless number keeps whatever magnitude it had; pair it with
|
||||
* {@link expireSeconds} or an explicit `unitless` argument to resolve it.
|
||||
*/
|
||||
export function tokenizeDuration(
|
||||
value: string | number,
|
||||
options: TokenizeDurationOptions = {}
|
||||
): DurationToken | undefined {
|
||||
if (typeof value === "number") {
|
||||
return Number.isFinite(value) ? { value, unit: undefined } : undefined;
|
||||
}
|
||||
if (typeof value !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const match = value.trim().match(DURATION_PATTERN);
|
||||
if (!match || !match[1]) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const magnitude = parseFloat(match[1]);
|
||||
if (!Number.isFinite(magnitude)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const rawUnit = match[2]?.toLowerCase();
|
||||
if (!rawUnit) {
|
||||
return { value: magnitude, unit: undefined };
|
||||
}
|
||||
|
||||
const unit = UNIT_ALIASES[rawUnit];
|
||||
if (!unit) {
|
||||
return undefined;
|
||||
}
|
||||
if (options.units && !options.units.includes(unit)) {
|
||||
return undefined;
|
||||
}
|
||||
return { value: magnitude, unit };
|
||||
}
|
||||
|
||||
/**
|
||||
* Units the `--expire` flags accept. Sub-second precision is meaningless for
|
||||
* an assistance link and was rejected before the parsers were shared.
|
||||
*/
|
||||
export const EXPIRE_UNITS: readonly DurationUnit[] = ["d", "h", "m", "s"];
|
||||
|
||||
/** Convert a token to seconds, resolving a unitless value as `unitless`. */
|
||||
export function durationSeconds(token: DurationToken, unitless: DurationUnit): number {
|
||||
switch (token.unit ?? unitless) {
|
||||
case "ms":
|
||||
return token.value / 1000;
|
||||
case "m":
|
||||
return token.value * 60;
|
||||
case "h":
|
||||
return token.value * 3600;
|
||||
case "d":
|
||||
return token.value * 86400;
|
||||
case "s":
|
||||
default:
|
||||
return token.value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Unitless `--expire` heuristic shared by the Seal and Hose link flags:
|
||||
* a bare number at most 168 reads as hours (7 days of them), a larger one
|
||||
* reads as seconds. Without this, `--expire 300` would mean 300 hours on one
|
||||
* path and 5 minutes on another.
|
||||
*/
|
||||
export function expireSeconds(token: DurationToken): number {
|
||||
return durationSeconds(token, token.value <= 168 ? "h" : "s");
|
||||
}
|
||||
|
||||
/** Default used by {@link parseDurationMs} when the literal is unreadable. */
|
||||
export const DEFAULT_DURATION_MS = 600_000;
|
||||
|
||||
/**
|
||||
* Simulation windows and poll intervals: milliseconds, unitless input read as
|
||||
* seconds, and an unreadable literal falls back to the default instead of
|
||||
* failing the call — a poll interval is not worth aborting a batch over.
|
||||
*/
|
||||
export function parseDurationMs(duration: string, fallbackMs = DEFAULT_DURATION_MS): number {
|
||||
const token = tokenizeDuration(duration);
|
||||
if (!token || token.value < 0) {
|
||||
return fallbackMs;
|
||||
}
|
||||
const milliseconds = Math.round(durationSeconds(token, "s") * 1000);
|
||||
return Number.isFinite(milliseconds) ? milliseconds : fallbackMs;
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { redactSensitiveText } from "./redact.js";
|
||||
|
||||
describe("redactSensitiveText", () => {
|
||||
test("redacts credential query parameters while preserving the rest of the URL", () => {
|
||||
const input = "https://seal.example/api/hosecloud/outbound?config_id=keep-me&signKey=super-secret&z=1";
|
||||
const output = redactSensitiveText(input);
|
||||
|
||||
expect(output).toContain("config_id=keep-me");
|
||||
expect(output).toContain("signKey=<redacted>");
|
||||
expect(output).not.toContain("super-secret");
|
||||
expect(output).toContain("z=1");
|
||||
});
|
||||
|
||||
test("redacts Bearer tokens", () => {
|
||||
const output = redactSensitiveText("Authorization failed for Bearer abc.def.ghi");
|
||||
expect(output).toContain("Bearer <redacted>");
|
||||
expect(output).not.toContain("abc.def.ghi");
|
||||
});
|
||||
|
||||
test("redacts credential fields in JSON without corrupting the document", () => {
|
||||
const input = `{"signKey":"abc123","appSecurity":"sec","name":"keep"}`;
|
||||
const output = redactSensitiveText(input);
|
||||
|
||||
expect(output).toContain(`"signKey":"<redacted>"`);
|
||||
expect(output).toContain(`"appSecurity":"<redacted>"`);
|
||||
expect(output).toContain(`"name":"keep"`);
|
||||
expect(output).not.toContain("abc123");
|
||||
// The output must still be parseable: a broken replacement would leave a
|
||||
// literal `$2`/`$3` and drop the closing quote.
|
||||
expect(() => JSON.parse(output)).not.toThrow();
|
||||
expect(output).not.toMatch(/\$\d/);
|
||||
});
|
||||
|
||||
test("leaves text without secrets untouched", () => {
|
||||
const input = "plain text with no credentials at all";
|
||||
expect(redactSensitiveText(input)).toBe(input);
|
||||
});
|
||||
|
||||
test("covers every credential field name the schema allows", () => {
|
||||
const fields = [
|
||||
"appSecurity",
|
||||
"password",
|
||||
"secret",
|
||||
"signKey",
|
||||
"closeToken",
|
||||
"refreshToken",
|
||||
"accessToken",
|
||||
"authorization"
|
||||
];
|
||||
for (const field of fields) {
|
||||
const output = redactSensitiveText(`{"${field}":"value-should-vanish"}`);
|
||||
expect(output).toContain(`"${field}":"<redacted>"`);
|
||||
expect(output).not.toContain("value-should-vanish");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* Redacts credential-bearing patterns from free text before it reaches an
|
||||
* output channel.
|
||||
*
|
||||
* Applied to: error messages surfaced by the CLI runner (`src/cli/runner.ts`) and
|
||||
* HTTP error responses (`src/http/routes.ts`).
|
||||
*
|
||||
* NOT applied to successful stdout payloads: those are redacted where they are
|
||||
* built — handlers mask fields via `presentWebhookIntegration`,
|
||||
* `redactIntegrationSecrets`, `maskHoseSecurity` and `formatSafeSourceDetail`.
|
||||
* Blanket redaction of stdout would also destroy deliberate credential-delivery
|
||||
* output (`auth link` tokens, `extract-keys --reveal`), so it stays per-handler.
|
||||
*/
|
||||
export function redactSensitiveText(value: string): string {
|
||||
return value
|
||||
.replace(/([?&](?:accessToken|token|returnToken|appSecurity|signKey|secret)=)[^&\s]+/gi, "$1<redacted>")
|
||||
.replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi, "$1<redacted>")
|
||||
.replace(/(Basic\s+)[A-Za-z0-9+/=]+/gi, "$1<redacted>")
|
||||
.replace(
|
||||
/("(?:appSecurity|password|secret|signKey|closeToken|refreshToken|accessToken|authorization)"\s*:\s*")[^"]*(")/gi,
|
||||
"$1<redacted>$2"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { isCompiledBinary, resolveAppRoot, resolveDefaultLauncher } from "./runtime.js";
|
||||
|
||||
describe("runtime detection and launcher", () => {
|
||||
test("isCompiledBinary detects bun runtime executable vs standalone binary", () => {
|
||||
expect(isCompiledBinary("/Users/user/.bun/bin/bun", "file:///Users/user/code/src/cli.ts")).toBe(false);
|
||||
expect(isCompiledBinary("C:\\Users\\user\\.bun\\bin\\bun.exe", "file:///C:/code/src/cli.ts")).toBe(false);
|
||||
expect(isCompiledBinary("/usr/local/bin/seal-home", "file:///Users/user/code/src/cli.ts")).toBe(true);
|
||||
expect(isCompiledBinary("/Users/user/.bun/bin/bun", "file:///$bunfs/root/src/cli.ts")).toBe(true);
|
||||
});
|
||||
|
||||
test("resolveAppRoot returns cwd for compiled binary and project root for source", () => {
|
||||
const sourceRoot = resolveAppRoot("/Users/user/code/src/cli.ts", false);
|
||||
expect(sourceRoot).toBe("/Users/user/code");
|
||||
|
||||
const binaryRoot = resolveAppRoot(undefined, true);
|
||||
expect(binaryRoot).toBe(process.cwd());
|
||||
});
|
||||
|
||||
test("resolveDefaultLauncher configures args based on compiled mode", () => {
|
||||
const sourceLauncher = resolveDefaultLauncher("/Users/user/code/src/cli.ts", false, "/path/to/bun");
|
||||
expect(sourceLauncher).toEqual({
|
||||
command: "/path/to/bun",
|
||||
args: ["/Users/user/code/src/cli.ts"]
|
||||
});
|
||||
|
||||
const binaryLauncher = resolveDefaultLauncher("/ignored", true, "/usr/local/bin/seal-home");
|
||||
expect(binaryLauncher).toEqual({
|
||||
command: "/usr/local/bin/seal-home",
|
||||
args: []
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
import { existsSync, symlinkSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { basename, dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
export function isCompiledBinary(execPath = process.execPath, metaUrl = import.meta.url): boolean {
|
||||
if (metaUrl.includes("/$bunfs/") || metaUrl.includes("\\$bunfs\\")) {
|
||||
return true;
|
||||
}
|
||||
const lower = execPath.toLowerCase().replace(/\\/g, "/");
|
||||
return !lower.endsWith("/bun") && !lower.endsWith("/bun.exe") && !lower.endsWith("/node") && !lower.endsWith("/node.exe");
|
||||
}
|
||||
|
||||
export function resolveAppRoot(entryFile?: string, isCompiled = isCompiledBinary()): string {
|
||||
if (isCompiled) {
|
||||
return process.cwd();
|
||||
}
|
||||
const file = entryFile || fileURLToPath(import.meta.url);
|
||||
return dirname(dirname(file));
|
||||
}
|
||||
|
||||
export type LauncherConfig = {
|
||||
command: string;
|
||||
args?: string[];
|
||||
};
|
||||
|
||||
export function resolveDefaultLauncher(
|
||||
entryFile: string,
|
||||
isCompiled = isCompiledBinary(),
|
||||
execPath = process.execPath
|
||||
): LauncherConfig {
|
||||
if (isCompiled) {
|
||||
return {
|
||||
command: execPath,
|
||||
args: []
|
||||
};
|
||||
}
|
||||
return {
|
||||
command: execPath,
|
||||
args: [entryFile]
|
||||
};
|
||||
}
|
||||
|
||||
export async function performRuntimeSelfHealing(): Promise<{
|
||||
binaryHealed?: boolean;
|
||||
skillHealed?: boolean;
|
||||
}> {
|
||||
const result: { binaryHealed?: boolean; skillHealed?: boolean } = {};
|
||||
|
||||
// 1. Binary executable alias self-healing
|
||||
try {
|
||||
if (isCompiledBinary()) {
|
||||
const execPath = process.execPath;
|
||||
const base = basename(execPath);
|
||||
const isWin = process.platform === "win32";
|
||||
const legacyName = isWin ? "seal-home.exe" : "seal-home";
|
||||
const primaryName = isWin ? "seal-use.exe" : "seal-use";
|
||||
|
||||
if (base === legacyName) {
|
||||
const primaryPath = join(dirname(execPath), primaryName);
|
||||
if (!existsSync(primaryPath)) {
|
||||
try {
|
||||
symlinkSync(execPath, primaryPath);
|
||||
result.binaryHealed = true;
|
||||
} catch {
|
||||
// ignore if permissions do not allow
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
|
||||
// 2. Legacy skill cutover self-healing
|
||||
try {
|
||||
const legacySkillDir = join(homedir(), ".agents", "skills", "seal-home");
|
||||
if (existsSync(legacySkillDir)) {
|
||||
// Ordinary discovery must not initialize the embedded resource graph.
|
||||
(await import("../skill/embedded-skill.js")).syncGlobalSkillIfPresent();
|
||||
result.skillHealed = true;
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { writeSecureFile } from "./secure-file.js";
|
||||
|
||||
/**
|
||||
* Direct unit tests for the credential write path.
|
||||
*
|
||||
* Indirect coverage exists through loader/token-store mode assertions, but
|
||||
* this helper is the single choke point that keeps existing world-readable
|
||||
* credential files from staying world-readable — the P0 from the 2026-10-17
|
||||
* architecture review. Its guarantees deserve their own colocated tests so a
|
||||
* refactor of either caller cannot silently drop them.
|
||||
*/
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
function tempDir(): string {
|
||||
const dir = mkdtempSync(join(tmpdir(), "seal-secure-file-"));
|
||||
tempDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of tempDirs.splice(0)) {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
function fileMode(path: string): number {
|
||||
return statSync(path).mode & 0o777;
|
||||
}
|
||||
|
||||
describe("writeSecureFile", () => {
|
||||
test("creates a new credential file as 0600 with exact content", () => {
|
||||
const dir = tempDir();
|
||||
const target = join(dir, "tokens.json");
|
||||
|
||||
writeSecureFile(target, '{"token":"secret"}\n');
|
||||
|
||||
expect(fileMode(target)).toBe(0o600);
|
||||
expect(readFileSync(target, "utf8")).toBe('{"token":"secret"}\n');
|
||||
});
|
||||
|
||||
test("tightens a pre-existing 0644 file to 0600 on write", () => {
|
||||
const dir = tempDir();
|
||||
const target = join(dir, "corp.json");
|
||||
writeFileSync(target, '{"old":"legacy-inherited"}', { mode: 0o644 });
|
||||
chmodSync(target, 0o644);
|
||||
expect(fileMode(target)).toBe(0o644);
|
||||
|
||||
writeSecureFile(target, '{"new":"rotated-secret"}');
|
||||
|
||||
expect(fileMode(target)).toBe(0o600);
|
||||
expect(readFileSync(target, "utf8")).toBe('{"new":"rotated-secret"}');
|
||||
});
|
||||
|
||||
test("truncates longer previous content so no secret residue survives", () => {
|
||||
const dir = tempDir();
|
||||
const target = join(dir, "tokens.json");
|
||||
writeSecureFile(target, '{"access":"a","refresh":"b","extra":"padding-padding"}');
|
||||
|
||||
writeSecureFile(target, "{}");
|
||||
|
||||
expect(readFileSync(target, "utf8")).toBe("{}");
|
||||
});
|
||||
|
||||
test("accepts binary content such as embedded skill assets", () => {
|
||||
const dir = tempDir();
|
||||
const target = join(dir, "asset.png");
|
||||
const bytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x00, 0xff]);
|
||||
|
||||
writeSecureFile(target, bytes);
|
||||
|
||||
expect(fileMode(target)).toBe(0o600);
|
||||
expect(new Uint8Array(readFileSync(target))).toEqual(bytes);
|
||||
});
|
||||
|
||||
test("creates missing parent directories as 0700", () => {
|
||||
const dir = tempDir();
|
||||
const target = join(dir, "nested", "deeper", "tokens.json");
|
||||
|
||||
writeSecureFile(target, "{}");
|
||||
|
||||
expect(fileMode(target)).toBe(0o600);
|
||||
expect(fileMode(join(dir, "nested"))).toBe(0o700);
|
||||
expect(fileMode(join(dir, "nested", "deeper"))).toBe(0o700);
|
||||
});
|
||||
|
||||
test("does not rewrite the mode of a user-owned parent directory", () => {
|
||||
const dir = tempDir();
|
||||
const shared = join(dir, "shared");
|
||||
mkdirSync(shared, { mode: 0o755 });
|
||||
chmodSync(shared, 0o755);
|
||||
|
||||
writeSecureFile(join(shared, "corp.json"), "{}");
|
||||
|
||||
expect(fileMode(shared)).toBe(0o755);
|
||||
expect(fileMode(join(shared, "corp.json"))).toBe(0o600);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import { closeSync, fchmodSync, mkdirSync, openSync, writeFileSync } from "node:fs"
|
||||
import { dirname } from "node:path"
|
||||
|
||||
/** Tighten an existing credential file before writing any new secret bytes. */
|
||||
export function writeSecureFile(path: string, content: string | Uint8Array): void {
|
||||
mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
|
||||
const fd = openSync(path, "w", 0o600)
|
||||
try {
|
||||
fchmodSync(fd, 0o600)
|
||||
writeFileSync(fd, content)
|
||||
} finally {
|
||||
closeSync(fd)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* Minimal semver comparison for release ordering. Kept out of
|
||||
* `cli/commands/update.ts` so the `version` command path does not have to load
|
||||
* the 1200-line updater (and its embedded-skill bundle) just to decide whether
|
||||
* a cached release is newer.
|
||||
*/
|
||||
export function compareSemVer(v1: string, v2: string): number {
|
||||
const p1 = v1.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0);
|
||||
const p2 = v2.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0);
|
||||
for (let i = 0; i < Math.max(p1.length, p2.length); i++) {
|
||||
const a = p1[i] ?? 0;
|
||||
const b = p2[i] ?? 0;
|
||||
if (a > b) return 1;
|
||||
if (a < b) return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
export function isNewerVersion(latest: string, current: string): boolean {
|
||||
return compareSemVer(latest, current) > 0;
|
||||
}
|
||||
Reference in new issue
Block a user