@hasna/hooks 0.14.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +31 -11
- package/bin/hooks/stop-review.js +17 -9
- package/bin/hooks-mcp.js +741 -311
- package/bin/index.js +1673 -634
- package/bin/native-safety-entry.js +2 -2
- package/bin/native-safety-worker.cjs +36 -34
- package/bin/release-manifest.json +297 -0
- package/bin/serve.js +577 -151
- package/dist/index.js +1813 -1178
- package/dist/lib/codex-safety-check.d.ts +1 -1
- package/dist/lib/error-events.d.ts +59 -0
- package/dist/lib/install-record.d.ts +136 -0
- package/dist/lib/manifest.d.ts +6 -0
- package/dist/lib/release-manifest.d.ts +162 -0
- package/dist/lib/store.d.ts +25 -2
- package/dist/openapi.d.ts +147 -0
- package/dist/registry-auth.d.ts +6 -1
- package/dist/registry-http.d.ts +2 -1
- package/dist/sdk/generated.d.ts +26 -0
- package/dist/sdk/index.js +14 -0
- package/hooks/codewith-native-common.ts +190 -6
- package/hooks/hook-signed-link-guard/README.md +46 -0
- package/hooks/hook-signed-link-guard/src/classify.ts +7 -3
- package/hooks/hook-signed-link-guard/src/jq.ts +205 -34
- package/hooks/hook-stop-review/README.md +5 -2
- package/hooks/hook-stop-review/src/jev.ts +9 -4
- package/hooks/hook-stop-review/src/policy.ts +7 -3
- package/hooks/hook-stop-review/src/runtime.ts +5 -4
- package/hooks/hook-trash-guard/README.md +9 -4
- package/hooks/hook-trash-guard/src/hook.ts +127 -10
- package/hooks/hook-workspace-repos-guard/src/hook.ts +27 -12
- package/hooks/pre-bash/README.md +47 -1
- package/hooks/pre-bash/src/hook.ts +168 -12
- package/hooks/shell-words.ts +40 -2
- package/package.json +3 -2
- package/scripts/build-release-manifest.ts +27 -0
- package/scripts/validate-package.ts +5 -1
- package/scripts/validate-release-manifest.ts +67 -0
package/bin/serve.js
CHANGED
|
@@ -751,7 +751,7 @@ function getHook(name) {
|
|
|
751
751
|
}
|
|
752
752
|
|
|
753
753
|
// src/lib/manifest.ts
|
|
754
|
-
import { existsSync as existsSync2, mkdirSync, readFileSync, readdirSync, realpathSync, writeFileSync } from "fs";
|
|
754
|
+
import { existsSync as existsSync2, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from "fs";
|
|
755
755
|
import { basename, dirname, isAbsolute, join as join3, normalize, resolve as resolve2, sep } from "path";
|
|
756
756
|
|
|
757
757
|
// node_modules/zod/v3/external.js
|
|
@@ -4799,6 +4799,7 @@ function compareVersions(a, b) {
|
|
|
4799
4799
|
|
|
4800
4800
|
// src/lib/manifest.ts
|
|
4801
4801
|
var HOOK_NAME_RE = /^[\w-]+$/;
|
|
4802
|
+
var INSTALL_RECORD_FILE = ".hooks-install.json";
|
|
4802
4803
|
var manifestSchema = exports_external.object({
|
|
4803
4804
|
name: exports_external.string().regex(HOOK_NAME_RE, "hook name must be /^[\\w-]+$/"),
|
|
4804
4805
|
version: exports_external.string().regex(SEMVER_PATTERN, "version must be full semver (e.g. 1.2.3 or 1.2.3-beta.1)"),
|
|
@@ -4945,9 +4946,9 @@ function readdirSafe(dir) {
|
|
|
4945
4946
|
}
|
|
4946
4947
|
|
|
4947
4948
|
// src/lib/store.ts
|
|
4948
|
-
import { createHash as
|
|
4949
|
-
import { existsSync as
|
|
4950
|
-
import { join as
|
|
4949
|
+
import { createHash as createHash4 } from "crypto";
|
|
4950
|
+
import { existsSync as existsSync7, mkdirSync as mkdirSync5, readFileSync as readFileSync5, writeFileSync as writeFileSync3, renameSync as renameSync3, lstatSync as lstatSync3 } from "fs";
|
|
4951
|
+
import { join as join9 } from "path";
|
|
4951
4952
|
import { readFile } from "fs/promises";
|
|
4952
4953
|
|
|
4953
4954
|
// src/db/index.ts
|
|
@@ -5346,9 +5347,352 @@ function validateRegistryArtifact(value) {
|
|
|
5346
5347
|
}
|
|
5347
5348
|
|
|
5348
5349
|
// src/lib/store.ts
|
|
5349
|
-
import { randomBytes } from "crypto";
|
|
5350
|
+
import { randomBytes as randomBytes3 } from "crypto";
|
|
5351
|
+
|
|
5352
|
+
// src/lib/resolve.ts
|
|
5353
|
+
import { dirname as dirname2, join as join6 } from "path";
|
|
5354
|
+
import { existsSync as existsSync5 } from "fs";
|
|
5355
|
+
import { fileURLToPath } from "url";
|
|
5356
|
+
function resolveBundledHooksDir(moduleDir = dirname2(fileURLToPath(import.meta.url))) {
|
|
5357
|
+
const sourceLayout = join6(moduleDir, "..", "..", "hooks");
|
|
5358
|
+
if (existsSync5(join6(sourceLayout, "hook-gitguard")))
|
|
5359
|
+
return sourceLayout;
|
|
5360
|
+
return join6(moduleDir, "..", "hooks");
|
|
5361
|
+
}
|
|
5362
|
+
function resolveHookDir(name) {
|
|
5363
|
+
const custom2 = readCustomManifest(name);
|
|
5364
|
+
if (custom2)
|
|
5365
|
+
return customHookDir(name);
|
|
5366
|
+
const meta = getHook(shortManifestName(name));
|
|
5367
|
+
if (!meta)
|
|
5368
|
+
return;
|
|
5369
|
+
const short = shortManifestName(name);
|
|
5370
|
+
const bundledBase = resolveBundledHooksDir();
|
|
5371
|
+
const direct = join6(bundledBase, short);
|
|
5372
|
+
if (existsSync5(direct))
|
|
5373
|
+
return direct;
|
|
5374
|
+
const prefixed = join6(bundledBase, `hook-${short}`);
|
|
5375
|
+
return existsSync5(prefixed) ? prefixed : undefined;
|
|
5376
|
+
}
|
|
5377
|
+
function resolveScriptPath(name) {
|
|
5378
|
+
const custom2 = readCustomManifest(name);
|
|
5379
|
+
if (custom2)
|
|
5380
|
+
return custom2.scriptPath;
|
|
5381
|
+
const meta = getHook(shortManifestName(name));
|
|
5382
|
+
if (meta?.bundledEntry) {
|
|
5383
|
+
if (!/^bin\/hooks\/[a-z0-9-]+\.js$/.test(meta.bundledEntry))
|
|
5384
|
+
return;
|
|
5385
|
+
const bundle = join6(resolveBundledHooksDir(), "..", meta.bundledEntry);
|
|
5386
|
+
return existsSync5(bundle) ? bundle : undefined;
|
|
5387
|
+
}
|
|
5388
|
+
const dir = resolveHookDir(name);
|
|
5389
|
+
if (!dir)
|
|
5390
|
+
return;
|
|
5391
|
+
const script = join6(dir, "src", "hook.ts");
|
|
5392
|
+
return existsSync5(script) ? script : undefined;
|
|
5393
|
+
}
|
|
5394
|
+
function resolveHookMeta(name) {
|
|
5395
|
+
const custom2 = readCustomManifest(name);
|
|
5396
|
+
if (custom2) {
|
|
5397
|
+
const { manifest } = custom2;
|
|
5398
|
+
return {
|
|
5399
|
+
name: shortManifestName(manifest.name),
|
|
5400
|
+
displayName: manifest.description ? manifest.name : manifest.name,
|
|
5401
|
+
description: manifest.description ?? "Custom hook",
|
|
5402
|
+
version: manifest.version,
|
|
5403
|
+
category: "Workflow Automation",
|
|
5404
|
+
event: manifest.events[0] ?? "PostToolUse",
|
|
5405
|
+
events: manifest.events,
|
|
5406
|
+
matcher: "",
|
|
5407
|
+
tags: ["custom"],
|
|
5408
|
+
nativeTargetDispatch: manifest.nativeTargetDispatch,
|
|
5409
|
+
requiresFinalMessage: manifest.requires_final_message,
|
|
5410
|
+
requiresBlock: manifest.requires_block,
|
|
5411
|
+
timeoutSeconds: manifest.timeout_ms === undefined ? undefined : Math.ceil(manifest.timeout_ms / 1000)
|
|
5412
|
+
};
|
|
5413
|
+
}
|
|
5414
|
+
return getHook(shortManifestName(name));
|
|
5415
|
+
}
|
|
5416
|
+
function resolveHook(name) {
|
|
5417
|
+
const custom2 = readCustomManifest(name);
|
|
5418
|
+
if (custom2) {
|
|
5419
|
+
const meta2 = resolveHookMeta(name);
|
|
5420
|
+
return {
|
|
5421
|
+
name: shortManifestName(custom2.manifest.name),
|
|
5422
|
+
source: "custom",
|
|
5423
|
+
version: custom2.manifest.version,
|
|
5424
|
+
events: custom2.manifest.events,
|
|
5425
|
+
description: custom2.manifest.description ?? "Custom hook",
|
|
5426
|
+
scriptPath: custom2.scriptPath,
|
|
5427
|
+
meta: meta2,
|
|
5428
|
+
timeoutMs: custom2.manifest.timeout_ms ?? null
|
|
5429
|
+
};
|
|
5430
|
+
}
|
|
5431
|
+
const meta = getHook(shortManifestName(name));
|
|
5432
|
+
const scriptPath = resolveScriptPath(name);
|
|
5433
|
+
if (!meta || !scriptPath)
|
|
5434
|
+
return;
|
|
5435
|
+
return {
|
|
5436
|
+
name: shortManifestName(name),
|
|
5437
|
+
source: "bundled",
|
|
5438
|
+
version: meta.version,
|
|
5439
|
+
events: meta.events && meta.events.length > 0 ? meta.events : [meta.event],
|
|
5440
|
+
description: meta.description,
|
|
5441
|
+
scriptPath,
|
|
5442
|
+
meta,
|
|
5443
|
+
timeoutMs: null
|
|
5444
|
+
};
|
|
5445
|
+
}
|
|
5446
|
+
|
|
5447
|
+
// src/lib/release-manifest.ts
|
|
5448
|
+
import { createHash as createHash2, randomBytes } from "crypto";
|
|
5449
|
+
import { existsSync as existsSync6, lstatSync, mkdirSync as mkdirSync3, readFileSync as readFileSync3, realpathSync as realpathSync2, renameSync, writeFileSync as writeFileSync2 } from "fs";
|
|
5450
|
+
import { basename as basename2, dirname as dirname3, join as join7, relative, resolve as resolve3, sep as sep2 } from "path";
|
|
5451
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
5452
|
+
var RELEASE_MANIFEST_SCHEMA = 1;
|
|
5453
|
+
var RELEASE_MANIFEST_RELATIVE_PATH = "bin/release-manifest.json";
|
|
5454
|
+
|
|
5455
|
+
class ReleaseManifestError extends Error {
|
|
5456
|
+
constructor(message) {
|
|
5457
|
+
super(message);
|
|
5458
|
+
this.name = "ReleaseManifestError";
|
|
5459
|
+
}
|
|
5460
|
+
}
|
|
5461
|
+
function sha256(bytes) {
|
|
5462
|
+
return createHash2("sha256").update(bytes).digest("hex");
|
|
5463
|
+
}
|
|
5464
|
+
function isWithin2(child, parent) {
|
|
5465
|
+
return child === parent || child.startsWith(parent + sep2);
|
|
5466
|
+
}
|
|
5467
|
+
function parseReleaseManifest(raw, path) {
|
|
5468
|
+
let parsed;
|
|
5469
|
+
try {
|
|
5470
|
+
parsed = JSON.parse(raw);
|
|
5471
|
+
} catch {
|
|
5472
|
+
throw new ReleaseManifestError(`release manifest (${path}) is not valid JSON`);
|
|
5473
|
+
}
|
|
5474
|
+
const value = parsed;
|
|
5475
|
+
if (value === null || typeof value !== "object" || value.schema !== RELEASE_MANIFEST_SCHEMA || typeof value.package !== "string" || typeof value.version !== "string" || value.hooks === null || typeof value.hooks !== "object" || Array.isArray(value.hooks)) {
|
|
5476
|
+
throw new ReleaseManifestError(`release manifest (${path}) is malformed`);
|
|
5477
|
+
}
|
|
5478
|
+
for (const [name, entry] of Object.entries(value.hooks)) {
|
|
5479
|
+
if (entry === null || typeof entry !== "object" || typeof entry.version !== "string" || typeof entry.script !== "string" || typeof entry.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(entry.sha256)) {
|
|
5480
|
+
throw new ReleaseManifestError(`release manifest (${path}) has a malformed entry for '${name}'`);
|
|
5481
|
+
}
|
|
5482
|
+
}
|
|
5483
|
+
return value;
|
|
5484
|
+
}
|
|
5485
|
+
function releaseRootOf(moduleDir = dirname3(fileURLToPath2(import.meta.url))) {
|
|
5486
|
+
for (let dir = resolve3(moduleDir);; dir = dirname3(dir)) {
|
|
5487
|
+
const name = basename2(dir);
|
|
5488
|
+
if (name === "bin" || name === "dist") {
|
|
5489
|
+
const root = dirname3(dir);
|
|
5490
|
+
if (existsSync6(join7(root, "package.json")) && existsSync6(join7(root, "hooks")))
|
|
5491
|
+
return root;
|
|
5492
|
+
}
|
|
5493
|
+
if (dirname3(dir) === dir)
|
|
5494
|
+
break;
|
|
5495
|
+
}
|
|
5496
|
+
return null;
|
|
5497
|
+
}
|
|
5498
|
+
var override;
|
|
5499
|
+
function loadReleaseAt(root) {
|
|
5500
|
+
const path = join7(root, RELEASE_MANIFEST_RELATIVE_PATH);
|
|
5501
|
+
let raw;
|
|
5502
|
+
try {
|
|
5503
|
+
if (!lstatSync(path).isFile())
|
|
5504
|
+
throw new ReleaseManifestError(`release manifest (${path}) is not a regular file`);
|
|
5505
|
+
raw = readFileSync3(path);
|
|
5506
|
+
} catch (error) {
|
|
5507
|
+
if (error.code === "ENOENT")
|
|
5508
|
+
return null;
|
|
5509
|
+
throw error instanceof ReleaseManifestError ? error : new ReleaseManifestError(`release manifest (${path}) could not be read`);
|
|
5510
|
+
}
|
|
5511
|
+
return { root: realpathSync2(root), path, sha256: sha256(raw), manifest: parseReleaseManifest(raw.toString("utf8"), path) };
|
|
5512
|
+
}
|
|
5513
|
+
function currentRelease() {
|
|
5514
|
+
if (override !== undefined)
|
|
5515
|
+
return override;
|
|
5516
|
+
const root = releaseRootOf();
|
|
5517
|
+
return root ? loadReleaseAt(root) : null;
|
|
5518
|
+
}
|
|
5519
|
+
function anchorsDir() {
|
|
5520
|
+
return join7(getHooksDataDir(), "release-anchors");
|
|
5521
|
+
}
|
|
5522
|
+
function anchorPathFor(release) {
|
|
5523
|
+
return join7(anchorsDir(), `${sha256(release.root)}.json`);
|
|
5524
|
+
}
|
|
5525
|
+
function anchorStateOf(release) {
|
|
5526
|
+
const path = anchorPathFor(release);
|
|
5527
|
+
let raw;
|
|
5528
|
+
try {
|
|
5529
|
+
if (!lstatSync(path).isFile())
|
|
5530
|
+
return { state: "invalid", path };
|
|
5531
|
+
raw = readFileSync3(path, "utf8");
|
|
5532
|
+
} catch (error) {
|
|
5533
|
+
if (error.code === "ENOENT")
|
|
5534
|
+
return { state: "absent", path };
|
|
5535
|
+
return { state: "invalid", path };
|
|
5536
|
+
}
|
|
5537
|
+
let anchor;
|
|
5538
|
+
try {
|
|
5539
|
+
anchor = JSON.parse(raw);
|
|
5540
|
+
} catch {
|
|
5541
|
+
return { state: "invalid", path };
|
|
5542
|
+
}
|
|
5543
|
+
if (anchor === null || typeof anchor !== "object" || anchor.schema !== 1 || anchor.package_root !== release.root || typeof anchor.manifest_sha256 !== "string" || !/^[0-9a-f]{64}$/.test(anchor.manifest_sha256)) {
|
|
5544
|
+
return { state: "invalid", path };
|
|
5545
|
+
}
|
|
5546
|
+
if (anchor.manifest_sha256 !== release.sha256) {
|
|
5547
|
+
return { state: "mismatch", path, expected: anchor.manifest_sha256, actual: release.sha256 };
|
|
5548
|
+
}
|
|
5549
|
+
return { state: "match", path, anchor };
|
|
5550
|
+
}
|
|
5551
|
+
function releaseTrustFor(name, actual, scriptPath) {
|
|
5552
|
+
let release;
|
|
5553
|
+
try {
|
|
5554
|
+
release = currentRelease();
|
|
5555
|
+
} catch (error) {
|
|
5556
|
+
if (!(error instanceof ReleaseManifestError))
|
|
5557
|
+
throw error;
|
|
5558
|
+
return { governed: true, ok: false, release: "unreadable", expected: "release-manifest-invalid", reason: "manifest" };
|
|
5559
|
+
}
|
|
5560
|
+
if (!release)
|
|
5561
|
+
return { governed: false };
|
|
5562
|
+
const label = `${release.manifest.package}@${release.manifest.version}`;
|
|
5563
|
+
if (scriptPath !== undefined) {
|
|
5564
|
+
let real;
|
|
5565
|
+
try {
|
|
5566
|
+
real = realpathSync2(scriptPath);
|
|
5567
|
+
} catch {
|
|
5568
|
+
real = resolve3(scriptPath);
|
|
5569
|
+
}
|
|
5570
|
+
if (!isWithin2(real, release.root))
|
|
5571
|
+
return { governed: false };
|
|
5572
|
+
const entry2 = release.manifest.hooks[name];
|
|
5573
|
+
if (entry2 && relative(release.root, real).split(sep2).join("/") !== entry2.script) {
|
|
5574
|
+
return { governed: true, ok: false, release: label, expected: "release-manifest-script-mismatch", reason: "manifest" };
|
|
5575
|
+
}
|
|
5576
|
+
}
|
|
5577
|
+
const entry = release.manifest.hooks[name];
|
|
5578
|
+
if (!entry)
|
|
5579
|
+
return { governed: true, ok: false, release: label, expected: "release-manifest-entry-missing", reason: "unlisted" };
|
|
5580
|
+
const anchor = anchorStateOf(release);
|
|
5581
|
+
if (anchor.state === "mismatch" || anchor.state === "invalid") {
|
|
5582
|
+
return { governed: true, ok: false, release: label, expected: "release-manifest-anchor-mismatch", reason: "anchor" };
|
|
5583
|
+
}
|
|
5584
|
+
if (entry.sha256 !== actual)
|
|
5585
|
+
return { governed: true, ok: false, release: label, expected: entry.sha256, reason: "content" };
|
|
5586
|
+
return { governed: true, ok: true, release: label, expected: entry.sha256, anchored: anchor.state === "match" };
|
|
5587
|
+
}
|
|
5588
|
+
|
|
5589
|
+
// src/lib/install-record.ts
|
|
5590
|
+
import { createHash as createHash3, randomBytes as randomBytes2 } from "crypto";
|
|
5591
|
+
import { closeSync, fsyncSync, lstatSync as lstatSync2, mkdirSync as mkdirSync4, openSync, readFileSync as readFileSync4, renameSync as renameSync2, rmSync as rmSync2, writeSync } from "fs";
|
|
5592
|
+
import { dirname as dirname4, isAbsolute as isAbsolute2, join as join8, resolve as resolve4, sep as sep3 } from "path";
|
|
5593
|
+
var INSTALL_RECORD_SCHEMA = 1;
|
|
5594
|
+
|
|
5595
|
+
class InstallRecordError extends Error {
|
|
5596
|
+
constructor(message) {
|
|
5597
|
+
super(message);
|
|
5598
|
+
this.name = "InstallRecordError";
|
|
5599
|
+
}
|
|
5600
|
+
}
|
|
5601
|
+
function sha2562(bytes) {
|
|
5602
|
+
return createHash3("sha256").update(bytes).digest("hex");
|
|
5603
|
+
}
|
|
5604
|
+
var NOT_A_FILE = "not-a-regular-file";
|
|
5605
|
+
function hashOrNull(path) {
|
|
5606
|
+
try {
|
|
5607
|
+
if (!lstatSync2(path).isFile())
|
|
5608
|
+
return NOT_A_FILE;
|
|
5609
|
+
return sha2562(readFileSync4(path));
|
|
5610
|
+
} catch (error) {
|
|
5611
|
+
if (error.code === "ENOENT")
|
|
5612
|
+
return null;
|
|
5613
|
+
throw error;
|
|
5614
|
+
}
|
|
5615
|
+
}
|
|
5616
|
+
function writeFileAtomic(path, bytes, mode) {
|
|
5617
|
+
const tmp = `${path}.tmp-${randomBytes2(8).toString("hex")}`;
|
|
5618
|
+
const fd = openSync(tmp, "wx", mode);
|
|
5619
|
+
try {
|
|
5620
|
+
writeSync(fd, typeof bytes === "string" ? Buffer.from(bytes, "utf8") : bytes);
|
|
5621
|
+
fsyncSync(fd);
|
|
5622
|
+
} finally {
|
|
5623
|
+
closeSync(fd);
|
|
5624
|
+
}
|
|
5625
|
+
try {
|
|
5626
|
+
renameSync2(tmp, path);
|
|
5627
|
+
} catch (error) {
|
|
5628
|
+
rmSync2(tmp, { force: true });
|
|
5629
|
+
throw error;
|
|
5630
|
+
}
|
|
5631
|
+
}
|
|
5632
|
+
function scriptPathIn(dir, rel) {
|
|
5633
|
+
if (isAbsolute2(rel))
|
|
5634
|
+
throw new ScriptContainmentError(rel, dir);
|
|
5635
|
+
const target = resolve4(dir, rel);
|
|
5636
|
+
if (target === resolve4(dir) || !target.startsWith(resolve4(dir) + sep3))
|
|
5637
|
+
throw new ScriptContainmentError(rel, dir);
|
|
5638
|
+
if (target === join8(resolve4(dir), "manifest.json") || target === join8(resolve4(dir), INSTALL_RECORD_FILE)) {
|
|
5639
|
+
throw new ScriptContainmentError(rel, dir);
|
|
5640
|
+
}
|
|
5641
|
+
return target;
|
|
5642
|
+
}
|
|
5643
|
+
function commitInstall(name, manifest, scriptContent, scriptRelPath, options) {
|
|
5644
|
+
const short = shortManifestName(name);
|
|
5645
|
+
const dir = customHookDir(short);
|
|
5646
|
+
if (scriptRelPath !== scriptRelFor(manifest)) {
|
|
5647
|
+
throw new InstallRecordError(`'${short}' cannot be installed: script path '${scriptRelPath}' is not the one its manifest resolves to`);
|
|
5648
|
+
}
|
|
5649
|
+
const scriptPath = scriptPathIn(dir, scriptRelPath);
|
|
5650
|
+
mkdirSync4(dir, { recursive: true });
|
|
5651
|
+
assertContained(scriptPath, dir, scriptRelPath);
|
|
5652
|
+
const scriptBytes = typeof scriptContent === "string" ? Buffer.from(scriptContent, "utf8") : scriptContent;
|
|
5653
|
+
const manifestBytes = options.manifestBytes ?? Buffer.from(JSON.stringify(manifest, null, 2) + `
|
|
5654
|
+
`, "utf8");
|
|
5655
|
+
const manifestPath = join8(dir, "manifest.json");
|
|
5656
|
+
const replaced = { script_sha256: hashOrNull(scriptPath), manifest_sha256: hashOrNull(manifestPath) };
|
|
5657
|
+
if (replaced.script_sha256 === NOT_A_FILE || replaced.manifest_sha256 === NOT_A_FILE) {
|
|
5658
|
+
throw new InstallRecordError(`'${short}' cannot be installed: its script or manifest path holds something that is not a regular file`);
|
|
5659
|
+
}
|
|
5660
|
+
const record = {
|
|
5661
|
+
schema: INSTALL_RECORD_SCHEMA,
|
|
5662
|
+
name: short,
|
|
5663
|
+
version: manifest.version,
|
|
5664
|
+
source: options.source,
|
|
5665
|
+
source_ref: options.sourceRef ?? null,
|
|
5666
|
+
installed_at: new Date().toISOString(),
|
|
5667
|
+
script: { path: scriptRelPath, sha256: sha2562(scriptBytes), content_base64: scriptBytes.toString("base64") },
|
|
5668
|
+
manifest: { sha256: sha2562(manifestBytes), content_base64: manifestBytes.toString("base64") },
|
|
5669
|
+
replaces: replaced
|
|
5670
|
+
};
|
|
5671
|
+
options.onStep?.("before-commit");
|
|
5672
|
+
writeFileAtomic(join8(dir, INSTALL_RECORD_FILE), JSON.stringify(record, null, 2) + `
|
|
5673
|
+
`, 384);
|
|
5674
|
+
options.onStep?.("record-committed");
|
|
5675
|
+
materialize(dir, record, options.onStep);
|
|
5676
|
+
return { dir, scriptPath, record };
|
|
5677
|
+
}
|
|
5678
|
+
function materialize(dir, record, onStep) {
|
|
5679
|
+
const scriptPath = scriptPathIn(dir, record.script.path);
|
|
5680
|
+
const scriptBytes = Buffer.from(record.script.content_base64, "base64");
|
|
5681
|
+
const manifestBytes = Buffer.from(record.manifest.content_base64, "base64");
|
|
5682
|
+
if (hashOrNull(scriptPath) !== record.script.sha256) {
|
|
5683
|
+
mkdirSync4(dirname4(scriptPath), { recursive: true });
|
|
5684
|
+
writeFileAtomic(scriptPath, scriptBytes, 420);
|
|
5685
|
+
}
|
|
5686
|
+
onStep?.("script-written");
|
|
5687
|
+
const manifestPath = join8(dir, "manifest.json");
|
|
5688
|
+
if (hashOrNull(manifestPath) !== record.manifest.sha256)
|
|
5689
|
+
writeFileAtomic(manifestPath, manifestBytes, 420);
|
|
5690
|
+
onStep?.("manifest-written");
|
|
5691
|
+
}
|
|
5692
|
+
|
|
5693
|
+
// src/lib/store.ts
|
|
5350
5694
|
function sha256Of(input) {
|
|
5351
|
-
return
|
|
5695
|
+
return createHash4("sha256").update(input).digest("hex");
|
|
5352
5696
|
}
|
|
5353
5697
|
async function sha256File(path) {
|
|
5354
5698
|
const buf = await readFile(path);
|
|
@@ -5408,11 +5752,11 @@ function assertLockShape(parsed, path) {
|
|
|
5408
5752
|
}
|
|
5409
5753
|
function readLock() {
|
|
5410
5754
|
const path = getLockPath();
|
|
5411
|
-
if (!
|
|
5755
|
+
if (!existsSync7(path))
|
|
5412
5756
|
return { hooks: {} };
|
|
5413
5757
|
let raw;
|
|
5414
5758
|
try {
|
|
5415
|
-
raw =
|
|
5759
|
+
raw = readFileSync5(path, "utf-8");
|
|
5416
5760
|
} catch {
|
|
5417
5761
|
throw new LockFileError(`hooks.lock (${path}) could not be read. Repair: fix permissions or move the file aside and run 'hooks sync'.`);
|
|
5418
5762
|
}
|
|
@@ -5427,15 +5771,15 @@ function readLock() {
|
|
|
5427
5771
|
}
|
|
5428
5772
|
function writeLock(lock) {
|
|
5429
5773
|
const path = getLockPath();
|
|
5430
|
-
|
|
5774
|
+
mkdirSync5(path.substring(0, path.lastIndexOf("/")) || ".", { recursive: true });
|
|
5431
5775
|
const sorted = {};
|
|
5432
5776
|
for (const name of Object.keys(lock.hooks).sort()) {
|
|
5433
5777
|
sorted[name] = lock.hooks[name];
|
|
5434
5778
|
}
|
|
5435
|
-
const tmp = `${path}.tmp-${
|
|
5436
|
-
|
|
5779
|
+
const tmp = `${path}.tmp-${randomBytes3(8).toString("hex")}`;
|
|
5780
|
+
writeFileSync3(tmp, JSON.stringify({ hooks: sorted }, null, 2) + `
|
|
5437
5781
|
`, "utf-8");
|
|
5438
|
-
|
|
5782
|
+
renameSync3(tmp, path);
|
|
5439
5783
|
return path;
|
|
5440
5784
|
}
|
|
5441
5785
|
function setPinnedHook(name, entry) {
|
|
@@ -5444,11 +5788,11 @@ function setPinnedHook(name, entry) {
|
|
|
5444
5788
|
return writeLock(lock);
|
|
5445
5789
|
}
|
|
5446
5790
|
function registryManagedMarker(name) {
|
|
5447
|
-
return
|
|
5791
|
+
return join9(getHooksDataDir(), "registry-managed", sha256Of(name) + ".json");
|
|
5448
5792
|
}
|
|
5449
5793
|
function isRegistryManaged(name) {
|
|
5450
5794
|
try {
|
|
5451
|
-
|
|
5795
|
+
lstatSync3(registryManagedMarker(name));
|
|
5452
5796
|
return true;
|
|
5453
5797
|
} catch (error) {
|
|
5454
5798
|
if (error.code === "ENOENT")
|
|
@@ -5457,10 +5801,23 @@ function isRegistryManaged(name) {
|
|
|
5457
5801
|
}
|
|
5458
5802
|
}
|
|
5459
5803
|
function retrustHook(name, scriptPath, version, source) {
|
|
5460
|
-
const
|
|
5461
|
-
const
|
|
5462
|
-
|
|
5804
|
+
const scriptBytes = readFileSync5(scriptPath);
|
|
5805
|
+
const actual = sha256Of(scriptBytes);
|
|
5806
|
+
const registryManaged = isRegistryManaged(name);
|
|
5807
|
+
const custom2 = readCustomManifest(name);
|
|
5808
|
+
if (registryManaged && !custom2)
|
|
5463
5809
|
throw new Error("REGISTRY_MANIFEST_REQUIRED");
|
|
5810
|
+
let release;
|
|
5811
|
+
if (custom2 && !registryManaged) {
|
|
5812
|
+
commitInstall(custom2.manifest.name, custom2.manifest, scriptBytes, scriptRelFor(custom2.manifest), {
|
|
5813
|
+
source: "hooks-trust",
|
|
5814
|
+
manifestBytes: readFileSync5(join9(customHookDir(name), "manifest.json"))
|
|
5815
|
+
});
|
|
5816
|
+
} else if (!custom2 && getHook(shortManifestName(name))) {
|
|
5817
|
+
const decided = releaseTrustFor(shortManifestName(name), actual, scriptPath);
|
|
5818
|
+
if (decided.governed)
|
|
5819
|
+
release = decided.release;
|
|
5820
|
+
}
|
|
5464
5821
|
const db = storeDb();
|
|
5465
5822
|
if (db) {
|
|
5466
5823
|
upsertHookRecord(db, {
|
|
@@ -5471,121 +5828,32 @@ function retrustHook(name, scriptPath, version, source) {
|
|
|
5471
5828
|
last_verified_at: new Date().toISOString()
|
|
5472
5829
|
});
|
|
5473
5830
|
}
|
|
5474
|
-
setPinnedHook(name, {
|
|
5831
|
+
setPinnedHook(name, {
|
|
5832
|
+
version,
|
|
5833
|
+
sha256: actual,
|
|
5834
|
+
source,
|
|
5835
|
+
...registryManaged && custom2 ? { manifest_sha256: registryDigest(custom2.manifest) } : {},
|
|
5836
|
+
...release ? { release } : {}
|
|
5837
|
+
});
|
|
5475
5838
|
return { ok: true, pinned: true, expected: actual, actual, name };
|
|
5476
5839
|
}
|
|
5477
5840
|
|
|
5478
|
-
// src/lib/resolve.ts
|
|
5479
|
-
import { dirname as dirname2, join as join7 } from "path";
|
|
5480
|
-
import { existsSync as existsSync6 } from "fs";
|
|
5481
|
-
import { fileURLToPath } from "url";
|
|
5482
|
-
function resolveBundledHooksDir(moduleDir = dirname2(fileURLToPath(import.meta.url))) {
|
|
5483
|
-
const sourceLayout = join7(moduleDir, "..", "..", "hooks");
|
|
5484
|
-
if (existsSync6(join7(sourceLayout, "hook-gitguard")))
|
|
5485
|
-
return sourceLayout;
|
|
5486
|
-
return join7(moduleDir, "..", "hooks");
|
|
5487
|
-
}
|
|
5488
|
-
function resolveHookDir(name) {
|
|
5489
|
-
const custom2 = readCustomManifest(name);
|
|
5490
|
-
if (custom2)
|
|
5491
|
-
return customHookDir(name);
|
|
5492
|
-
const meta = getHook(shortManifestName(name));
|
|
5493
|
-
if (!meta)
|
|
5494
|
-
return;
|
|
5495
|
-
const short = shortManifestName(name);
|
|
5496
|
-
const bundledBase = resolveBundledHooksDir();
|
|
5497
|
-
const direct = join7(bundledBase, short);
|
|
5498
|
-
if (existsSync6(direct))
|
|
5499
|
-
return direct;
|
|
5500
|
-
const prefixed = join7(bundledBase, `hook-${short}`);
|
|
5501
|
-
return existsSync6(prefixed) ? prefixed : undefined;
|
|
5502
|
-
}
|
|
5503
|
-
function resolveScriptPath(name) {
|
|
5504
|
-
const custom2 = readCustomManifest(name);
|
|
5505
|
-
if (custom2)
|
|
5506
|
-
return custom2.scriptPath;
|
|
5507
|
-
const meta = getHook(shortManifestName(name));
|
|
5508
|
-
if (meta?.bundledEntry) {
|
|
5509
|
-
if (!/^bin\/hooks\/[a-z0-9-]+\.js$/.test(meta.bundledEntry))
|
|
5510
|
-
return;
|
|
5511
|
-
const bundle = join7(resolveBundledHooksDir(), "..", meta.bundledEntry);
|
|
5512
|
-
return existsSync6(bundle) ? bundle : undefined;
|
|
5513
|
-
}
|
|
5514
|
-
const dir = resolveHookDir(name);
|
|
5515
|
-
if (!dir)
|
|
5516
|
-
return;
|
|
5517
|
-
const script = join7(dir, "src", "hook.ts");
|
|
5518
|
-
return existsSync6(script) ? script : undefined;
|
|
5519
|
-
}
|
|
5520
|
-
function resolveHookMeta(name) {
|
|
5521
|
-
const custom2 = readCustomManifest(name);
|
|
5522
|
-
if (custom2) {
|
|
5523
|
-
const { manifest } = custom2;
|
|
5524
|
-
return {
|
|
5525
|
-
name: shortManifestName(manifest.name),
|
|
5526
|
-
displayName: manifest.description ? manifest.name : manifest.name,
|
|
5527
|
-
description: manifest.description ?? "Custom hook",
|
|
5528
|
-
version: manifest.version,
|
|
5529
|
-
category: "Workflow Automation",
|
|
5530
|
-
event: manifest.events[0] ?? "PostToolUse",
|
|
5531
|
-
events: manifest.events,
|
|
5532
|
-
matcher: "",
|
|
5533
|
-
tags: ["custom"],
|
|
5534
|
-
nativeTargetDispatch: manifest.nativeTargetDispatch,
|
|
5535
|
-
requiresFinalMessage: manifest.requires_final_message,
|
|
5536
|
-
requiresBlock: manifest.requires_block,
|
|
5537
|
-
timeoutSeconds: manifest.timeout_ms === undefined ? undefined : Math.ceil(manifest.timeout_ms / 1000)
|
|
5538
|
-
};
|
|
5539
|
-
}
|
|
5540
|
-
return getHook(shortManifestName(name));
|
|
5541
|
-
}
|
|
5542
|
-
function resolveHook(name) {
|
|
5543
|
-
const custom2 = readCustomManifest(name);
|
|
5544
|
-
if (custom2) {
|
|
5545
|
-
const meta2 = resolveHookMeta(name);
|
|
5546
|
-
return {
|
|
5547
|
-
name: shortManifestName(custom2.manifest.name),
|
|
5548
|
-
source: "custom",
|
|
5549
|
-
version: custom2.manifest.version,
|
|
5550
|
-
events: custom2.manifest.events,
|
|
5551
|
-
description: custom2.manifest.description ?? "Custom hook",
|
|
5552
|
-
scriptPath: custom2.scriptPath,
|
|
5553
|
-
meta: meta2,
|
|
5554
|
-
timeoutMs: custom2.manifest.timeout_ms ?? null
|
|
5555
|
-
};
|
|
5556
|
-
}
|
|
5557
|
-
const meta = getHook(shortManifestName(name));
|
|
5558
|
-
const scriptPath = resolveScriptPath(name);
|
|
5559
|
-
if (!meta || !scriptPath)
|
|
5560
|
-
return;
|
|
5561
|
-
return {
|
|
5562
|
-
name: shortManifestName(name),
|
|
5563
|
-
source: "bundled",
|
|
5564
|
-
version: meta.version,
|
|
5565
|
-
events: meta.events && meta.events.length > 0 ? meta.events : [meta.event],
|
|
5566
|
-
description: meta.description,
|
|
5567
|
-
scriptPath,
|
|
5568
|
-
meta,
|
|
5569
|
-
timeoutMs: null
|
|
5570
|
-
};
|
|
5571
|
-
}
|
|
5572
|
-
|
|
5573
5841
|
// src/serve.ts
|
|
5574
|
-
import { readFileSync as
|
|
5575
|
-
import { dirname as
|
|
5576
|
-
import { fileURLToPath as
|
|
5842
|
+
import { readFileSync as readFileSync7 } from "fs";
|
|
5843
|
+
import { dirname as dirname6, join as join11 } from "path";
|
|
5844
|
+
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
5577
5845
|
|
|
5578
5846
|
// node_modules/@hasna/contracts/dist/client/transport.js
|
|
5579
5847
|
import { spawnSync } from "child_process";
|
|
5580
5848
|
import { closeSync as closeSync2, fstatSync as fstatSync2, openSync as openSync2, readFileSync as readFileSync22 } from "fs";
|
|
5581
5849
|
import { O_NOFOLLOW as O_NOFOLLOW2, O_NONBLOCK as O_NONBLOCK2, O_RDONLY as O_RDONLY2 } from "constants";
|
|
5582
5850
|
import { hostname as osHostname } from "os";
|
|
5583
|
-
import { isAbsolute as
|
|
5851
|
+
import { isAbsolute as isAbsolute3, join as join22 } from "path";
|
|
5584
5852
|
import { createRequire } from "module";
|
|
5585
|
-
import { fileURLToPath as
|
|
5586
|
-
import { closeSync, fstatSync, lstatSync as
|
|
5853
|
+
import { fileURLToPath as fileURLToPath22 } from "url";
|
|
5854
|
+
import { closeSync as closeSync3, fstatSync, lstatSync as lstatSync4, openSync as openSync3, readFileSync as readFileSync6, realpathSync as realpathSync3, statSync } from "fs";
|
|
5587
5855
|
import { O_NOFOLLOW, O_NONBLOCK, O_RDONLY } from "constants";
|
|
5588
|
-
import { basename as
|
|
5856
|
+
import { basename as basename3, dirname as dirname5, join as join10, relative as relative2, sep as sep4 } from "path";
|
|
5589
5857
|
import { fileURLToPath as fileURLToPath3, pathToFileURL } from "url";
|
|
5590
5858
|
function envToken(name) {
|
|
5591
5859
|
return name.toUpperCase().replace(/-/g, "_");
|
|
@@ -5662,16 +5930,16 @@ function o(e2, r2, t2) {
|
|
|
5662
5930
|
var PACKAGE = "@hasna/secrets";
|
|
5663
5931
|
var MAX_PACKAGE_BYTES = 1024 * 1024;
|
|
5664
5932
|
function entryPoint(directory) {
|
|
5665
|
-
const root =
|
|
5666
|
-
const fd =
|
|
5933
|
+
const root = realpathSync3(directory);
|
|
5934
|
+
const fd = openSync3(join10(root, "package.json"), O_RDONLY | O_NOFOLLOW | O_NONBLOCK);
|
|
5667
5935
|
let pkg;
|
|
5668
5936
|
try {
|
|
5669
5937
|
const stat = fstatSync(fd);
|
|
5670
5938
|
if (!stat.isFile() || stat.size > MAX_PACKAGE_BYTES)
|
|
5671
5939
|
throw new Error("Invalid Secrets package metadata");
|
|
5672
|
-
pkg = JSON.parse(
|
|
5940
|
+
pkg = JSON.parse(readFileSync6(fd, "utf8"));
|
|
5673
5941
|
} finally {
|
|
5674
|
-
|
|
5942
|
+
closeSync3(fd);
|
|
5675
5943
|
}
|
|
5676
5944
|
if (!pkg || typeof pkg !== "object" || !("name" in pkg) || pkg.name !== PACKAGE) {
|
|
5677
5945
|
throw new Error("Invalid Secrets package identity");
|
|
@@ -5683,21 +5951,21 @@ function entryPoint(directory) {
|
|
|
5683
5951
|
if (/[\\%?#\0]/.test(target) || parts.some((part) => !part || part === "." || part === ".." || part === "node_modules")) {
|
|
5684
5952
|
throw new Error("Invalid Secrets import export");
|
|
5685
5953
|
}
|
|
5686
|
-
const file =
|
|
5687
|
-
const within =
|
|
5688
|
-
if (!within || within === ".." || within.startsWith(`..${
|
|
5954
|
+
const file = realpathSync3(join10(root, ...parts));
|
|
5955
|
+
const within = relative2(root, file);
|
|
5956
|
+
if (!within || within === ".." || within.startsWith(`..${sep4}`) || !statSync(file).isFile()) {
|
|
5689
5957
|
throw new Error("Secrets import export escapes its package or is not a file");
|
|
5690
5958
|
}
|
|
5691
5959
|
return pathToFileURL(file).href;
|
|
5692
5960
|
}
|
|
5693
5961
|
function resolveInstalledSecrets(parentUrl) {
|
|
5694
|
-
let directory =
|
|
5962
|
+
let directory = dirname5(fileURLToPath3(parentUrl));
|
|
5695
5963
|
for (;; ) {
|
|
5696
|
-
if (
|
|
5697
|
-
const candidate =
|
|
5964
|
+
if (basename3(directory) !== "node_modules") {
|
|
5965
|
+
const candidate = join10(directory, "node_modules", PACKAGE);
|
|
5698
5966
|
let absent = false;
|
|
5699
5967
|
try {
|
|
5700
|
-
|
|
5968
|
+
lstatSync4(candidate);
|
|
5701
5969
|
} catch (error) {
|
|
5702
5970
|
if (error.code !== "ENOENT")
|
|
5703
5971
|
throw error;
|
|
@@ -5706,7 +5974,7 @@ function resolveInstalledSecrets(parentUrl) {
|
|
|
5706
5974
|
if (!absent)
|
|
5707
5975
|
return entryPoint(candidate);
|
|
5708
5976
|
}
|
|
5709
|
-
const parent =
|
|
5977
|
+
const parent = dirname5(directory);
|
|
5710
5978
|
if (parent === directory)
|
|
5711
5979
|
throw new Error("Secrets SDK is not installed for this consumer");
|
|
5712
5980
|
directory = parent;
|
|
@@ -5753,12 +6021,12 @@ function homeDir(env) {
|
|
|
5753
6021
|
}
|
|
5754
6022
|
function absoluteOverride(env, key) {
|
|
5755
6023
|
const value = env[key]?.trim();
|
|
5756
|
-
return value &&
|
|
6024
|
+
return value && isAbsolute3(value) ? value : null;
|
|
5757
6025
|
}
|
|
5758
6026
|
function hasnaHomeDir(env) {
|
|
5759
|
-
const
|
|
5760
|
-
if (
|
|
5761
|
-
return
|
|
6027
|
+
const override2 = absoluteOverride(env, HASNA_HOME_ENV_KEY);
|
|
6028
|
+
if (override2)
|
|
6029
|
+
return override2;
|
|
5762
6030
|
const home = homeDir(env);
|
|
5763
6031
|
return home ? join22(home, HASNA_HOME_DIR) : null;
|
|
5764
6032
|
}
|
|
@@ -6067,13 +6335,13 @@ function resolveCredential(name, env, options = {}) {
|
|
|
6067
6335
|
const overrideKeyName = credentialOverrideEnvKey(name);
|
|
6068
6336
|
const overrideRaw = Object.prototype.hasOwnProperty.call(env, overrideKeyName) ? env[overrideKeyName] : undefined;
|
|
6069
6337
|
if (overrideRaw !== undefined) {
|
|
6070
|
-
const
|
|
6071
|
-
if (!
|
|
6338
|
+
const override2 = overrideRaw.trim();
|
|
6339
|
+
if (!override2) {
|
|
6072
6340
|
throw new CredentialResolutionError(name, `${overrideKeyName} is set but empty. It is a deliberate override, so it is not resolved around: ` + `either give it a real key or unset it to fall back to the credential on disk.`, [overrideKeyName]);
|
|
6073
6341
|
}
|
|
6074
|
-
assertUsableCredential(name, overrideKeyName,
|
|
6342
|
+
assertUsableCredential(name, overrideKeyName, override2);
|
|
6075
6343
|
return sealCredential({
|
|
6076
|
-
apiKey:
|
|
6344
|
+
apiKey: override2,
|
|
6077
6345
|
tier: "override",
|
|
6078
6346
|
source: overrideKeyName,
|
|
6079
6347
|
deliberate: true,
|
|
@@ -6210,7 +6478,7 @@ async function completePointerCredential(name, pointerResolution, env = process.
|
|
|
6210
6478
|
let secretsSdk;
|
|
6211
6479
|
try {
|
|
6212
6480
|
const sdkUrl = resolveInstalledSecrets(import.meta.url);
|
|
6213
|
-
secretsSdk = requireSecretsSdk(
|
|
6481
|
+
secretsSdk = requireSecretsSdk(fileURLToPath22(sdkUrl));
|
|
6214
6482
|
} catch {
|
|
6215
6483
|
throw new CredentialResolutionError(name, `${pointerEnvKey} names vault item '${vaultKey}', but the secrets SDK (@hasna/secrets) is not installed ` + `in this process. A vault pointer is TERMINAL: install @hasna/secrets to resolve it, or unset ${pointerEnvKey}.`, [pointerEnvKey]);
|
|
6216
6484
|
}
|
|
@@ -6497,6 +6765,34 @@ function buildOpenApiDocument(version) {
|
|
|
6497
6765
|
}
|
|
6498
6766
|
}
|
|
6499
6767
|
},
|
|
6768
|
+
"/v1/events/errors": {
|
|
6769
|
+
post: {
|
|
6770
|
+
summary: "Append one failed hook run (error-only, no content); 120 per key per minute",
|
|
6771
|
+
operationId: "postErrorEvent",
|
|
6772
|
+
security: [{ apiKey: [] }],
|
|
6773
|
+
requestBody: { required: true, content: { "application/json": { schema: { type: "object", additionalProperties: false, required: ["hook", "event", "class", "exit_code", "duration_ms", "station", "harness", "hooks_version", "at"], properties: {
|
|
6774
|
+
hook: { type: "string", pattern: "^[a-z0-9][a-z0-9_-]{0,127}$" },
|
|
6775
|
+
event: { type: "string", pattern: "^[A-Za-z][A-Za-z0-9_]*$", maxLength: 64 },
|
|
6776
|
+
class: { type: "string", enum: ["nonzero-exit", "guard-blocked-unrunnable", "missing-script", "trust-changed", "trust-unreadable", "invalid-options", "start-failed", "timed-out"] },
|
|
6777
|
+
exit_code: { type: ["integer", "null"] },
|
|
6778
|
+
duration_ms: { type: "integer", minimum: 0, maximum: 86400000 },
|
|
6779
|
+
station: { type: "string", maxLength: 64 },
|
|
6780
|
+
harness: { type: "string", enum: ["claude", "codex", "other"] },
|
|
6781
|
+
hooks_version: { type: "string", maxLength: 32 },
|
|
6782
|
+
at: { type: "string", format: "date-time" }
|
|
6783
|
+
} } } } },
|
|
6784
|
+
responses: { "202": { description: "Recorded" }, "400": { description: "Unknown field or invalid value", content: { "application/json": { schema: { $ref: "#/components/schemas/HooksError" } } } }, "429": { description: "More than 120 events from this key in the last minute", content: { "application/json": { schema: { $ref: "#/components/schemas/HooksError" } } } } }
|
|
6785
|
+
}
|
|
6786
|
+
},
|
|
6787
|
+
"/v1/events/errors/summary": {
|
|
6788
|
+
get: {
|
|
6789
|
+
summary: "Hourly counts of failed hook runs by station, hook, event and class",
|
|
6790
|
+
operationId: "getErrorEventSummary",
|
|
6791
|
+
parameters: [{ name: "since", in: "query", required: false, schema: { type: "string", format: "date-time" }, description: "UTC instant within the last 30 days; default 24 hours ago" }],
|
|
6792
|
+
security: [{ apiKey: [] }],
|
|
6793
|
+
responses: { "200": { description: "Counts per hour", content: { "application/json": { schema: { type: "object", properties: { since: { type: "string" }, hours: { type: "array", items: { type: "object", properties: { hour: { type: "string" }, station: { type: "string" }, hook: { type: "string" }, event: { type: "string" }, class: { type: "string" }, count: { type: "integer" } } } } } } } } } }
|
|
6794
|
+
}
|
|
6795
|
+
},
|
|
6500
6796
|
"/v1/selections/{profile}": {
|
|
6501
6797
|
get: {
|
|
6502
6798
|
summary: "Read one exact hosted selection profile",
|
|
@@ -7045,7 +7341,7 @@ function getStorageBackend() {
|
|
|
7045
7341
|
}
|
|
7046
7342
|
|
|
7047
7343
|
// node_modules/@hasna/contracts/dist/auth/index.js
|
|
7048
|
-
import { createHash as
|
|
7344
|
+
import { createHash as createHash5, createHmac, randomBytes as randomBytes4, timingSafeEqual } from "crypto";
|
|
7049
7345
|
var MAX_TENANT_ID_LENGTH = 64;
|
|
7050
7346
|
var TENANT_ID_PATTERN = new RegExp(`^[A-Za-z0-9][A-Za-z0-9._-]{0,${MAX_TENANT_ID_LENGTH - 1}}$`);
|
|
7051
7347
|
var UUID_HEX = "[0-9a-fA-F]";
|
|
@@ -7710,13 +8006,124 @@ function registryKeyStatus() {
|
|
|
7710
8006
|
}
|
|
7711
8007
|
async function authenticateRegistryRequest(request, verifier) {
|
|
7712
8008
|
const auth = verifier ?? createRegistryVerifier(resolveSigningSecret("hooks", process.env, process.env.HASNA_HOOKS_API_SIGNING_KEY !== undefined ? { envName: "HASNA_HOOKS_API_SIGNING_KEY" } : {}).value, registryKeyStatus());
|
|
8009
|
+
const path = new URL(request.url).pathname;
|
|
7713
8010
|
const decision = await auth.authenticate(request.headers, {
|
|
7714
8011
|
method: request.method,
|
|
7715
|
-
path
|
|
7716
|
-
requiredScopes: [request.method === "GET" ? "hooks:read" : "hooks:write"]
|
|
8012
|
+
path,
|
|
8013
|
+
requiredScopes: [request.method === "GET" || isErrorEventWrite(request.method, path) ? "hooks:read" : "hooks:write"]
|
|
7717
8014
|
});
|
|
7718
8015
|
if (!decision.ok)
|
|
7719
8016
|
throw new RegistryError(decision.status, "REGISTRY_AUTH_" + decision.reason.toUpperCase());
|
|
8017
|
+
return decision.principal.kid;
|
|
8018
|
+
}
|
|
8019
|
+
function isErrorEventWrite(method, path) {
|
|
8020
|
+
return method === "POST" && path.replace(/^\/api\/v1(?=\/|$)/, "/v1") === "/v1/events/errors";
|
|
8021
|
+
}
|
|
8022
|
+
|
|
8023
|
+
// src/lib/error-events.ts
|
|
8024
|
+
var ERROR_EVENT_CLASSES = ["nonzero-exit", "guard-blocked-unrunnable", "missing-script", "trust-changed", "trust-unreadable", "invalid-options", "start-failed", "timed-out"];
|
|
8025
|
+
var ERROR_EVENT_HARNESSES = ["claude", "codex", "other"];
|
|
8026
|
+
var ERROR_EVENT_RETENTION_DAYS = 30;
|
|
8027
|
+
var ERROR_EVENT_RATE_PER_MINUTE = 120;
|
|
8028
|
+
var ERROR_EVENT_MAX_BYTES = 4096;
|
|
8029
|
+
var MAX_SUMMARY_ROWS = 5000;
|
|
8030
|
+
var MAX_EVENT_AGE_MS = 24 * 3600000;
|
|
8031
|
+
var MAX_EVENT_SKEW_MS = 5 * 60000;
|
|
8032
|
+
var quoted = (values) => values.map((value) => `'${value}'`).join(",");
|
|
8033
|
+
var ERROR_EVENT_MIGRATIONS = [
|
|
8034
|
+
`CREATE TABLE IF NOT EXISTS hooks_error_events (id BIGSERIAL PRIMARY KEY, key_id TEXT NOT NULL, hook TEXT NOT NULL, event TEXT NOT NULL, class TEXT NOT NULL CHECK(class IN (${quoted(ERROR_EVENT_CLASSES)})), exit_code INTEGER, duration_ms INTEGER NOT NULL CHECK(duration_ms >= 0), station TEXT NOT NULL, harness TEXT NOT NULL CHECK(harness IN (${quoted(ERROR_EVENT_HARNESSES)})), hooks_version TEXT NOT NULL, at TIMESTAMPTZ NOT NULL, received_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
|
|
8035
|
+
`CREATE INDEX IF NOT EXISTS idx_hooks_error_events_received ON hooks_error_events (received_at)`,
|
|
8036
|
+
`CREATE INDEX IF NOT EXISTS idx_hooks_error_events_key_received ON hooks_error_events (key_id, received_at)`,
|
|
8037
|
+
`CREATE INDEX IF NOT EXISTS idx_hooks_error_events_at ON hooks_error_events (at)`
|
|
8038
|
+
];
|
|
8039
|
+
var FIELDS = ["hook", "event", "class", "exit_code", "duration_ms", "station", "harness", "hooks_version", "at"];
|
|
8040
|
+
var INT32_MIN = -2147483648;
|
|
8041
|
+
var INT32_MAX = 2147483647;
|
|
8042
|
+
function text(value, field, max, pattern) {
|
|
8043
|
+
if (typeof value !== "string" || !value.length || value.length > max || !pattern.test(value))
|
|
8044
|
+
throw new RegistryError(400, `ERROR_EVENT_${field.toUpperCase()}_INVALID`);
|
|
8045
|
+
return value;
|
|
8046
|
+
}
|
|
8047
|
+
function integer(value, field, min, max) {
|
|
8048
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max)
|
|
8049
|
+
throw new RegistryError(400, `ERROR_EVENT_${field.toUpperCase()}_INVALID`);
|
|
8050
|
+
return value;
|
|
8051
|
+
}
|
|
8052
|
+
function validateErrorEvent(value, now = Date.now()) {
|
|
8053
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
8054
|
+
throw new RegistryError(400, "ERROR_EVENT_INVALID");
|
|
8055
|
+
const input = value, keys = Object.keys(input);
|
|
8056
|
+
if (keys.length !== FIELDS.length || keys.some((key) => !FIELDS.includes(key)))
|
|
8057
|
+
throw new RegistryError(400, "ERROR_EVENT_FIELDS_INVALID");
|
|
8058
|
+
if (!ERROR_EVENT_CLASSES.includes(input.class))
|
|
8059
|
+
throw new RegistryError(400, "ERROR_EVENT_CLASS_INVALID");
|
|
8060
|
+
if (!ERROR_EVENT_HARNESSES.includes(input.harness))
|
|
8061
|
+
throw new RegistryError(400, "ERROR_EVENT_HARNESS_INVALID");
|
|
8062
|
+
const at = text(input.at, "at", 40, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,6})?Z$/);
|
|
8063
|
+
const when = Date.parse(at);
|
|
8064
|
+
if (!Number.isFinite(when) || when < now - MAX_EVENT_AGE_MS || when > now + MAX_EVENT_SKEW_MS)
|
|
8065
|
+
throw new RegistryError(400, "ERROR_EVENT_AT_INVALID");
|
|
8066
|
+
return {
|
|
8067
|
+
hook: text(input.hook, "hook", 128, REGISTRY_NAME),
|
|
8068
|
+
event: text(input.event, "event", 64, /^[A-Za-z][A-Za-z0-9_]*$/),
|
|
8069
|
+
class: input.class,
|
|
8070
|
+
exit_code: input.exit_code === null ? null : integer(input.exit_code, "exit_code", INT32_MIN, INT32_MAX),
|
|
8071
|
+
duration_ms: integer(input.duration_ms, "duration_ms", 0, 86400000),
|
|
8072
|
+
station: text(input.station, "station", 64, /^[A-Za-z0-9][A-Za-z0-9._-]*$/),
|
|
8073
|
+
harness: input.harness,
|
|
8074
|
+
hooks_version: text(input.hooks_version, "hooks_version", 32, /^[0-9A-Za-z][0-9A-Za-z.+-]*$/),
|
|
8075
|
+
at
|
|
8076
|
+
};
|
|
8077
|
+
}
|
|
8078
|
+
function summarySince(value, now = Date.now()) {
|
|
8079
|
+
if (value === null)
|
|
8080
|
+
return new Date(now - 24 * 3600000).toISOString();
|
|
8081
|
+
const when = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/.test(value) ? Date.parse(value) : NaN;
|
|
8082
|
+
if (!Number.isFinite(when) || when < now - ERROR_EVENT_RETENTION_DAYS * 24 * 3600000 || when > now)
|
|
8083
|
+
throw new RegistryError(400, "ERROR_EVENT_SINCE_INVALID");
|
|
8084
|
+
return new Date(when).toISOString();
|
|
8085
|
+
}
|
|
8086
|
+
|
|
8087
|
+
class PgErrorEventStore {
|
|
8088
|
+
db;
|
|
8089
|
+
constructor(db) {
|
|
8090
|
+
this.db = db;
|
|
8091
|
+
}
|
|
8092
|
+
async insert(event, keyId) {
|
|
8093
|
+
return (await this.db.run(`INSERT INTO hooks_error_events (key_id,hook,event,class,exit_code,duration_ms,station,harness,hooks_version,at)
|
|
8094
|
+
SELECT ?::text,?::text,?::text,?::text,?::integer,?::integer,?::text,?::text,?::text,?::timestamptz
|
|
8095
|
+
WHERE (SELECT COUNT(*) FROM hooks_error_events WHERE key_id = ?::text AND received_at > NOW() - INTERVAL '60 seconds') < ?::integer`, keyId, event.hook, event.event, event.class, event.exit_code, event.duration_ms, event.station, event.harness, event.hooks_version, event.at, keyId, ERROR_EVENT_RATE_PER_MINUTE)).changes === 1;
|
|
8096
|
+
}
|
|
8097
|
+
async prune() {
|
|
8098
|
+
return (await this.db.run(`DELETE FROM hooks_error_events WHERE received_at < NOW() - INTERVAL '${ERROR_EVENT_RETENTION_DAYS} days'`)).changes;
|
|
8099
|
+
}
|
|
8100
|
+
async summary(since) {
|
|
8101
|
+
return await this.db.all(`SELECT to_char(date_trunc('hour', at AT TIME ZONE 'UTC'), 'YYYY-MM-DD"T"HH24":00:00Z"') AS hour, station, hook, event, class, COUNT(*)::integer AS count
|
|
8102
|
+
FROM hooks_error_events WHERE at >= ?::timestamptz GROUP BY 1,2,3,4,5 ORDER BY 1,2,3,4,5 LIMIT ${MAX_SUMMARY_ROWS}`, since);
|
|
8103
|
+
}
|
|
8104
|
+
}
|
|
8105
|
+
|
|
8106
|
+
class HostedErrorEvents {
|
|
8107
|
+
store;
|
|
8108
|
+
now;
|
|
8109
|
+
prunedAt = 0;
|
|
8110
|
+
constructor(store, now = Date.now) {
|
|
8111
|
+
this.store = store;
|
|
8112
|
+
this.now = now;
|
|
8113
|
+
}
|
|
8114
|
+
async record(value, keyId) {
|
|
8115
|
+
const event = validateErrorEvent(value, this.now());
|
|
8116
|
+
if (this.now() - this.prunedAt >= 3600000) {
|
|
8117
|
+
this.prunedAt = this.now();
|
|
8118
|
+
await this.store.prune().catch(() => 0);
|
|
8119
|
+
}
|
|
8120
|
+
if (!await this.store.insert(event, keyId))
|
|
8121
|
+
throw new RegistryError(429, "ERROR_EVENT_RATE_LIMITED");
|
|
8122
|
+
}
|
|
8123
|
+
async summary(since) {
|
|
8124
|
+
const from = summarySince(since, this.now());
|
|
8125
|
+
return { since: from, hours: await this.store.summary(from) };
|
|
8126
|
+
}
|
|
7720
8127
|
}
|
|
7721
8128
|
|
|
7722
8129
|
// src/registry-http.ts
|
|
@@ -7732,6 +8139,18 @@ function configuredRegistry() {
|
|
|
7732
8139
|
serverRegistry = new HostedRegistry(new PgRegistryStore(new PgAdapterAsync(url, { timeoutMs: 5000 })));
|
|
7733
8140
|
return serverRegistry;
|
|
7734
8141
|
}
|
|
8142
|
+
var serverErrorEvents;
|
|
8143
|
+
function configuredErrorEvents() {
|
|
8144
|
+
if (serverErrorEvents)
|
|
8145
|
+
return serverErrorEvents;
|
|
8146
|
+
if (getStorageBackend() !== "postgresql")
|
|
8147
|
+
throw new RegistryError(503, "REGISTRY_DATABASE_REQUIRED");
|
|
8148
|
+
const url = getStorageDatabaseUrl();
|
|
8149
|
+
if (!url)
|
|
8150
|
+
throw new RegistryError(503, "REGISTRY_DATABASE_REQUIRED");
|
|
8151
|
+
serverErrorEvents = new HostedErrorEvents(new PgErrorEventStore(new PgAdapterAsync(url, { timeoutMs: 5000 })));
|
|
8152
|
+
return serverErrorEvents;
|
|
8153
|
+
}
|
|
7735
8154
|
async function registryReady() {
|
|
7736
8155
|
try {
|
|
7737
8156
|
await configuredRegistry().ready();
|
|
@@ -7743,7 +8162,7 @@ async function registryReady() {
|
|
|
7743
8162
|
function json(body, status = 200, headers = {}) {
|
|
7744
8163
|
return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", "cache-control": "no-store", ...headers } });
|
|
7745
8164
|
}
|
|
7746
|
-
async function boundedJson(request) {
|
|
8165
|
+
async function boundedJson(request, max = REGISTRY_MAX_BYTES) {
|
|
7747
8166
|
if (!request.body)
|
|
7748
8167
|
throw new RegistryError(400, "REGISTRY_BODY_REQUIRED");
|
|
7749
8168
|
const reader = request.body.getReader(), chunks = [];
|
|
@@ -7753,7 +8172,7 @@ async function boundedJson(request) {
|
|
|
7753
8172
|
if (next.done)
|
|
7754
8173
|
break;
|
|
7755
8174
|
length += next.value.byteLength;
|
|
7756
|
-
if (length >
|
|
8175
|
+
if (length > max) {
|
|
7757
8176
|
await reader.cancel();
|
|
7758
8177
|
throw new RegistryError(413, "REGISTRY_BODY_TOO_LARGE");
|
|
7759
8178
|
}
|
|
@@ -7765,10 +8184,11 @@ async function boundedJson(request) {
|
|
|
7765
8184
|
throw new RegistryError(400, "REGISTRY_JSON_INVALID");
|
|
7766
8185
|
}
|
|
7767
8186
|
}
|
|
7768
|
-
async function handleRegistryRequest(request, key, registry) {
|
|
8187
|
+
async function handleRegistryRequest(request, key, registry, errorEvents) {
|
|
7769
8188
|
try {
|
|
8189
|
+
let keyId = "local";
|
|
7770
8190
|
if (hasRegistrySigningConfiguration())
|
|
7771
|
-
await authenticateRegistryRequest(request);
|
|
8191
|
+
keyId = await authenticateRegistryRequest(request);
|
|
7772
8192
|
else {
|
|
7773
8193
|
if (!isHooksLocalOptIn())
|
|
7774
8194
|
throw new RegistryError(503, "REGISTRY_SIGNING_CONFIGURATION_REQUIRED");
|
|
@@ -7780,6 +8200,12 @@ async function handleRegistryRequest(request, key, registry) {
|
|
|
7780
8200
|
throw new RegistryError(401, "REGISTRY_UNAUTHORIZED");
|
|
7781
8201
|
}
|
|
7782
8202
|
const url = new URL(request.url), path = url.pathname.replace(/^\/api\/v1(?=\/|$)/, "/v1");
|
|
8203
|
+
if (path === "/v1/events/errors" && request.method === "POST") {
|
|
8204
|
+
await (errorEvents ?? configuredErrorEvents()).record(await boundedJson(request, ERROR_EVENT_MAX_BYTES), keyId);
|
|
8205
|
+
return new Response(null, { status: 202, headers: { "cache-control": "no-store" } });
|
|
8206
|
+
}
|
|
8207
|
+
if (path === "/v1/events/errors/summary" && request.method === "GET")
|
|
8208
|
+
return json(await (errorEvents ?? configuredErrorEvents()).summary(url.searchParams.get("since")));
|
|
7783
8209
|
const owner = registry ?? configuredRegistry();
|
|
7784
8210
|
if (path === "/v1/catalog" && request.method === "GET")
|
|
7785
8211
|
return json(await owner.catalog());
|
|
@@ -7803,7 +8229,7 @@ async function handleRegistryRequest(request, key, registry) {
|
|
|
7803
8229
|
return json({ error: "REGISTRY_ROUTE_NOT_FOUND" }, 404);
|
|
7804
8230
|
} catch (error) {
|
|
7805
8231
|
if (error instanceof RegistryError)
|
|
7806
|
-
return json({ error: error.code }, error.status);
|
|
8232
|
+
return json({ error: error.code }, error.status, error.status === 429 ? { "retry-after": "60" } : {});
|
|
7807
8233
|
if (error instanceof URIError)
|
|
7808
8234
|
return json({ error: "REGISTRY_PATH_INVALID" }, 400);
|
|
7809
8235
|
return json({ error: "REGISTRY_STORAGE_UNAVAILABLE" }, 503);
|
|
@@ -7816,8 +8242,8 @@ var SERVE_HOST = "127.0.0.1";
|
|
|
7816
8242
|
var SERVE_SERVICE_NAME = "hooks-registry";
|
|
7817
8243
|
function packageVersion() {
|
|
7818
8244
|
try {
|
|
7819
|
-
const pkgPath =
|
|
7820
|
-
return JSON.parse(
|
|
8245
|
+
const pkgPath = join11(dirname6(fileURLToPath4(import.meta.url)), "..", "package.json");
|
|
8246
|
+
return JSON.parse(readFileSync7(pkgPath, "utf-8")).version || "0.0.0";
|
|
7821
8247
|
} catch {
|
|
7822
8248
|
return "0.0.0";
|
|
7823
8249
|
}
|