@hasna/hooks 0.12.10 → 0.12.16
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 +69 -6
- package/bin/hooks/stop-review.js +1235 -0
- package/bin/hooks-mcp.js +298 -85
- package/bin/index.js +3348 -1086
- package/bin/native-readiness-entry.js +5 -1
- package/bin/native-safety-entry.js +27 -25
- package/bin/native-safety-worker.cjs +27 -25
- package/bin/serve.js +1362 -70
- package/dist/db/remote-storage.d.ts +7 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.js +1665 -257
- package/dist/lib/codex-safety-check.d.ts +1 -1
- package/dist/lib/hosted-registry.d.ts +70 -0
- package/dist/lib/legacy-registry-artifact.d.ts +23 -0
- package/dist/lib/manifest.d.ts +7 -0
- package/dist/lib/native-safety.d.ts +1 -0
- package/dist/lib/native-target.d.ts +7 -0
- package/dist/lib/opencode-stop-plugin.d.ts +55 -0
- package/dist/lib/registry-artifact.d.ts +36 -0
- package/dist/lib/registry.d.ts +4 -0
- package/dist/lib/stop-review-context.d.ts +12 -0
- package/dist/lib/store.d.ts +4 -0
- package/dist/lib/sumi-stop-plugin.d.ts +129 -0
- package/dist/lib/sync.d.ts +10 -0
- package/dist/lib/transport.d.ts +1 -1
- package/dist/native-readiness.d.ts +1 -1
- package/dist/native-readiness.js +5 -1
- package/dist/openapi.d.ts +160 -16
- package/dist/opencode-stop-plugin.js +384 -0
- package/dist/registry-auth.d.ts +5 -0
- package/dist/registry-http.d.ts +4 -0
- package/dist/sdk/generated.d.ts +32 -12
- package/dist/sdk/index.d.ts +28 -5
- package/dist/sdk/index.js +49 -24
- package/dist/sdk/registry-client.d.ts +1 -1
- package/dist/serve.d.ts +4 -4
- package/dist/storage.js +33 -2
- package/dist/sumi-stop-plugin.js +380 -0
- package/hooks/hook-stop-review/README.md +109 -0
- package/hooks/hook-stop-review/manifest.json +10 -0
- package/hooks/hook-stop-review/package.json +11 -0
- package/hooks/hook-stop-review/src/hook.ts +59 -0
- package/hooks/hook-stop-review/src/index.ts +3 -0
- package/hooks/hook-stop-review/src/jev.ts +121 -0
- package/hooks/hook-stop-review/src/native.ts +246 -0
- package/hooks/hook-stop-review/src/policy.ts +145 -0
- package/hooks/hook-stop-review/src/runtime.ts +309 -0
- package/hooks/hook-stop-review/src/types.ts +121 -0
- package/hooks/hook-trash-guard/src/hook.ts +96 -0
- package/hooks/hook-workspace-repos-guard/src/hook.ts +116 -3
- package/hooks/local-executors.ts +841 -0
- package/package.json +22 -4
- package/scripts/build-bundled-hooks.ts +40 -0
- package/scripts/validate-bundled-hooks.ts +78 -0
- package/scripts/validate-opencode-stop-plugin.ts +42 -0
- package/scripts/validate-package.ts +9 -0
- package/scripts/validate-sumi-stop-plugin.ts +47 -0
package/bin/serve.js
CHANGED
|
@@ -574,6 +574,20 @@ var HOOKS = [
|
|
|
574
574
|
matcher: "",
|
|
575
575
|
tags: ["codewith", "session", "context", "conversations", "heartbeat"]
|
|
576
576
|
},
|
|
577
|
+
{
|
|
578
|
+
name: "stop-review",
|
|
579
|
+
bundledEntry: "bin/hooks/stop-review.js",
|
|
580
|
+
displayName: "Stop Review",
|
|
581
|
+
description: "Reviews turn completion against the latest user request and active goal",
|
|
582
|
+
version: "0.1.0",
|
|
583
|
+
category: "Agent Teams",
|
|
584
|
+
event: "Stop",
|
|
585
|
+
events: ["Stop"],
|
|
586
|
+
nativeTargetDispatch: true,
|
|
587
|
+
timeoutSeconds: 20,
|
|
588
|
+
matcher: "",
|
|
589
|
+
tags: ["stop", "goals", "continuity", "review"]
|
|
590
|
+
},
|
|
577
591
|
{
|
|
578
592
|
name: "stop-sync",
|
|
579
593
|
displayName: "Stop Sync",
|
|
@@ -703,7 +717,7 @@ function getHook(name) {
|
|
|
703
717
|
import { existsSync as existsSync2, mkdirSync, readFileSync, readdirSync, realpathSync, writeFileSync } from "fs";
|
|
704
718
|
import { basename, dirname, isAbsolute, join as join3, normalize, resolve as resolve2, sep } from "path";
|
|
705
719
|
|
|
706
|
-
//
|
|
720
|
+
// node_modules/zod/v3/external.js
|
|
707
721
|
var exports_external = {};
|
|
708
722
|
__export(exports_external, {
|
|
709
723
|
void: () => voidType,
|
|
@@ -815,7 +829,7 @@ __export(exports_external, {
|
|
|
815
829
|
BRAND: () => BRAND
|
|
816
830
|
});
|
|
817
831
|
|
|
818
|
-
//
|
|
832
|
+
// node_modules/zod/v3/helpers/util.js
|
|
819
833
|
var util;
|
|
820
834
|
(function(util2) {
|
|
821
835
|
util2.assertEqual = (_) => {};
|
|
@@ -946,7 +960,7 @@ var getParsedType = (data) => {
|
|
|
946
960
|
}
|
|
947
961
|
};
|
|
948
962
|
|
|
949
|
-
//
|
|
963
|
+
// node_modules/zod/v3/ZodError.js
|
|
950
964
|
var ZodIssueCode = util.arrayToEnum([
|
|
951
965
|
"invalid_type",
|
|
952
966
|
"invalid_literal",
|
|
@@ -1065,7 +1079,7 @@ ZodError.create = (issues) => {
|
|
|
1065
1079
|
return error;
|
|
1066
1080
|
};
|
|
1067
1081
|
|
|
1068
|
-
//
|
|
1082
|
+
// node_modules/zod/v3/locales/en.js
|
|
1069
1083
|
var errorMap = (issue, _ctx) => {
|
|
1070
1084
|
let message;
|
|
1071
1085
|
switch (issue.code) {
|
|
@@ -1168,7 +1182,7 @@ var errorMap = (issue, _ctx) => {
|
|
|
1168
1182
|
};
|
|
1169
1183
|
var en_default = errorMap;
|
|
1170
1184
|
|
|
1171
|
-
//
|
|
1185
|
+
// node_modules/zod/v3/errors.js
|
|
1172
1186
|
var overrideErrorMap = en_default;
|
|
1173
1187
|
function setErrorMap(map) {
|
|
1174
1188
|
overrideErrorMap = map;
|
|
@@ -1176,7 +1190,7 @@ function setErrorMap(map) {
|
|
|
1176
1190
|
function getErrorMap() {
|
|
1177
1191
|
return overrideErrorMap;
|
|
1178
1192
|
}
|
|
1179
|
-
//
|
|
1193
|
+
// node_modules/zod/v3/helpers/parseUtil.js
|
|
1180
1194
|
var makeIssue = (params) => {
|
|
1181
1195
|
const { data, path, errorMaps, issueData } = params;
|
|
1182
1196
|
const fullPath = [...path, ...issueData.path || []];
|
|
@@ -1282,14 +1296,14 @@ var isAborted = (x) => x.status === "aborted";
|
|
|
1282
1296
|
var isDirty = (x) => x.status === "dirty";
|
|
1283
1297
|
var isValid = (x) => x.status === "valid";
|
|
1284
1298
|
var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
|
|
1285
|
-
//
|
|
1299
|
+
// node_modules/zod/v3/helpers/errorUtil.js
|
|
1286
1300
|
var errorUtil;
|
|
1287
1301
|
(function(errorUtil2) {
|
|
1288
1302
|
errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
|
|
1289
1303
|
errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
|
|
1290
1304
|
})(errorUtil || (errorUtil = {}));
|
|
1291
1305
|
|
|
1292
|
-
//
|
|
1306
|
+
// node_modules/zod/v3/types.js
|
|
1293
1307
|
class ParseInputLazyPath {
|
|
1294
1308
|
constructor(parent, value, path, key) {
|
|
1295
1309
|
this._cachedPath = [];
|
|
@@ -4695,6 +4709,56 @@ function getLockPath() {
|
|
|
4695
4709
|
var NUMERIC_ID = "(0|[1-9]\\d{0,15})";
|
|
4696
4710
|
var ALNUM_ID = "\\d*[A-Za-z-][0-9A-Za-z-]*";
|
|
4697
4711
|
var SEMVER_PATTERN = new RegExp(`^${NUMERIC_ID}\\.${NUMERIC_ID}\\.${NUMERIC_ID}` + `(?:-(?:${NUMERIC_ID}|${ALNUM_ID})(?:\\.(?:${NUMERIC_ID}|${ALNUM_ID}))*)?` + `(?:\\+[0-9A-Za-z.-]+)?$`);
|
|
4712
|
+
function parseVersion(value) {
|
|
4713
|
+
const coreAndPre = value.split("+")[0];
|
|
4714
|
+
const dash = coreAndPre.indexOf("-");
|
|
4715
|
+
const core = dash >= 0 ? coreAndPre.slice(0, dash) : coreAndPre;
|
|
4716
|
+
const pre = dash >= 0 ? coreAndPre.slice(dash + 1).split(".") : [];
|
|
4717
|
+
const [major, minor, patch] = core.split(".").map((part) => BigInt(part));
|
|
4718
|
+
return { core: [major, minor, patch], pre };
|
|
4719
|
+
}
|
|
4720
|
+
function compareVersions(a, b) {
|
|
4721
|
+
const pa = parseVersion(a);
|
|
4722
|
+
const pb = parseVersion(b);
|
|
4723
|
+
for (let i = 0;i < 3; i++) {
|
|
4724
|
+
if (pa.core[i] !== pb.core[i])
|
|
4725
|
+
return pa.core[i] < pb.core[i] ? -1 : 1;
|
|
4726
|
+
}
|
|
4727
|
+
const aPre = pa.pre.length > 0;
|
|
4728
|
+
const bPre = pb.pre.length > 0;
|
|
4729
|
+
if (!aPre && !bPre)
|
|
4730
|
+
return 0;
|
|
4731
|
+
if (aPre && !bPre)
|
|
4732
|
+
return -1;
|
|
4733
|
+
if (!aPre && bPre)
|
|
4734
|
+
return 1;
|
|
4735
|
+
const len = Math.max(pa.pre.length, pb.pre.length);
|
|
4736
|
+
for (let i = 0;i < len; i++) {
|
|
4737
|
+
const ai = pa.pre[i];
|
|
4738
|
+
const bi = pb.pre[i];
|
|
4739
|
+
if (ai === undefined)
|
|
4740
|
+
return -1;
|
|
4741
|
+
if (bi === undefined)
|
|
4742
|
+
return 1;
|
|
4743
|
+
if (ai === bi)
|
|
4744
|
+
continue;
|
|
4745
|
+
const aNum = /^\d+$/.test(ai);
|
|
4746
|
+
const bNum = /^\d+$/.test(bi);
|
|
4747
|
+
if (aNum && bNum) {
|
|
4748
|
+
const aN = BigInt(ai);
|
|
4749
|
+
const bN = BigInt(bi);
|
|
4750
|
+
if (aN === bN)
|
|
4751
|
+
continue;
|
|
4752
|
+
return aN < bN ? -1 : 1;
|
|
4753
|
+
}
|
|
4754
|
+
if (aNum)
|
|
4755
|
+
return -1;
|
|
4756
|
+
if (bNum)
|
|
4757
|
+
return 1;
|
|
4758
|
+
return ai < bi ? -1 : 1;
|
|
4759
|
+
}
|
|
4760
|
+
return 0;
|
|
4761
|
+
}
|
|
4698
4762
|
|
|
4699
4763
|
// src/lib/manifest.ts
|
|
4700
4764
|
var HOOK_NAME_RE = /^[\w-]+$/;
|
|
@@ -4706,6 +4770,7 @@ var manifestSchema = exports_external.object({
|
|
|
4706
4770
|
script: exports_external.string().min(1, "script must name a relative path or inline content"),
|
|
4707
4771
|
script_kind: exports_external.enum(["inline", "file"]).optional(),
|
|
4708
4772
|
args: exports_external.array(exports_external.string()).optional(),
|
|
4773
|
+
nativeTargetDispatch: exports_external.boolean().optional(),
|
|
4709
4774
|
timeout_ms: exports_external.number().int().positive().optional(),
|
|
4710
4775
|
env: exports_external.record(exports_external.string(), exports_external.string()).optional()
|
|
4711
4776
|
});
|
|
@@ -4783,8 +4848,17 @@ function resolveScript(manifest, manifestDir) {
|
|
|
4783
4848
|
}
|
|
4784
4849
|
return { path: rel, content: readFileSync(resolved, "utf-8") };
|
|
4785
4850
|
}
|
|
4851
|
+
|
|
4852
|
+
class HookIdentityError extends Error {
|
|
4853
|
+
constructor() {
|
|
4854
|
+
super("Hook name must be canonical and match its manifest identity");
|
|
4855
|
+
}
|
|
4856
|
+
}
|
|
4786
4857
|
function customHookDir(name) {
|
|
4787
|
-
|
|
4858
|
+
const canonical = shortManifestName(name);
|
|
4859
|
+
if (!HOOK_NAME_RE.test(canonical))
|
|
4860
|
+
throw new HookIdentityError;
|
|
4861
|
+
return join3(getCustomHooksDir(), canonical);
|
|
4788
4862
|
}
|
|
4789
4863
|
function readCustomManifest(name) {
|
|
4790
4864
|
const dir = customHookDir(name);
|
|
@@ -4793,11 +4867,13 @@ function readCustomManifest(name) {
|
|
|
4793
4867
|
return;
|
|
4794
4868
|
try {
|
|
4795
4869
|
const manifest = parseManifest(readFileSync(manifestPath, "utf-8"));
|
|
4870
|
+
if (shortManifestName(manifest.name) !== shortManifestName(name))
|
|
4871
|
+
throw new HookIdentityError;
|
|
4796
4872
|
const script = resolveScript(manifest, dir);
|
|
4797
4873
|
const scriptIsInline = isInlineScript(manifest);
|
|
4798
4874
|
return { manifest, scriptPath: join3(dir, script.path), scriptContent: script.content, scriptIsInline };
|
|
4799
4875
|
} catch (err) {
|
|
4800
|
-
if (err instanceof ScriptContainmentError)
|
|
4876
|
+
if (err instanceof ScriptContainmentError || err instanceof HookIdentityError)
|
|
4801
4877
|
throw err;
|
|
4802
4878
|
return;
|
|
4803
4879
|
}
|
|
@@ -4808,9 +4884,16 @@ function listCustomHooks() {
|
|
|
4808
4884
|
return [];
|
|
4809
4885
|
const results = [];
|
|
4810
4886
|
for (const entry of readdirSafe(dir)) {
|
|
4811
|
-
|
|
4812
|
-
|
|
4813
|
-
|
|
4887
|
+
if (!HOOK_NAME_RE.test(entry))
|
|
4888
|
+
continue;
|
|
4889
|
+
try {
|
|
4890
|
+
const parsed = readCustomManifest(entry);
|
|
4891
|
+
if (parsed)
|
|
4892
|
+
results.push(parsed);
|
|
4893
|
+
} catch (error) {
|
|
4894
|
+
if (!(error instanceof HookIdentityError))
|
|
4895
|
+
throw error;
|
|
4896
|
+
}
|
|
4814
4897
|
}
|
|
4815
4898
|
return results.sort((a, b) => a.manifest.name.localeCompare(b.manifest.name));
|
|
4816
4899
|
}
|
|
@@ -4823,8 +4906,9 @@ function readdirSafe(dir) {
|
|
|
4823
4906
|
}
|
|
4824
4907
|
|
|
4825
4908
|
// src/lib/store.ts
|
|
4826
|
-
import { createHash } from "crypto";
|
|
4827
|
-
import { existsSync as existsSync5, mkdirSync as mkdirSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync2, renameSync } from "fs";
|
|
4909
|
+
import { createHash as createHash2 } from "crypto";
|
|
4910
|
+
import { existsSync as existsSync5, mkdirSync as mkdirSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync2, renameSync, lstatSync } from "fs";
|
|
4911
|
+
import { join as join6 } from "path";
|
|
4828
4912
|
import { readFile } from "fs/promises";
|
|
4829
4913
|
|
|
4830
4914
|
// src/db/index.ts
|
|
@@ -5186,10 +5270,46 @@ function getDb() {
|
|
|
5186
5270
|
return instance;
|
|
5187
5271
|
}
|
|
5188
5272
|
|
|
5273
|
+
// src/lib/registry-artifact.ts
|
|
5274
|
+
import { createHash } from "crypto";
|
|
5275
|
+
class RegistryError extends Error {
|
|
5276
|
+
status;
|
|
5277
|
+
code;
|
|
5278
|
+
constructor(status, code) {
|
|
5279
|
+
super(code);
|
|
5280
|
+
this.status = status;
|
|
5281
|
+
this.code = code;
|
|
5282
|
+
}
|
|
5283
|
+
}
|
|
5284
|
+
var REGISTRY_NAME = /^[a-z0-9][a-z0-9_-]{0,127}$/;
|
|
5285
|
+
var REGISTRY_MAX_BYTES = 2 * 1024 * 1024;
|
|
5286
|
+
function canonicalJson(value) {
|
|
5287
|
+
if (Array.isArray(value))
|
|
5288
|
+
return `[${value.map(canonicalJson).join(",")}]`;
|
|
5289
|
+
if (value && typeof value === "object")
|
|
5290
|
+
return `{${Object.entries(value).filter(([, v]) => v !== undefined).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(",")}}`;
|
|
5291
|
+
return JSON.stringify(value);
|
|
5292
|
+
}
|
|
5293
|
+
function registryDigest(value) {
|
|
5294
|
+
return createHash("sha256").update(canonicalJson(value)).digest("hex");
|
|
5295
|
+
}
|
|
5296
|
+
function scriptDigest(script) {
|
|
5297
|
+
return createHash("sha256").update(script).digest("hex");
|
|
5298
|
+
}
|
|
5299
|
+
function validateRegistryArtifact(value) {
|
|
5300
|
+
const a = value;
|
|
5301
|
+
const m = a?.manifest;
|
|
5302
|
+
const keys = new Set(["name", "version", "description", "events", "script", "script_kind", "args", "timeout_ms", "nativeTargetDispatch"]);
|
|
5303
|
+
if (!a || typeof a !== "object" || !m || typeof m !== "object" || Object.keys(a).some((k) => !["manifest", "script"].includes(k)) || Object.keys(m).some((k) => !keys.has(k)) || typeof m.name !== "string" || !REGISTRY_NAME.test(m.name) || m.name.startsWith("hook-") || typeof m.version !== "string" || !SEMVER_PATTERN.test(m.version) || typeof a.script !== "string" || !a.script || Buffer.byteLength(canonicalJson(a)) > REGISTRY_MAX_BYTES || m.script_kind !== "file" || m.script !== "hook.js" || !Array.isArray(m.events) || !m.events.length || m.events.length > 16 || m.events.some((e) => typeof e !== "string" || !/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(e)) || m.description !== undefined && (typeof m.description !== "string" || m.description.length > 4000) || m.args !== undefined && (!Array.isArray(m.args) || m.args.length > 32 || m.args.some((s) => typeof s !== "string" || s.length > 4096)) || m.nativeTargetDispatch !== undefined && typeof m.nativeTargetDispatch !== "boolean" || m.timeout_ms !== undefined && (!Number.isInteger(m.timeout_ms) || m.timeout_ms < 1 || m.timeout_ms > 300000)) {
|
|
5304
|
+
throw new RegistryError(400, "REGISTRY_ARTIFACT_INVALID");
|
|
5305
|
+
}
|
|
5306
|
+
return JSON.parse(canonicalJson(a));
|
|
5307
|
+
}
|
|
5308
|
+
|
|
5189
5309
|
// src/lib/store.ts
|
|
5190
5310
|
import { randomBytes } from "crypto";
|
|
5191
5311
|
function sha256Of(input) {
|
|
5192
|
-
return
|
|
5312
|
+
return createHash2("sha256").update(input).digest("hex");
|
|
5193
5313
|
}
|
|
5194
5314
|
async function sha256File(path) {
|
|
5195
5315
|
const buf = await readFile(path);
|
|
@@ -5284,8 +5404,24 @@ function setPinnedHook(name, entry) {
|
|
|
5284
5404
|
lock.hooks[name] = entry;
|
|
5285
5405
|
return writeLock(lock);
|
|
5286
5406
|
}
|
|
5407
|
+
function registryManagedMarker(name) {
|
|
5408
|
+
return join6(getHooksDataDir(), "registry-managed", sha256Of(name) + ".json");
|
|
5409
|
+
}
|
|
5410
|
+
function isRegistryManaged(name) {
|
|
5411
|
+
try {
|
|
5412
|
+
lstatSync(registryManagedMarker(name));
|
|
5413
|
+
return true;
|
|
5414
|
+
} catch (error) {
|
|
5415
|
+
if (error.code === "ENOENT")
|
|
5416
|
+
return false;
|
|
5417
|
+
throw error;
|
|
5418
|
+
}
|
|
5419
|
+
}
|
|
5287
5420
|
function retrustHook(name, scriptPath, version, source) {
|
|
5288
5421
|
const actual = sha256Of(readFileSync3(scriptPath));
|
|
5422
|
+
const custom2 = isRegistryManaged(name) ? readCustomManifest(name) : undefined;
|
|
5423
|
+
if (isRegistryManaged(name) && !custom2)
|
|
5424
|
+
throw new Error("REGISTRY_MANIFEST_REQUIRED");
|
|
5289
5425
|
const db = storeDb();
|
|
5290
5426
|
if (db) {
|
|
5291
5427
|
upsertHookRecord(db, {
|
|
@@ -5296,19 +5432,19 @@ function retrustHook(name, scriptPath, version, source) {
|
|
|
5296
5432
|
last_verified_at: new Date().toISOString()
|
|
5297
5433
|
});
|
|
5298
5434
|
}
|
|
5299
|
-
setPinnedHook(name, { version, sha256: actual, source });
|
|
5435
|
+
setPinnedHook(name, { version, sha256: actual, source, ...custom2 ? { manifest_sha256: registryDigest(custom2.manifest) } : {} });
|
|
5300
5436
|
return { ok: true, pinned: true, expected: actual, actual, name };
|
|
5301
5437
|
}
|
|
5302
5438
|
|
|
5303
5439
|
// src/lib/resolve.ts
|
|
5304
|
-
import { dirname as dirname2, join as
|
|
5440
|
+
import { dirname as dirname2, join as join7 } from "path";
|
|
5305
5441
|
import { existsSync as existsSync6 } from "fs";
|
|
5306
5442
|
import { fileURLToPath } from "url";
|
|
5307
5443
|
function resolveBundledHooksDir(moduleDir = dirname2(fileURLToPath(import.meta.url))) {
|
|
5308
|
-
const sourceLayout =
|
|
5309
|
-
if (existsSync6(
|
|
5444
|
+
const sourceLayout = join7(moduleDir, "..", "..", "hooks");
|
|
5445
|
+
if (existsSync6(join7(sourceLayout, "hook-gitguard")))
|
|
5310
5446
|
return sourceLayout;
|
|
5311
|
-
return
|
|
5447
|
+
return join7(moduleDir, "..", "hooks");
|
|
5312
5448
|
}
|
|
5313
5449
|
function resolveHookDir(name) {
|
|
5314
5450
|
const custom2 = readCustomManifest(name);
|
|
@@ -5319,20 +5455,27 @@ function resolveHookDir(name) {
|
|
|
5319
5455
|
return;
|
|
5320
5456
|
const short = shortManifestName(name);
|
|
5321
5457
|
const bundledBase = resolveBundledHooksDir();
|
|
5322
|
-
const direct =
|
|
5458
|
+
const direct = join7(bundledBase, short);
|
|
5323
5459
|
if (existsSync6(direct))
|
|
5324
5460
|
return direct;
|
|
5325
|
-
const prefixed =
|
|
5461
|
+
const prefixed = join7(bundledBase, `hook-${short}`);
|
|
5326
5462
|
return existsSync6(prefixed) ? prefixed : undefined;
|
|
5327
5463
|
}
|
|
5328
5464
|
function resolveScriptPath(name) {
|
|
5329
5465
|
const custom2 = readCustomManifest(name);
|
|
5330
5466
|
if (custom2)
|
|
5331
5467
|
return custom2.scriptPath;
|
|
5468
|
+
const meta = getHook(shortManifestName(name));
|
|
5469
|
+
if (meta?.bundledEntry) {
|
|
5470
|
+
if (!/^bin\/hooks\/[a-z0-9-]+\.js$/.test(meta.bundledEntry))
|
|
5471
|
+
return;
|
|
5472
|
+
const bundle = join7(resolveBundledHooksDir(), "..", meta.bundledEntry);
|
|
5473
|
+
return existsSync6(bundle) ? bundle : undefined;
|
|
5474
|
+
}
|
|
5332
5475
|
const dir = resolveHookDir(name);
|
|
5333
5476
|
if (!dir)
|
|
5334
5477
|
return;
|
|
5335
|
-
const script =
|
|
5478
|
+
const script = join7(dir, "src", "hook.ts");
|
|
5336
5479
|
return existsSync6(script) ? script : undefined;
|
|
5337
5480
|
}
|
|
5338
5481
|
function resolveHookMeta(name) {
|
|
@@ -5348,7 +5491,9 @@ function resolveHookMeta(name) {
|
|
|
5348
5491
|
event: manifest.events[0] ?? "PostToolUse",
|
|
5349
5492
|
events: manifest.events,
|
|
5350
5493
|
matcher: "",
|
|
5351
|
-
tags: ["custom"]
|
|
5494
|
+
tags: ["custom"],
|
|
5495
|
+
nativeTargetDispatch: manifest.nativeTargetDispatch,
|
|
5496
|
+
timeoutSeconds: manifest.timeout_ms === undefined ? undefined : Math.ceil(manifest.timeout_ms / 1000)
|
|
5352
5497
|
};
|
|
5353
5498
|
}
|
|
5354
5499
|
return getHook(shortManifestName(name));
|
|
@@ -5386,10 +5531,10 @@ function resolveHook(name) {
|
|
|
5386
5531
|
|
|
5387
5532
|
// src/serve.ts
|
|
5388
5533
|
import { readFileSync as readFileSync5 } from "fs";
|
|
5389
|
-
import { dirname as dirname4, join as
|
|
5534
|
+
import { dirname as dirname4, join as join9 } from "path";
|
|
5390
5535
|
import { fileURLToPath as fileURLToPath5 } from "url";
|
|
5391
5536
|
|
|
5392
|
-
//
|
|
5537
|
+
// node_modules/@hasna/contracts/dist/client/transport.js
|
|
5393
5538
|
import { spawnSync } from "child_process";
|
|
5394
5539
|
import { closeSync as closeSync2, fstatSync as fstatSync2, openSync as openSync2, readFileSync as readFileSync22 } from "fs";
|
|
5395
5540
|
import { O_NOFOLLOW as O_NOFOLLOW2, O_NONBLOCK as O_NONBLOCK2, O_RDONLY as O_RDONLY2 } from "constants";
|
|
@@ -5397,9 +5542,9 @@ import { hostname as osHostname } from "os";
|
|
|
5397
5542
|
import { isAbsolute as isAbsolute2, join as join22 } from "path";
|
|
5398
5543
|
import { createRequire } from "module";
|
|
5399
5544
|
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
5400
|
-
import { closeSync, fstatSync, lstatSync, openSync, readFileSync as readFileSync4, realpathSync as realpathSync2, statSync } from "fs";
|
|
5545
|
+
import { closeSync, fstatSync, lstatSync as lstatSync2, openSync, readFileSync as readFileSync4, realpathSync as realpathSync2, statSync } from "fs";
|
|
5401
5546
|
import { O_NOFOLLOW, O_NONBLOCK, O_RDONLY } from "constants";
|
|
5402
|
-
import { basename as basename2, dirname as dirname3, join as
|
|
5547
|
+
import { basename as basename2, dirname as dirname3, join as join8, relative, sep as sep2 } from "path";
|
|
5403
5548
|
import { fileURLToPath as fileURLToPath3, pathToFileURL } from "url";
|
|
5404
5549
|
function envToken(name) {
|
|
5405
5550
|
return name.toUpperCase().replace(/-/g, "_");
|
|
@@ -5477,7 +5622,7 @@ var PACKAGE = "@hasna/secrets";
|
|
|
5477
5622
|
var MAX_PACKAGE_BYTES = 1024 * 1024;
|
|
5478
5623
|
function entryPoint(directory) {
|
|
5479
5624
|
const root = realpathSync2(directory);
|
|
5480
|
-
const fd = openSync(
|
|
5625
|
+
const fd = openSync(join8(root, "package.json"), O_RDONLY | O_NOFOLLOW | O_NONBLOCK);
|
|
5481
5626
|
let pkg;
|
|
5482
5627
|
try {
|
|
5483
5628
|
const stat = fstatSync(fd);
|
|
@@ -5497,7 +5642,7 @@ function entryPoint(directory) {
|
|
|
5497
5642
|
if (/[\\%?#\0]/.test(target) || parts.some((part) => !part || part === "." || part === ".." || part === "node_modules")) {
|
|
5498
5643
|
throw new Error("Invalid Secrets import export");
|
|
5499
5644
|
}
|
|
5500
|
-
const file = realpathSync2(
|
|
5645
|
+
const file = realpathSync2(join8(root, ...parts));
|
|
5501
5646
|
const within = relative(root, file);
|
|
5502
5647
|
if (!within || within === ".." || within.startsWith(`..${sep2}`) || !statSync(file).isFile()) {
|
|
5503
5648
|
throw new Error("Secrets import export escapes its package or is not a file");
|
|
@@ -5508,10 +5653,10 @@ function resolveInstalledSecrets(parentUrl) {
|
|
|
5508
5653
|
let directory = dirname3(fileURLToPath3(parentUrl));
|
|
5509
5654
|
for (;; ) {
|
|
5510
5655
|
if (basename2(directory) !== "node_modules") {
|
|
5511
|
-
const candidate =
|
|
5656
|
+
const candidate = join8(directory, "node_modules", PACKAGE);
|
|
5512
5657
|
let absent = false;
|
|
5513
5658
|
try {
|
|
5514
|
-
|
|
5659
|
+
lstatSync2(candidate);
|
|
5515
5660
|
} catch (error) {
|
|
5516
5661
|
if (error.code !== "ENOENT")
|
|
5517
5662
|
throw error;
|
|
@@ -6068,6 +6213,10 @@ var AUTHORITY_OVERRIDE_HEADERS = new Set([
|
|
|
6068
6213
|
]);
|
|
6069
6214
|
|
|
6070
6215
|
// src/lib/local-opt-in.ts
|
|
6216
|
+
var HOOKS_LOCAL_OPT_IN_ENV_KEYS = ["HASNA_HOOKS_LOCAL", "HOOKS_LOCAL"];
|
|
6217
|
+
function isHooksLocalOptIn(env = process.env) {
|
|
6218
|
+
return HOOKS_LOCAL_OPT_IN_ENV_KEYS.some((key) => (env[key] ?? "").trim() !== "");
|
|
6219
|
+
}
|
|
6071
6220
|
function hooksAuthorityEnvKeys() {
|
|
6072
6221
|
const keys = clientTransportEnvKeys("hooks");
|
|
6073
6222
|
return [
|
|
@@ -6078,6 +6227,12 @@ function hooksAuthorityEnvKeys() {
|
|
|
6078
6227
|
CREDENTIAL_PROFILE_ENV_KEY
|
|
6079
6228
|
];
|
|
6080
6229
|
}
|
|
6230
|
+
function hasHooksEnvAuthorityIntent(env = process.env) {
|
|
6231
|
+
return hooksAuthorityEnvKeys().some((key) => (env[key] ?? "").trim() !== "");
|
|
6232
|
+
}
|
|
6233
|
+
function selectsHooksLocalStore(env = process.env) {
|
|
6234
|
+
return !hasHooksEnvAuthorityIntent(env) && isHooksLocalOptIn(env);
|
|
6235
|
+
}
|
|
6081
6236
|
function hooksResolverEnv(env) {
|
|
6082
6237
|
const blanks = hooksAuthorityEnvKeys().filter((key) => (key in env) && (env[key] ?? "").trim() === "");
|
|
6083
6238
|
if (blanks.length === 0)
|
|
@@ -6146,7 +6301,7 @@ function buildOpenApiDocument(version) {
|
|
|
6146
6301
|
info: {
|
|
6147
6302
|
title: "Hooks Registry API",
|
|
6148
6303
|
version,
|
|
6149
|
-
description: "
|
|
6304
|
+
description: "Authenticated hosted registry for @hasna/hooks: immutable executable artifacts and version-guarded selection profiles. Canonical /v1 routes require PostgreSQL; legacy /api/v1 self-hosted routes remain compatible."
|
|
6150
6305
|
},
|
|
6151
6306
|
servers: [{ url: "/" }],
|
|
6152
6307
|
paths: {
|
|
@@ -6168,7 +6323,7 @@ function buildOpenApiDocument(version) {
|
|
|
6168
6323
|
},
|
|
6169
6324
|
"/ready": {
|
|
6170
6325
|
get: {
|
|
6171
|
-
summary: "Readiness probe \u2014
|
|
6326
|
+
summary: "Readiness probe \u2014 hosted registry tables are readable",
|
|
6172
6327
|
operationId: "getReady",
|
|
6173
6328
|
responses: {
|
|
6174
6329
|
"200": {
|
|
@@ -6222,10 +6377,11 @@ function buildOpenApiDocument(version) {
|
|
|
6222
6377
|
}
|
|
6223
6378
|
}
|
|
6224
6379
|
},
|
|
6225
|
-
"/
|
|
6380
|
+
"/v1/catalog": {
|
|
6226
6381
|
get: {
|
|
6227
6382
|
summary: "List the full hook catalog with versions and sha256",
|
|
6228
6383
|
operationId: "getCatalog",
|
|
6384
|
+
security: [{ apiKey: [] }],
|
|
6229
6385
|
responses: {
|
|
6230
6386
|
"200": {
|
|
6231
6387
|
description: "Catalog entries",
|
|
@@ -6238,10 +6394,12 @@ function buildOpenApiDocument(version) {
|
|
|
6238
6394
|
}
|
|
6239
6395
|
}
|
|
6240
6396
|
},
|
|
6241
|
-
"/
|
|
6397
|
+
"/v1/lock": {
|
|
6242
6398
|
get: {
|
|
6243
6399
|
summary: "Read the published hooks.lock with per-hook versions",
|
|
6244
6400
|
operationId: "getLock",
|
|
6401
|
+
parameters: [{ name: "profile", in: "query", required: false, schema: { type: "string", default: "fleet" } }],
|
|
6402
|
+
security: [{ apiKey: [] }],
|
|
6245
6403
|
responses: {
|
|
6246
6404
|
"200": {
|
|
6247
6405
|
description: "The lock file",
|
|
@@ -6254,10 +6412,11 @@ function buildOpenApiDocument(version) {
|
|
|
6254
6412
|
}
|
|
6255
6413
|
}
|
|
6256
6414
|
},
|
|
6257
|
-
"/
|
|
6415
|
+
"/v1/hooks/{name}/{version}": {
|
|
6258
6416
|
get: {
|
|
6259
6417
|
summary: "Fetch one hook's manifest and script",
|
|
6260
6418
|
operationId: "getHookArtifact",
|
|
6419
|
+
security: [{ apiKey: [] }],
|
|
6261
6420
|
parameters: [
|
|
6262
6421
|
{ name: "name", in: "path", required: true, schema: { type: "string" } },
|
|
6263
6422
|
{ name: "version", in: "path", required: true, schema: { type: "string" } }
|
|
@@ -6266,6 +6425,7 @@ function buildOpenApiDocument(version) {
|
|
|
6266
6425
|
"200": {
|
|
6267
6426
|
description: "Hook artifact; x-hook-sha256 header carries the script hash",
|
|
6268
6427
|
headers: {
|
|
6428
|
+
"x-hook-bundle-sha256": { description: "SHA256 of canonical manifest and script", schema: { type: "string" } },
|
|
6269
6429
|
"x-hook-sha256": {
|
|
6270
6430
|
description: "sha256 of the served script, the same value the lock pins",
|
|
6271
6431
|
schema: { type: "string" }
|
|
@@ -6286,7 +6446,7 @@ function buildOpenApiDocument(version) {
|
|
|
6286
6446
|
}
|
|
6287
6447
|
},
|
|
6288
6448
|
"404": {
|
|
6289
|
-
description: "
|
|
6449
|
+
description: "Exact published version not found",
|
|
6290
6450
|
content: {
|
|
6291
6451
|
"application/json": {
|
|
6292
6452
|
schema: { $ref: "#/components/schemas/HooksError" }
|
|
@@ -6296,9 +6456,26 @@ function buildOpenApiDocument(version) {
|
|
|
6296
6456
|
}
|
|
6297
6457
|
}
|
|
6298
6458
|
},
|
|
6299
|
-
"/
|
|
6459
|
+
"/v1/selections/{profile}": {
|
|
6460
|
+
get: {
|
|
6461
|
+
summary: "Read one exact hosted selection profile",
|
|
6462
|
+
operationId: "getSelection",
|
|
6463
|
+
parameters: [{ name: "profile", in: "path", required: true, schema: { type: "string" } }],
|
|
6464
|
+
security: [{ apiKey: [] }],
|
|
6465
|
+
responses: { "200": { description: "Current exact selection", content: { "application/json": { schema: { $ref: "#/components/schemas/HooksLock" } } } } }
|
|
6466
|
+
},
|
|
6300
6467
|
put: {
|
|
6301
|
-
summary: "
|
|
6468
|
+
summary: "Append a selection revision under its exact predecessor guard",
|
|
6469
|
+
operationId: "putSelection",
|
|
6470
|
+
parameters: [{ name: "profile", in: "path", required: true, schema: { type: "string" } }],
|
|
6471
|
+
security: [{ apiKey: [] }],
|
|
6472
|
+
requestBody: { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/HooksSelectionRequest" } } } },
|
|
6473
|
+
responses: { "200": { description: "Accepted or idempotently reconciled selection", content: { "application/json": { schema: { $ref: "#/components/schemas/HooksLock" } } } }, "409": { description: "Stale revision or mismatched artifact digest" } }
|
|
6474
|
+
}
|
|
6475
|
+
},
|
|
6476
|
+
"/v1/hooks": {
|
|
6477
|
+
put: {
|
|
6478
|
+
summary: "Publish an immutable executable artifact (requires the API key)",
|
|
6302
6479
|
operationId: "putHook",
|
|
6303
6480
|
requestBody: {
|
|
6304
6481
|
required: true,
|
|
@@ -6310,7 +6487,7 @@ function buildOpenApiDocument(version) {
|
|
|
6310
6487
|
},
|
|
6311
6488
|
responses: {
|
|
6312
6489
|
"200": {
|
|
6313
|
-
description: "
|
|
6490
|
+
description: "Immutable artifact accepted or identical prior publication reconciled",
|
|
6314
6491
|
content: {
|
|
6315
6492
|
"application/json": {
|
|
6316
6493
|
schema: { $ref: "#/components/schemas/HooksPublishResponse" }
|
|
@@ -6342,7 +6519,7 @@ function buildOpenApiDocument(version) {
|
|
|
6342
6519
|
}
|
|
6343
6520
|
},
|
|
6344
6521
|
"409": {
|
|
6345
|
-
description: "
|
|
6522
|
+
description: "Conflicting bytes for an existing name and version",
|
|
6346
6523
|
content: {
|
|
6347
6524
|
"application/json": {
|
|
6348
6525
|
schema: { $ref: "#/components/schemas/HooksError" }
|
|
@@ -6386,6 +6563,7 @@ function buildOpenApiDocument(version) {
|
|
|
6386
6563
|
name: { type: "string" },
|
|
6387
6564
|
version: { type: "string" },
|
|
6388
6565
|
sha256: { type: "string" },
|
|
6566
|
+
bundle_sha256: { type: "string" },
|
|
6389
6567
|
events: { type: "array", items: { type: "string" } },
|
|
6390
6568
|
description: { type: "string" },
|
|
6391
6569
|
source: {
|
|
@@ -6410,6 +6588,7 @@ function buildOpenApiDocument(version) {
|
|
|
6410
6588
|
properties: {
|
|
6411
6589
|
version: { type: "string" },
|
|
6412
6590
|
sha256: { type: "string" },
|
|
6591
|
+
bundle_sha256: { type: "string" },
|
|
6413
6592
|
source: { type: "string" },
|
|
6414
6593
|
pinned: {
|
|
6415
6594
|
type: "boolean",
|
|
@@ -6423,6 +6602,8 @@ function buildOpenApiDocument(version) {
|
|
|
6423
6602
|
additionalProperties: false,
|
|
6424
6603
|
required: ["hooks"],
|
|
6425
6604
|
properties: {
|
|
6605
|
+
profile: { type: "string" },
|
|
6606
|
+
revision: { type: "integer" },
|
|
6426
6607
|
hooks: {
|
|
6427
6608
|
type: "object",
|
|
6428
6609
|
additionalProperties: { $ref: "#/components/schemas/HooksLockEntry" }
|
|
@@ -6432,14 +6613,15 @@ function buildOpenApiDocument(version) {
|
|
|
6432
6613
|
HooksManifest: {
|
|
6433
6614
|
type: "object",
|
|
6434
6615
|
additionalProperties: false,
|
|
6435
|
-
required: ["name", "version", "events", "script"],
|
|
6616
|
+
required: ["name", "version", "events", "script", "script_kind"],
|
|
6436
6617
|
properties: {
|
|
6618
|
+
nativeTargetDispatch: { type: "boolean", description: "Pass the trusted installed target through the Hooks runner" },
|
|
6437
6619
|
name: { type: "string" },
|
|
6438
6620
|
version: { type: "string" },
|
|
6439
6621
|
description: { type: "string" },
|
|
6440
6622
|
events: { type: "array", items: { type: "string" } },
|
|
6441
|
-
script: { type: "string" },
|
|
6442
|
-
script_kind: { type: "string", enum: ["
|
|
6623
|
+
script: { type: "string", enum: ["hook.js"] },
|
|
6624
|
+
script_kind: { type: "string", enum: ["file"] },
|
|
6443
6625
|
args: { type: "array", items: { type: "string" } },
|
|
6444
6626
|
timeout_ms: { type: "number" }
|
|
6445
6627
|
}
|
|
@@ -6462,10 +6644,16 @@ function buildOpenApiDocument(version) {
|
|
|
6462
6644
|
HooksPublishRequest: {
|
|
6463
6645
|
type: "object",
|
|
6464
6646
|
additionalProperties: false,
|
|
6465
|
-
required: ["
|
|
6647
|
+
required: ["manifest", "script"],
|
|
6648
|
+
properties: { manifest: { $ref: "#/components/schemas/HooksManifest" }, script: { type: "string" } }
|
|
6649
|
+
},
|
|
6650
|
+
HooksSelectionRequest: {
|
|
6651
|
+
type: "object",
|
|
6652
|
+
additionalProperties: false,
|
|
6653
|
+
required: ["expected_revision", "hooks"],
|
|
6466
6654
|
properties: {
|
|
6467
|
-
|
|
6468
|
-
version: { type: "string" }
|
|
6655
|
+
expected_revision: { type: "integer", minimum: 0 },
|
|
6656
|
+
hooks: { type: "object", additionalProperties: { type: "object", additionalProperties: false, required: ["version", "bundle_sha256"], properties: { version: { type: "string" }, bundle_sha256: { type: "string", pattern: "^[a-f0-9]{64}$" } } } }
|
|
6469
6657
|
}
|
|
6470
6658
|
},
|
|
6471
6659
|
HooksPublishResponse: {
|
|
@@ -6474,6 +6662,7 @@ function buildOpenApiDocument(version) {
|
|
|
6474
6662
|
required: ["ok", "hook"],
|
|
6475
6663
|
properties: {
|
|
6476
6664
|
ok: { type: "boolean" },
|
|
6665
|
+
idempotent: { type: "boolean" },
|
|
6477
6666
|
hook: {
|
|
6478
6667
|
type: "object",
|
|
6479
6668
|
additionalProperties: false,
|
|
@@ -6481,7 +6670,8 @@ function buildOpenApiDocument(version) {
|
|
|
6481
6670
|
properties: {
|
|
6482
6671
|
name: { type: "string" },
|
|
6483
6672
|
version: { type: "string" },
|
|
6484
|
-
sha256: { type: "string" }
|
|
6673
|
+
sha256: { type: "string" },
|
|
6674
|
+
bundle_sha256: { type: "string" }
|
|
6485
6675
|
}
|
|
6486
6676
|
}
|
|
6487
6677
|
}
|
|
@@ -6491,13 +6681,1101 @@ function buildOpenApiDocument(version) {
|
|
|
6491
6681
|
};
|
|
6492
6682
|
}
|
|
6493
6683
|
|
|
6684
|
+
// src/lib/legacy-registry-artifact.ts
|
|
6685
|
+
function validateLegacyArtifact(wire, name, version, expectedScript) {
|
|
6686
|
+
try {
|
|
6687
|
+
const value = JSON.parse(wire), manifest = value?.manifest;
|
|
6688
|
+
if (!REGISTRY_NAME.test(name) || !SEMVER_PATTERN.test(version) || Buffer.byteLength(wire) > REGISTRY_MAX_BYTES || !manifest || typeof manifest !== "object" || Array.isArray(manifest) || manifest.name !== name || manifest.version !== version || typeof value.script !== "string" || !value.script || scriptDigest(value.script) !== expectedScript)
|
|
6689
|
+
throw new Error;
|
|
6690
|
+
return value;
|
|
6691
|
+
} catch {
|
|
6692
|
+
throw new RegistryError(400, "REGISTRY_LEGACY_ARTIFACT_INVALID");
|
|
6693
|
+
}
|
|
6694
|
+
}
|
|
6695
|
+
function validateLegacyCatalog(value) {
|
|
6696
|
+
const row = value;
|
|
6697
|
+
if (!row || typeof row !== "object" || Array.isArray(row) || typeof row.name !== "string" || !REGISTRY_NAME.test(row.name) || typeof row.version !== "string" || !SEMVER_PATTERN.test(row.version) || typeof row.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(row.sha256) || !Array.isArray(row.versions) || row.versions.length !== 1 || row.versions[0] !== row.version || typeof row.source !== "string" || row.description !== undefined && typeof row.description !== "string" || row.events !== undefined && (!Array.isArray(row.events) || row.events.some((e2) => typeof e2 !== "string")))
|
|
6698
|
+
throw new RegistryError(400, "REGISTRY_LEGACY_CATALOG_INVALID");
|
|
6699
|
+
return row;
|
|
6700
|
+
}
|
|
6701
|
+
function readLegacyRegistryRow(row) {
|
|
6702
|
+
try {
|
|
6703
|
+
if (row.artifact_format !== "legacy-raw-v1" || scriptDigest(row.artifact_json) !== row.bundle_sha256 || !row.catalog_json || !row.catalog_sha256)
|
|
6704
|
+
throw new Error;
|
|
6705
|
+
const catalog = validateLegacyCatalog(JSON.parse(row.catalog_json));
|
|
6706
|
+
if (registryDigest(catalog) !== row.catalog_sha256 || catalog.name !== row.name || catalog.version !== row.version || catalog.sha256 !== row.script_sha256)
|
|
6707
|
+
throw new Error;
|
|
6708
|
+
const artifact = validateLegacyArtifact(row.artifact_json, row.name, row.version, row.script_sha256);
|
|
6709
|
+
return { artifact, catalog };
|
|
6710
|
+
} catch {
|
|
6711
|
+
throw new RegistryError(503, "REGISTRY_LEGACY_INTEGRITY_FAILED");
|
|
6712
|
+
}
|
|
6713
|
+
}
|
|
6714
|
+
|
|
6715
|
+
// src/lib/hosted-registry.ts
|
|
6716
|
+
class PgRegistryStore {
|
|
6717
|
+
db;
|
|
6718
|
+
constructor(db) {
|
|
6719
|
+
this.db = db;
|
|
6720
|
+
}
|
|
6721
|
+
async ready() {
|
|
6722
|
+
await this.db.all("SELECT name, artifact_format, catalog_json, catalog_sha256 FROM hooks_registry_versions LIMIT 0");
|
|
6723
|
+
await this.db.all("SELECT profile FROM hooks_registry_selections LIMIT 0");
|
|
6724
|
+
await this.db.all("SELECT export_sha256 FROM hooks_registry_legacy_imports LIMIT 0");
|
|
6725
|
+
}
|
|
6726
|
+
async versions() {
|
|
6727
|
+
return await this.db.all("SELECT name, version, bundle_sha256, script_sha256, artifact_json, artifact_format, catalog_json, catalog_sha256 FROM hooks_registry_versions ORDER BY name, version");
|
|
6728
|
+
}
|
|
6729
|
+
async version(name, version) {
|
|
6730
|
+
return (await this.db.all("SELECT name, version, bundle_sha256, script_sha256, artifact_json, artifact_format, catalog_json, catalog_sha256 FROM hooks_registry_versions WHERE name = ? AND version = ?", name, version))[0] ?? null;
|
|
6731
|
+
}
|
|
6732
|
+
async insertVersion(row) {
|
|
6733
|
+
return (await this.db.run("INSERT INTO hooks_registry_versions (name,version,bundle_sha256,script_sha256,artifact_json) VALUES (?,?,?,?,?) ON CONFLICT (name,version) DO NOTHING", row.name, row.version, row.bundle_sha256, row.script_sha256, row.artifact_json)).changes === 1;
|
|
6734
|
+
}
|
|
6735
|
+
async selection(profile) {
|
|
6736
|
+
const row = (await this.db.all("SELECT selection_json, selection_sha256 FROM hooks_registry_selections WHERE profile = ? ORDER BY revision DESC LIMIT 1", profile))[0];
|
|
6737
|
+
if (!row)
|
|
6738
|
+
return null;
|
|
6739
|
+
const selection = JSON.parse(row.selection_json);
|
|
6740
|
+
if (registryDigest(selection) !== row.selection_sha256)
|
|
6741
|
+
throw new RegistryError(503, "REGISTRY_SELECTION_INTEGRITY_FAILED");
|
|
6742
|
+
return selection;
|
|
6743
|
+
}
|
|
6744
|
+
async insertSelection(selection, expectedRevision) {
|
|
6745
|
+
return (await this.db.run(`INSERT INTO hooks_registry_selections (profile,revision,selection_json,selection_sha256)
|
|
6746
|
+
SELECT ?,?,?,? WHERE COALESCE((SELECT MAX(revision) FROM hooks_registry_selections WHERE profile = ?),0) = ?
|
|
6747
|
+
ON CONFLICT (profile,revision) DO NOTHING`, selection.profile, selection.revision, canonicalJson(selection), registryDigest(selection), selection.profile, expectedRevision)).changes === 1;
|
|
6748
|
+
}
|
|
6749
|
+
}
|
|
6750
|
+
|
|
6751
|
+
class HostedRegistry {
|
|
6752
|
+
store;
|
|
6753
|
+
constructor(store) {
|
|
6754
|
+
this.store = store;
|
|
6755
|
+
}
|
|
6756
|
+
async ready() {
|
|
6757
|
+
await this.store.ready?.();
|
|
6758
|
+
}
|
|
6759
|
+
async publish(value) {
|
|
6760
|
+
const artifact = validateRegistryArtifact(value), { name, version } = artifact.manifest;
|
|
6761
|
+
const row = { name, version, bundle_sha256: registryDigest(artifact), script_sha256: scriptDigest(artifact.script), artifact_json: canonicalJson(artifact) };
|
|
6762
|
+
const inserted = await this.store.insertVersion(row);
|
|
6763
|
+
if (!inserted) {
|
|
6764
|
+
const previous = await this.store.version(name, version);
|
|
6765
|
+
if (!previous || previous.artifact_format === "legacy-raw-v1" || previous.artifact_json !== row.artifact_json || previous.bundle_sha256 !== row.bundle_sha256)
|
|
6766
|
+
throw new RegistryError(409, "REGISTRY_VERSION_CONFLICT");
|
|
6767
|
+
}
|
|
6768
|
+
return { ok: true, idempotent: !inserted, hook: { name, version, sha256: row.script_sha256, bundle_sha256: row.bundle_sha256, source: "hosted" } };
|
|
6769
|
+
}
|
|
6770
|
+
async artifact(name, version) {
|
|
6771
|
+
const row = await this.store.version(name, version);
|
|
6772
|
+
if (!row)
|
|
6773
|
+
throw new RegistryError(404, "REGISTRY_VERSION_NOT_FOUND");
|
|
6774
|
+
if (row.artifact_format === "legacy-raw-v1")
|
|
6775
|
+
throw new RegistryError(409, "REGISTRY_LEGACY_ARTIFACT_NOT_PORTABLE");
|
|
6776
|
+
const artifact = validateRegistryArtifact(JSON.parse(row.artifact_json));
|
|
6777
|
+
if (artifact.manifest.name !== name || artifact.manifest.version !== version || registryDigest(artifact) !== row.bundle_sha256 || scriptDigest(artifact.script) !== row.script_sha256)
|
|
6778
|
+
throw new RegistryError(503, "REGISTRY_ARTIFACT_INTEGRITY_FAILED");
|
|
6779
|
+
return { artifact, row };
|
|
6780
|
+
}
|
|
6781
|
+
async artifactWire(name, version) {
|
|
6782
|
+
const row = await this.store.version(name, version);
|
|
6783
|
+
if (!row)
|
|
6784
|
+
throw new RegistryError(404, "REGISTRY_VERSION_NOT_FOUND");
|
|
6785
|
+
if (row.artifact_format === "legacy-raw-v1") {
|
|
6786
|
+
readLegacyRegistryRow(row);
|
|
6787
|
+
return { body: row.artifact_json, row, format: "legacy-raw-v1", portable: false };
|
|
6788
|
+
}
|
|
6789
|
+
const valid = await this.artifact(name, version);
|
|
6790
|
+
return { body: valid.row.artifact_json, row: valid.row, format: "portable-v1", portable: true };
|
|
6791
|
+
}
|
|
6792
|
+
async catalog() {
|
|
6793
|
+
const rows = await this.store.versions(), groups = new Map;
|
|
6794
|
+
for (const row of rows)
|
|
6795
|
+
groups.set(row.name, [...groups.get(row.name) ?? [], row]);
|
|
6796
|
+
return { hooks: [...groups.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([name, versions]) => {
|
|
6797
|
+
versions.sort((a, b) => compareVersions(b.version, a.version) || b.version.localeCompare(a.version));
|
|
6798
|
+
const row = versions[0];
|
|
6799
|
+
if (row.artifact_format === "legacy-raw-v1") {
|
|
6800
|
+
const { catalog } = readLegacyRegistryRow(row);
|
|
6801
|
+
return { ...catalog, name, version: row.version, sha256: row.script_sha256, bundle_sha256: row.bundle_sha256, source: "hosted", format: "legacy-raw-v1", portable: false, versions: versions.map((v) => v.version) };
|
|
6802
|
+
}
|
|
6803
|
+
const artifact = validateRegistryArtifact(JSON.parse(row.artifact_json));
|
|
6804
|
+
if (artifact.manifest.name !== name || artifact.manifest.version !== row.version || registryDigest(artifact) !== row.bundle_sha256 || scriptDigest(artifact.script) !== row.script_sha256)
|
|
6805
|
+
throw new RegistryError(503, "REGISTRY_ARTIFACT_INTEGRITY_FAILED");
|
|
6806
|
+
return { name, version: row.version, sha256: row.script_sha256, bundle_sha256: row.bundle_sha256, description: artifact.manifest.description ?? "", events: artifact.manifest.events, source: "hosted", format: "portable-v1", portable: true, versions: versions.map((v) => v.version) };
|
|
6807
|
+
}) };
|
|
6808
|
+
}
|
|
6809
|
+
async selection(profile) {
|
|
6810
|
+
if (!REGISTRY_NAME.test(profile))
|
|
6811
|
+
throw new RegistryError(400, "REGISTRY_PROFILE_INVALID");
|
|
6812
|
+
const selection = await this.store.selection(profile);
|
|
6813
|
+
if (!selection)
|
|
6814
|
+
throw new RegistryError(404, "REGISTRY_SELECTION_NOT_FOUND");
|
|
6815
|
+
return selection;
|
|
6816
|
+
}
|
|
6817
|
+
async select(profile, value) {
|
|
6818
|
+
const body = value;
|
|
6819
|
+
if (!REGISTRY_NAME.test(profile) || !body || !Number.isSafeInteger(body.expected_revision) || body.expected_revision < 0 || body.expected_revision >= 2147483647 || !body.hooks || typeof body.hooks !== "object" || Array.isArray(body.hooks) || Object.keys(body).some((k) => !["expected_revision", "hooks"].includes(k)) || Object.keys(body.hooks).length > 256)
|
|
6820
|
+
throw new RegistryError(400, "REGISTRY_SELECTION_INVALID");
|
|
6821
|
+
const hooks = {};
|
|
6822
|
+
for (const [name, pin] of Object.entries(body.hooks)) {
|
|
6823
|
+
if (!REGISTRY_NAME.test(name) || !pin || typeof pin !== "object" || Object.keys(pin).some((k) => !["version", "bundle_sha256"].includes(k)) || typeof pin.version !== "string" || typeof pin.bundle_sha256 !== "string" || !/^[a-f0-9]{64}$/.test(pin.bundle_sha256))
|
|
6824
|
+
throw new RegistryError(400, "REGISTRY_SELECTION_INVALID");
|
|
6825
|
+
const { row } = await this.artifact(name, pin.version);
|
|
6826
|
+
if (pin.bundle_sha256 !== row.bundle_sha256)
|
|
6827
|
+
throw new RegistryError(409, "REGISTRY_SELECTION_DIGEST_MISMATCH");
|
|
6828
|
+
hooks[name] = { version: row.version, sha256: row.script_sha256, bundle_sha256: row.bundle_sha256, source: "hosted" };
|
|
6829
|
+
}
|
|
6830
|
+
const next = { profile, revision: body.expected_revision + 1, hooks };
|
|
6831
|
+
if (await this.store.insertSelection(next, body.expected_revision))
|
|
6832
|
+
return next;
|
|
6833
|
+
const current = await this.store.selection(profile);
|
|
6834
|
+
if (current && canonicalJson(current) === canonicalJson(next))
|
|
6835
|
+
return current;
|
|
6836
|
+
throw new RegistryError(409, "REGISTRY_SELECTION_PRECONDITION_FAILED");
|
|
6837
|
+
}
|
|
6838
|
+
}
|
|
6839
|
+
|
|
6840
|
+
// src/db/remote-storage.ts
|
|
6841
|
+
import pg from "pg";
|
|
6842
|
+
function translatePlaceholders(sql) {
|
|
6843
|
+
let index = 0;
|
|
6844
|
+
return sql.replace(/\?/g, () => `$${++index}`);
|
|
6845
|
+
}
|
|
6846
|
+
function normalizeParams(params) {
|
|
6847
|
+
const flat = params.length === 1 && Array.isArray(params[0]) ? params[0] : params;
|
|
6848
|
+
return flat.map((value) => value === undefined ? null : value);
|
|
6849
|
+
}
|
|
6850
|
+
function sslConfigFor(connectionString) {
|
|
6851
|
+
const wantsSsl = wantsSslFor(connectionString);
|
|
6852
|
+
if (!wantsSsl)
|
|
6853
|
+
return;
|
|
6854
|
+
const insecure = process.env.HASNA_HOOKS_PG_INSECURE_TLS === "1" || process.env.HOOKS_PG_INSECURE_TLS === "1";
|
|
6855
|
+
if (insecure && false) {}
|
|
6856
|
+
return insecure ? { rejectUnauthorized: false } : { rejectUnauthorized: true };
|
|
6857
|
+
}
|
|
6858
|
+
function wantsSslFor(connectionString) {
|
|
6859
|
+
let raw;
|
|
6860
|
+
try {
|
|
6861
|
+
raw = new URL(connectionString).search.replace(/^\?/, "");
|
|
6862
|
+
} catch {
|
|
6863
|
+
raw = connectionString;
|
|
6864
|
+
}
|
|
6865
|
+
try {
|
|
6866
|
+
raw = decodeURIComponent(raw);
|
|
6867
|
+
} catch {}
|
|
6868
|
+
const paramValue = (name) => {
|
|
6869
|
+
const match = raw.match(new RegExp(`(?:^|[&\\s])${name}\\s*=\\s*([^&\\s]+)`, "i"));
|
|
6870
|
+
return match ? match[1].toLowerCase() : undefined;
|
|
6871
|
+
};
|
|
6872
|
+
const sslmode = paramValue("sslmode");
|
|
6873
|
+
if (sslmode !== undefined)
|
|
6874
|
+
return sslmode !== "disable" && sslmode !== "allow";
|
|
6875
|
+
const ssl = paramValue("ssl");
|
|
6876
|
+
if (ssl !== undefined)
|
|
6877
|
+
return ssl !== "false" && ssl !== "0" && ssl !== "no";
|
|
6878
|
+
return false;
|
|
6879
|
+
}
|
|
6880
|
+
|
|
6881
|
+
class PgAdapterAsync {
|
|
6882
|
+
pool;
|
|
6883
|
+
constructor(connectionString, options = {}) {
|
|
6884
|
+
const timeout = options.timeoutMs;
|
|
6885
|
+
this.pool = new pg.Pool({ connectionString, ssl: sslConfigFor(connectionString), ...timeout ? { connectionTimeoutMillis: timeout, query_timeout: timeout, statement_timeout: timeout } : {} });
|
|
6886
|
+
}
|
|
6887
|
+
async readOnlyAll(sql, ...params) {
|
|
6888
|
+
const client = await this.pool.connect();
|
|
6889
|
+
try {
|
|
6890
|
+
await client.query("BEGIN READ ONLY");
|
|
6891
|
+
return (await client.query(translatePlaceholders(sql), normalizeParams(params))).rows;
|
|
6892
|
+
} finally {
|
|
6893
|
+
try {
|
|
6894
|
+
await client.query("ROLLBACK");
|
|
6895
|
+
} finally {
|
|
6896
|
+
client.release();
|
|
6897
|
+
}
|
|
6898
|
+
}
|
|
6899
|
+
}
|
|
6900
|
+
async transaction(operation) {
|
|
6901
|
+
const client = await this.pool.connect();
|
|
6902
|
+
try {
|
|
6903
|
+
await client.query("BEGIN");
|
|
6904
|
+
const result = await operation({
|
|
6905
|
+
run: async (sql, ...params) => ({ changes: (await client.query(translatePlaceholders(sql), normalizeParams(params))).rowCount ?? 0 }),
|
|
6906
|
+
all: async (sql, ...params) => (await client.query(translatePlaceholders(sql), normalizeParams(params))).rows
|
|
6907
|
+
});
|
|
6908
|
+
await client.query("COMMIT");
|
|
6909
|
+
return result;
|
|
6910
|
+
} catch (error) {
|
|
6911
|
+
await client.query("ROLLBACK");
|
|
6912
|
+
throw error;
|
|
6913
|
+
} finally {
|
|
6914
|
+
client.release();
|
|
6915
|
+
}
|
|
6916
|
+
}
|
|
6917
|
+
async run(sql, ...params) {
|
|
6918
|
+
const result = await this.pool.query(translatePlaceholders(sql), normalizeParams(params));
|
|
6919
|
+
return { changes: result.rowCount ?? 0 };
|
|
6920
|
+
}
|
|
6921
|
+
async all(sql, ...params) {
|
|
6922
|
+
const result = await this.pool.query(translatePlaceholders(sql), normalizeParams(params));
|
|
6923
|
+
return result.rows;
|
|
6924
|
+
}
|
|
6925
|
+
async close() {
|
|
6926
|
+
await this.pool.end();
|
|
6927
|
+
}
|
|
6928
|
+
}
|
|
6929
|
+
|
|
6930
|
+
// src/db/storage-sync.ts
|
|
6931
|
+
var STORAGE_BACKENDS = ["sqlite", "postgresql"];
|
|
6932
|
+
var HOOKS_STORAGE_ENV = "HASNA_HOOKS_DATABASE_URL";
|
|
6933
|
+
var HOOKS_STORAGE_FALLBACK_ENV = "HOOKS_DATABASE_URL";
|
|
6934
|
+
var HOOKS_STORAGE_BACKEND_ENV = "HASNA_HOOKS_STORAGE_BACKEND";
|
|
6935
|
+
var HOOKS_STORAGE_BACKEND_FALLBACK_ENV = "HOOKS_STORAGE_BACKEND";
|
|
6936
|
+
var STORAGE_DATABASE_ENV = [HOOKS_STORAGE_ENV, HOOKS_STORAGE_FALLBACK_ENV];
|
|
6937
|
+
var RETIRED_STORAGE_MODE_ENV = ["HASNA_HOOKS_STORAGE_MODE", "HOOKS_STORAGE_MODE"];
|
|
6938
|
+
function readEnv(name) {
|
|
6939
|
+
const value = process.env[name]?.trim();
|
|
6940
|
+
return value || undefined;
|
|
6941
|
+
}
|
|
6942
|
+
var RETIRED_MODE_REPLACEMENT = {
|
|
6943
|
+
local: "sqlite",
|
|
6944
|
+
hybrid: "postgresql",
|
|
6945
|
+
remote: "postgresql",
|
|
6946
|
+
self_hosted: "postgresql",
|
|
6947
|
+
"self-hosted": "postgresql",
|
|
6948
|
+
selfhosted: "postgresql",
|
|
6949
|
+
cloud: "postgresql"
|
|
6950
|
+
};
|
|
6951
|
+
var BACKEND_ALIASES = {
|
|
6952
|
+
sqlite: "sqlite",
|
|
6953
|
+
sqlite3: "sqlite",
|
|
6954
|
+
postgresql: "postgresql",
|
|
6955
|
+
postgres: "postgresql",
|
|
6956
|
+
pg: "postgresql"
|
|
6957
|
+
};
|
|
6958
|
+
function assertNoRetiredModeEnv() {
|
|
6959
|
+
for (const name of RETIRED_STORAGE_MODE_ENV) {
|
|
6960
|
+
const value = readEnv(name);
|
|
6961
|
+
if (!value)
|
|
6962
|
+
continue;
|
|
6963
|
+
const replacement = RETIRED_MODE_REPLACEMENT[value.trim().toLowerCase()];
|
|
6964
|
+
const mapping = replacement ? `${value} maps to ${replacement}` : `use one of ${STORAGE_BACKENDS.join(", ")}`;
|
|
6965
|
+
throw new Error(`${name} is a retired deployment-mode variable and is no longer read. ` + `Hooks storage is a data-backend switch, not a deployment mode: ` + `set ${HOOKS_STORAGE_BACKEND_ENV} to ${STORAGE_BACKENDS.join(" or ")} instead (${mapping}), ` + `then unset ${name}.`);
|
|
6966
|
+
}
|
|
6967
|
+
}
|
|
6968
|
+
function normalizeStorageBackend(value, envName) {
|
|
6969
|
+
if (value === undefined)
|
|
6970
|
+
return;
|
|
6971
|
+
const normalized = value.trim().toLowerCase();
|
|
6972
|
+
if (normalized === "")
|
|
6973
|
+
return;
|
|
6974
|
+
const backend = BACKEND_ALIASES[normalized];
|
|
6975
|
+
if (backend)
|
|
6976
|
+
return backend;
|
|
6977
|
+
const replacement = RETIRED_MODE_REPLACEMENT[normalized];
|
|
6978
|
+
if (replacement) {
|
|
6979
|
+
throw new Error(`${envName}=${value} names a retired deployment mode. ` + `local/hybrid/remote/self_hosted/cloud were removed: hooks storage now selects a data ` + `backend only. Set ${envName}=${replacement} instead.`);
|
|
6980
|
+
}
|
|
6981
|
+
throw new Error(`${envName}=${value} is not a known hooks storage backend. ` + `Set ${HOOKS_STORAGE_BACKEND_ENV} to one of ${STORAGE_BACKENDS.join(", ")}.`);
|
|
6982
|
+
}
|
|
6983
|
+
function getStorageDatabaseEnvName() {
|
|
6984
|
+
for (const name of STORAGE_DATABASE_ENV) {
|
|
6985
|
+
if (readEnv(name))
|
|
6986
|
+
return name;
|
|
6987
|
+
}
|
|
6988
|
+
return null;
|
|
6989
|
+
}
|
|
6990
|
+
function getStorageDatabaseEnv() {
|
|
6991
|
+
const name = getStorageDatabaseEnvName();
|
|
6992
|
+
return name ? { name } : null;
|
|
6993
|
+
}
|
|
6994
|
+
function getStorageDatabaseUrl() {
|
|
6995
|
+
const env = getStorageDatabaseEnv();
|
|
6996
|
+
return env ? readEnv(env.name) ?? null : null;
|
|
6997
|
+
}
|
|
6998
|
+
function getStorageBackend() {
|
|
6999
|
+
assertNoRetiredModeEnv();
|
|
7000
|
+
const backend = normalizeStorageBackend(readEnv(HOOKS_STORAGE_BACKEND_ENV), HOOKS_STORAGE_BACKEND_ENV) ?? normalizeStorageBackend(readEnv(HOOKS_STORAGE_BACKEND_FALLBACK_ENV), HOOKS_STORAGE_BACKEND_FALLBACK_ENV);
|
|
7001
|
+
if (backend)
|
|
7002
|
+
return backend;
|
|
7003
|
+
return getStorageDatabaseUrl() ? "postgresql" : "sqlite";
|
|
7004
|
+
}
|
|
7005
|
+
|
|
7006
|
+
// node_modules/@hasna/contracts/dist/auth/index.js
|
|
7007
|
+
import { createHash as createHash3, createHmac, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
|
|
7008
|
+
var MAX_TENANT_ID_LENGTH = 64;
|
|
7009
|
+
var TENANT_ID_PATTERN = new RegExp(`^[A-Za-z0-9][A-Za-z0-9._-]{0,${MAX_TENANT_ID_LENGTH - 1}}$`);
|
|
7010
|
+
var UUID_HEX = "[0-9a-fA-F]";
|
|
7011
|
+
var UUID_PATTERN = new RegExp(`^\\{?(?:${UUID_HEX}{8}-${UUID_HEX}{4}-${UUID_HEX}{4}-${UUID_HEX}{4}-${UUID_HEX}{12}|${UUID_HEX}{32})\\}?$`);
|
|
7012
|
+
function isValidTenantId(value) {
|
|
7013
|
+
return typeof value === "string" && TENANT_ID_PATTERN.test(value);
|
|
7014
|
+
}
|
|
7015
|
+
function isUuidTenantId(value) {
|
|
7016
|
+
return typeof value === "string" && UUID_PATTERN.test(value);
|
|
7017
|
+
}
|
|
7018
|
+
function canonicalizeTenantId(value) {
|
|
7019
|
+
if (!isUuidTenantId(value))
|
|
7020
|
+
return value;
|
|
7021
|
+
const hex = value.replace(/[{}-]/g, "").toLowerCase();
|
|
7022
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
7023
|
+
}
|
|
7024
|
+
function normalizeTenantId(value) {
|
|
7025
|
+
const trimmed = typeof value === "string" ? value.trim() : "";
|
|
7026
|
+
const canonical = canonicalizeTenantId(trimmed);
|
|
7027
|
+
if (!isValidTenantId(canonical)) {
|
|
7028
|
+
throw new Error(`Invalid tenant id '${value}'. Expected 1-${MAX_TENANT_ID_LENGTH} characters matching ${TENANT_ID_PATTERN} (a UUID, ULID, slug, or prefixed id).`);
|
|
7029
|
+
}
|
|
7030
|
+
return canonical;
|
|
7031
|
+
}
|
|
7032
|
+
function tenantIdsEqual(left, right) {
|
|
7033
|
+
const canonical = (value) => {
|
|
7034
|
+
if (typeof value !== "string")
|
|
7035
|
+
return null;
|
|
7036
|
+
const folded = canonicalizeTenantId(value.trim());
|
|
7037
|
+
return isValidTenantId(folded) ? folded : null;
|
|
7038
|
+
};
|
|
7039
|
+
const a = canonical(left);
|
|
7040
|
+
const b = canonical(right);
|
|
7041
|
+
return a !== null && b !== null && a === b;
|
|
7042
|
+
}
|
|
7043
|
+
function ownTenantId(source) {
|
|
7044
|
+
return Object.hasOwn(source, "tid") ? source.tid : undefined;
|
|
7045
|
+
}
|
|
7046
|
+
var API_KEY_TOKEN_VERSION = 1;
|
|
7047
|
+
var API_KEY_NAMESPACE = "hasna";
|
|
7048
|
+
var API_KEY_TOKEN_PATTERN = /^hasna_([a-z][a-z0-9-]*)_([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]+)$/;
|
|
7049
|
+
var TOKEN_PATTERN = API_KEY_TOKEN_PATTERN;
|
|
7050
|
+
var DEFAULT_API_KEY_TTL_SECONDS = 90 * 24 * 60 * 60;
|
|
7051
|
+
function ownAgentClaim(source) {
|
|
7052
|
+
return Object.hasOwn(source, "agent") && typeof source.agent === "string" ? source.agent : null;
|
|
7053
|
+
}
|
|
7054
|
+
function ownScopesClaim(source) {
|
|
7055
|
+
return Object.hasOwn(source, "scopes") && Array.isArray(source.scopes) ? source.scopes : null;
|
|
7056
|
+
}
|
|
7057
|
+
function ownOption(options, name) {
|
|
7058
|
+
return Object.hasOwn(options, name) ? options[name] : undefined;
|
|
7059
|
+
}
|
|
7060
|
+
var typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
|
|
7061
|
+
var intrinsicViewBuffer = Object.getOwnPropertyDescriptor(typedArrayPrototype, "buffer").get;
|
|
7062
|
+
var intrinsicViewByteOffset = Object.getOwnPropertyDescriptor(typedArrayPrototype, "byteOffset").get;
|
|
7063
|
+
var intrinsicViewByteLength = Object.getOwnPropertyDescriptor(typedArrayPrototype, "byteLength").get;
|
|
7064
|
+
var intrinsicDataViewBuffer = Object.getOwnPropertyDescriptor(DataView.prototype, "buffer").get;
|
|
7065
|
+
var intrinsicDataViewByteOffset = Object.getOwnPropertyDescriptor(DataView.prototype, "byteOffset").get;
|
|
7066
|
+
var intrinsicDataViewByteLength = Object.getOwnPropertyDescriptor(DataView.prototype, "byteLength").get;
|
|
7067
|
+
function viewWindow(view) {
|
|
7068
|
+
try {
|
|
7069
|
+
return [
|
|
7070
|
+
intrinsicViewBuffer.call(view),
|
|
7071
|
+
intrinsicViewByteOffset.call(view),
|
|
7072
|
+
intrinsicViewByteLength.call(view)
|
|
7073
|
+
];
|
|
7074
|
+
} catch {
|
|
7075
|
+
return [
|
|
7076
|
+
intrinsicDataViewBuffer.call(view),
|
|
7077
|
+
intrinsicDataViewByteOffset.call(view),
|
|
7078
|
+
intrinsicDataViewByteLength.call(view)
|
|
7079
|
+
];
|
|
7080
|
+
}
|
|
7081
|
+
}
|
|
7082
|
+
function toBuffer(secret) {
|
|
7083
|
+
if (typeof secret === "string")
|
|
7084
|
+
return Buffer.from(secret.trim(), "utf8");
|
|
7085
|
+
if (ArrayBuffer.isView(secret)) {
|
|
7086
|
+
const [store, byteOffset, byteLength] = viewWindow(secret);
|
|
7087
|
+
return Buffer.from(store, byteOffset, byteLength);
|
|
7088
|
+
}
|
|
7089
|
+
return Buffer.from(secret);
|
|
7090
|
+
}
|
|
7091
|
+
function hmac(signingSecret, message) {
|
|
7092
|
+
return createHmac("sha256", toBuffer(signingSecret)).update(message, "utf8").digest();
|
|
7093
|
+
}
|
|
7094
|
+
function apiKeyPrefix(app) {
|
|
7095
|
+
return `${API_KEY_NAMESPACE}_${app}_`;
|
|
7096
|
+
}
|
|
7097
|
+
function parseApiKey(token) {
|
|
7098
|
+
if (typeof token !== "string")
|
|
7099
|
+
return null;
|
|
7100
|
+
const match = TOKEN_PATTERN.exec(token);
|
|
7101
|
+
if (!match)
|
|
7102
|
+
return null;
|
|
7103
|
+
const [, app, body, sig] = match;
|
|
7104
|
+
if (!app || !body || !sig)
|
|
7105
|
+
return null;
|
|
7106
|
+
let claims;
|
|
7107
|
+
try {
|
|
7108
|
+
claims = JSON.parse(Buffer.from(body, "base64url").toString("utf8"));
|
|
7109
|
+
} catch {
|
|
7110
|
+
return null;
|
|
7111
|
+
}
|
|
7112
|
+
if (typeof claims !== "object" || claims === null || typeof claims.kid !== "string" || typeof claims.app !== "string" || ownScopesClaim(claims) === null) {
|
|
7113
|
+
return null;
|
|
7114
|
+
}
|
|
7115
|
+
const claimedTid = ownTenantId(claims);
|
|
7116
|
+
if (claimedTid !== undefined && !isValidTenantId(claimedTid)) {
|
|
7117
|
+
return null;
|
|
7118
|
+
}
|
|
7119
|
+
return { app, body, sig, claims };
|
|
7120
|
+
}
|
|
7121
|
+
function verifyApiKeyToken(token, options) {
|
|
7122
|
+
const optSigningSecret = ownOption(options, "signingSecret");
|
|
7123
|
+
const optExpectedApp = ownOption(options, "expectedApp");
|
|
7124
|
+
const optNowMs = ownOption(options, "nowMs");
|
|
7125
|
+
const optLeewaySeconds = ownOption(options, "leewaySeconds");
|
|
7126
|
+
const optRequiredScopes = ownOption(options, "requiredScopes");
|
|
7127
|
+
const optRequireTenant = ownOption(options, "requireTenant");
|
|
7128
|
+
const optExpectedTid = ownOption(options, "expectedTid");
|
|
7129
|
+
const parsed = parseApiKey(token);
|
|
7130
|
+
if (!parsed) {
|
|
7131
|
+
return { ok: false, reason: "malformed", message: "Token is malformed." };
|
|
7132
|
+
}
|
|
7133
|
+
const { app, body, sig, claims } = parsed;
|
|
7134
|
+
if (claims.v !== API_KEY_TOKEN_VERSION) {
|
|
7135
|
+
return { ok: false, reason: "unsupported_version", message: `Unsupported token version ${claims.v}.` };
|
|
7136
|
+
}
|
|
7137
|
+
if (claims.app !== app) {
|
|
7138
|
+
return { ok: false, reason: "app_mismatch", message: "Token prefix app does not match claims." };
|
|
7139
|
+
}
|
|
7140
|
+
if (optExpectedApp !== undefined && app !== optExpectedApp) {
|
|
7141
|
+
return { ok: false, reason: "app_mismatch", message: `Token is for app '${app}', expected '${optExpectedApp}'.` };
|
|
7142
|
+
}
|
|
7143
|
+
const expected = hmac(optSigningSecret, `${apiKeyPrefix(app)}${body}`);
|
|
7144
|
+
let provided;
|
|
7145
|
+
try {
|
|
7146
|
+
provided = Buffer.from(sig, "base64url");
|
|
7147
|
+
} catch {
|
|
7148
|
+
return { ok: false, reason: "bad_signature", message: "Signature is not valid base64url." };
|
|
7149
|
+
}
|
|
7150
|
+
if (provided.length !== expected.length || !timingSafeEqual(provided, expected)) {
|
|
7151
|
+
return { ok: false, reason: "bad_signature", message: "Signature verification failed." };
|
|
7152
|
+
}
|
|
7153
|
+
const agent = ownAgentClaim(claims);
|
|
7154
|
+
const now = Math.floor((optNowMs ?? Date.now()) / 1000);
|
|
7155
|
+
const leeway = optLeewaySeconds ?? 0;
|
|
7156
|
+
if (typeof claims.iat === "number" && now + leeway < claims.iat) {
|
|
7157
|
+
return { ok: false, reason: "not_yet_valid", message: "Token is not yet valid.", agent };
|
|
7158
|
+
}
|
|
7159
|
+
if (claims.exp !== null && typeof claims.exp === "number" && now - leeway >= claims.exp) {
|
|
7160
|
+
return { ok: false, reason: "expired", message: "Token has expired.", agent };
|
|
7161
|
+
}
|
|
7162
|
+
const verifiedTid = ownTenantId(claims);
|
|
7163
|
+
const tid = verifiedTid === undefined ? null : canonicalizeTenantId(verifiedTid);
|
|
7164
|
+
const tenantRequired = Boolean(optRequireTenant) || optExpectedTid !== undefined;
|
|
7165
|
+
if (tenantRequired && tid === null) {
|
|
7166
|
+
return {
|
|
7167
|
+
ok: false,
|
|
7168
|
+
reason: "tenant_required",
|
|
7169
|
+
message: "Token carries no tenant id ('tid') and this service requires one.",
|
|
7170
|
+
kid: claims.kid,
|
|
7171
|
+
tid: null,
|
|
7172
|
+
agent
|
|
7173
|
+
};
|
|
7174
|
+
}
|
|
7175
|
+
if (optExpectedTid !== undefined && !tenantIdsEqual(tid, optExpectedTid)) {
|
|
7176
|
+
const expectationIsWellFormed = typeof optExpectedTid === "string" && isValidTenantId(optExpectedTid.trim());
|
|
7177
|
+
return {
|
|
7178
|
+
ok: false,
|
|
7179
|
+
reason: "tenant_mismatch",
|
|
7180
|
+
message: expectationIsWellFormed ? "Token is for a different tenant than the one this service accepts." : "Token tenant cannot be checked: the expected tenant id is not a valid tenant id.",
|
|
7181
|
+
kid: claims.kid,
|
|
7182
|
+
tid,
|
|
7183
|
+
agent
|
|
7184
|
+
};
|
|
7185
|
+
}
|
|
7186
|
+
if (optRequiredScopes && optRequiredScopes.length > 0) {
|
|
7187
|
+
const granted = ownScopesClaim(claims) ?? [];
|
|
7188
|
+
const satisfies = (required) => granted.some((g) => {
|
|
7189
|
+
if (g === "*")
|
|
7190
|
+
return true;
|
|
7191
|
+
const gi = g.indexOf(":");
|
|
7192
|
+
const ri = required.indexOf(":");
|
|
7193
|
+
if (gi < 0 || ri < 0)
|
|
7194
|
+
return false;
|
|
7195
|
+
const gApp = g.slice(0, gi);
|
|
7196
|
+
const gAction = g.slice(gi + 1);
|
|
7197
|
+
const rApp = required.slice(0, ri);
|
|
7198
|
+
const rAction = required.slice(ri + 1);
|
|
7199
|
+
return (gApp === "*" || gApp === rApp) && (gAction === "*" || gAction === rAction);
|
|
7200
|
+
});
|
|
7201
|
+
for (const required of optRequiredScopes) {
|
|
7202
|
+
if (!satisfies(required)) {
|
|
7203
|
+
return { ok: false, reason: "insufficient_scope", message: `Missing required scope '${required}'.`, agent };
|
|
7204
|
+
}
|
|
7205
|
+
}
|
|
7206
|
+
}
|
|
7207
|
+
return { ok: true, claims, kid: claims.kid, app, tid, agent };
|
|
7208
|
+
}
|
|
7209
|
+
var DEFAULT_API_KEYS_TABLE = "api_keys";
|
|
7210
|
+
var API_KEY_ISSUANCE_PENDING_REASON = "credential_delivery_pending";
|
|
7211
|
+
function createTableSql(table) {
|
|
7212
|
+
return `CREATE TABLE IF NOT EXISTS ${table} (
|
|
7213
|
+
kid TEXT PRIMARY KEY,
|
|
7214
|
+
app TEXT NOT NULL,
|
|
7215
|
+
agent TEXT,
|
|
7216
|
+
scopes JSONB NOT NULL,
|
|
7217
|
+
token_hash TEXT NOT NULL UNIQUE,
|
|
7218
|
+
issued_at TIMESTAMPTZ NOT NULL,
|
|
7219
|
+
expires_at TIMESTAMPTZ,
|
|
7220
|
+
revoked_at TIMESTAMPTZ,
|
|
7221
|
+
revoked_reason TEXT,
|
|
7222
|
+
last_used_at TIMESTAMPTZ,
|
|
7223
|
+
created_by TEXT,
|
|
7224
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
7225
|
+
)`;
|
|
7226
|
+
}
|
|
7227
|
+
function apiKeyMigrations(table = DEFAULT_API_KEYS_TABLE) {
|
|
7228
|
+
return [
|
|
7229
|
+
{ id: `hasna_auth_0001_${table}`, sql: createTableSql(table) },
|
|
7230
|
+
{
|
|
7231
|
+
id: `hasna_auth_0002_${table}_indexes`,
|
|
7232
|
+
sql: `CREATE INDEX IF NOT EXISTS ${table}_app_idx ON ${table} (app);
|
|
7233
|
+
CREATE INDEX IF NOT EXISTS ${table}_token_hash_idx ON ${table} (token_hash);`
|
|
7234
|
+
},
|
|
7235
|
+
{
|
|
7236
|
+
id: `hasna_auth_0003_${table}_tenant`,
|
|
7237
|
+
sql: `ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS tid TEXT;
|
|
7238
|
+
CREATE INDEX IF NOT EXISTS ${table}_tid_idx ON ${table} (tid);`
|
|
7239
|
+
}
|
|
7240
|
+
];
|
|
7241
|
+
}
|
|
7242
|
+
function toIso(value) {
|
|
7243
|
+
if (value === null || value === undefined)
|
|
7244
|
+
return null;
|
|
7245
|
+
if (value instanceof Date)
|
|
7246
|
+
return value.toISOString();
|
|
7247
|
+
return new Date(String(value)).toISOString();
|
|
7248
|
+
}
|
|
7249
|
+
function parseScopes(value) {
|
|
7250
|
+
if (Array.isArray(value))
|
|
7251
|
+
return value.map((v) => String(v));
|
|
7252
|
+
if (typeof value === "string") {
|
|
7253
|
+
try {
|
|
7254
|
+
const parsed = JSON.parse(value);
|
|
7255
|
+
return Array.isArray(parsed) ? parsed.map((v) => String(v)) : [];
|
|
7256
|
+
} catch {
|
|
7257
|
+
return [];
|
|
7258
|
+
}
|
|
7259
|
+
}
|
|
7260
|
+
return [];
|
|
7261
|
+
}
|
|
7262
|
+
function rowToRecord(row) {
|
|
7263
|
+
const tid = ownTenantId(row);
|
|
7264
|
+
const agentValue = Object.hasOwn(row, "agent") ? row.agent : null;
|
|
7265
|
+
return {
|
|
7266
|
+
kid: String(row.kid),
|
|
7267
|
+
app: String(row.app),
|
|
7268
|
+
agent: agentValue === null || agentValue === undefined ? null : String(agentValue),
|
|
7269
|
+
tid: tid === null || tid === undefined ? null : String(tid),
|
|
7270
|
+
scopes: parseScopes(row.scopes),
|
|
7271
|
+
tokenHash: String(row.token_hash),
|
|
7272
|
+
issuedAt: toIso(row.issued_at) ?? new Date(0).toISOString(),
|
|
7273
|
+
expiresAt: toIso(row.expires_at),
|
|
7274
|
+
revokedAt: toIso(row.revoked_at),
|
|
7275
|
+
revokedReason: row.revoked_reason === null || row.revoked_reason === undefined ? null : String(row.revoked_reason),
|
|
7276
|
+
lastUsedAt: toIso(row.last_used_at),
|
|
7277
|
+
createdBy: row.created_by === null || row.created_by === undefined ? null : String(row.created_by)
|
|
7278
|
+
};
|
|
7279
|
+
}
|
|
7280
|
+
|
|
7281
|
+
class ApiKeyStore {
|
|
7282
|
+
client;
|
|
7283
|
+
table;
|
|
7284
|
+
constructor(client, options = {}) {
|
|
7285
|
+
this.client = client;
|
|
7286
|
+
this.table = options.table ?? DEFAULT_API_KEYS_TABLE;
|
|
7287
|
+
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(this.table)) {
|
|
7288
|
+
throw new Error(`Invalid api-keys table name '${this.table}'.`);
|
|
7289
|
+
}
|
|
7290
|
+
}
|
|
7291
|
+
migrations() {
|
|
7292
|
+
return apiKeyMigrations(this.table);
|
|
7293
|
+
}
|
|
7294
|
+
async ensureSchema() {
|
|
7295
|
+
for (const migration of this.migrations()) {
|
|
7296
|
+
await this.client.execute(migration.sql);
|
|
7297
|
+
}
|
|
7298
|
+
}
|
|
7299
|
+
async insert(input) {
|
|
7300
|
+
await this.insertWithLifecycle(input, null, null);
|
|
7301
|
+
}
|
|
7302
|
+
async insertWithLifecycle(input, revokedAt, revokedReason) {
|
|
7303
|
+
const tid = ownTenantId(input);
|
|
7304
|
+
const agent = ownAgentClaim(input);
|
|
7305
|
+
await this.client.execute(`INSERT INTO ${this.table}
|
|
7306
|
+
(kid, app, agent, tid, scopes, token_hash, issued_at, expires_at, created_by, revoked_at, revoked_reason)
|
|
7307
|
+
VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7, $8, $9, $10, $11)`, [
|
|
7308
|
+
input.kid,
|
|
7309
|
+
input.app,
|
|
7310
|
+
agent,
|
|
7311
|
+
tid === undefined || tid === null ? null : normalizeTenantId(tid),
|
|
7312
|
+
JSON.stringify(input.scopes),
|
|
7313
|
+
input.tokenHash,
|
|
7314
|
+
input.issuedAt.toISOString(),
|
|
7315
|
+
input.expiresAt ? input.expiresAt.toISOString() : null,
|
|
7316
|
+
input.createdBy ?? null,
|
|
7317
|
+
revokedAt,
|
|
7318
|
+
revokedReason
|
|
7319
|
+
]);
|
|
7320
|
+
}
|
|
7321
|
+
mintedInput(minted, createdBy) {
|
|
7322
|
+
const claims = minted.claims;
|
|
7323
|
+
return {
|
|
7324
|
+
kid: minted.kid,
|
|
7325
|
+
app: claims.app,
|
|
7326
|
+
agent: ownAgentClaim(claims),
|
|
7327
|
+
tid: ownTenantId(claims) ?? null,
|
|
7328
|
+
scopes: claims.scopes,
|
|
7329
|
+
tokenHash: minted.tokenHash,
|
|
7330
|
+
issuedAt: new Date(claims.iat * 1000),
|
|
7331
|
+
expiresAt: claims.exp === null ? null : new Date(claims.exp * 1000),
|
|
7332
|
+
createdBy: createdBy ?? null
|
|
7333
|
+
};
|
|
7334
|
+
}
|
|
7335
|
+
async insertMinted(minted, createdBy) {
|
|
7336
|
+
await this.insert(this.mintedInput(minted, createdBy));
|
|
7337
|
+
}
|
|
7338
|
+
async insertMintedPending(minted, createdBy, atMs = Date.now()) {
|
|
7339
|
+
await this.insertWithLifecycle(this.mintedInput(minted, createdBy), new Date(atMs).toISOString(), API_KEY_ISSUANCE_PENDING_REASON);
|
|
7340
|
+
}
|
|
7341
|
+
async activatePending(kid, tokenHash) {
|
|
7342
|
+
const row = await this.client.get(`UPDATE ${this.table}
|
|
7343
|
+
SET revoked_at = NULL, revoked_reason = NULL
|
|
7344
|
+
WHERE kid = $1
|
|
7345
|
+
AND revoked_at IS NOT NULL
|
|
7346
|
+
AND revoked_reason = $2
|
|
7347
|
+
AND token_hash = $3
|
|
7348
|
+
RETURNING kid`, [kid, API_KEY_ISSUANCE_PENDING_REASON, tokenHash]);
|
|
7349
|
+
if (row)
|
|
7350
|
+
return true;
|
|
7351
|
+
const active = await this.client.get(`SELECT kid FROM ${this.table}
|
|
7352
|
+
WHERE kid = $1
|
|
7353
|
+
AND token_hash = $2
|
|
7354
|
+
AND revoked_at IS NULL
|
|
7355
|
+
AND revoked_reason IS NULL`, [kid, tokenHash]);
|
|
7356
|
+
return active !== null;
|
|
7357
|
+
}
|
|
7358
|
+
async findByKid(kid) {
|
|
7359
|
+
const row = await this.client.get(`SELECT * FROM ${this.table} WHERE kid = $1`, [kid]);
|
|
7360
|
+
return row ? rowToRecord(row) : null;
|
|
7361
|
+
}
|
|
7362
|
+
async findByTokenHash(tokenHash) {
|
|
7363
|
+
const row = await this.client.get(`SELECT * FROM ${this.table} WHERE token_hash = $1`, [tokenHash]);
|
|
7364
|
+
return row ? rowToRecord(row) : null;
|
|
7365
|
+
}
|
|
7366
|
+
isRevoked = async (kid) => {
|
|
7367
|
+
const row = await this.client.get(`SELECT revoked_at FROM ${this.table} WHERE kid = $1`, [kid]);
|
|
7368
|
+
if (!row)
|
|
7369
|
+
return false;
|
|
7370
|
+
return row.revoked_at !== null && row.revoked_at !== undefined;
|
|
7371
|
+
};
|
|
7372
|
+
async status(kid, nowMs = Date.now()) {
|
|
7373
|
+
const record = await this.findByKid(kid);
|
|
7374
|
+
if (!record)
|
|
7375
|
+
return "unknown";
|
|
7376
|
+
if (record.revokedAt)
|
|
7377
|
+
return "revoked";
|
|
7378
|
+
if (record.expiresAt && new Date(record.expiresAt).getTime() <= nowMs)
|
|
7379
|
+
return "expired";
|
|
7380
|
+
return "active";
|
|
7381
|
+
}
|
|
7382
|
+
keyStatus = async (kid) => {
|
|
7383
|
+
return this.status(kid);
|
|
7384
|
+
};
|
|
7385
|
+
statusChecker() {
|
|
7386
|
+
return async (kid) => {
|
|
7387
|
+
const status = await this.status(kid);
|
|
7388
|
+
return status !== "active";
|
|
7389
|
+
};
|
|
7390
|
+
}
|
|
7391
|
+
async revoke(kid, reason, atMs = Date.now(), options = {}) {
|
|
7392
|
+
const params = [kid, new Date(atMs).toISOString(), reason ?? null];
|
|
7393
|
+
let scope = "";
|
|
7394
|
+
if (options.app !== undefined) {
|
|
7395
|
+
params.push(options.app);
|
|
7396
|
+
scope = ` AND app = $${params.length}`;
|
|
7397
|
+
}
|
|
7398
|
+
const row = await this.client.get(`UPDATE ${this.table}
|
|
7399
|
+
SET revoked_at = COALESCE(revoked_at, $2), revoked_reason = COALESCE(revoked_reason, $3)
|
|
7400
|
+
WHERE kid = $1${scope}
|
|
7401
|
+
RETURNING kid`, params);
|
|
7402
|
+
return row !== null;
|
|
7403
|
+
}
|
|
7404
|
+
async touchLastUsed(kid, atMs = Date.now()) {
|
|
7405
|
+
await this.client.execute(`UPDATE ${this.table} SET last_used_at = $2 WHERE kid = $1`, [
|
|
7406
|
+
kid,
|
|
7407
|
+
new Date(atMs).toISOString()
|
|
7408
|
+
]);
|
|
7409
|
+
}
|
|
7410
|
+
async list(options = {}) {
|
|
7411
|
+
const clauses = [];
|
|
7412
|
+
const params = [];
|
|
7413
|
+
if (options.app) {
|
|
7414
|
+
params.push(options.app);
|
|
7415
|
+
clauses.push(`app = $${params.length}`);
|
|
7416
|
+
}
|
|
7417
|
+
const tid = ownTenantId(options);
|
|
7418
|
+
if (tid !== undefined) {
|
|
7419
|
+
params.push(normalizeTenantId(tid));
|
|
7420
|
+
clauses.push(`tid = $${params.length}`);
|
|
7421
|
+
}
|
|
7422
|
+
if (!options.includeRevoked) {
|
|
7423
|
+
clauses.push("revoked_at IS NULL");
|
|
7424
|
+
}
|
|
7425
|
+
const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
|
|
7426
|
+
const rows = await this.client.many(`SELECT * FROM ${this.table} ${where} ORDER BY issued_at DESC`, params);
|
|
7427
|
+
return rows.map(rowToRecord);
|
|
7428
|
+
}
|
|
7429
|
+
async revokedKids() {
|
|
7430
|
+
const rows = await this.client.many(`SELECT kid FROM ${this.table} WHERE revoked_at IS NOT NULL`);
|
|
7431
|
+
return rows.map((row) => String(row.kid));
|
|
7432
|
+
}
|
|
7433
|
+
}
|
|
7434
|
+
function readHeader(source, name) {
|
|
7435
|
+
const lower = name.toLowerCase();
|
|
7436
|
+
if (typeof source === "function") {
|
|
7437
|
+
return source(name) ?? source(lower) ?? null;
|
|
7438
|
+
}
|
|
7439
|
+
if (typeof Headers !== "undefined" && source instanceof Headers) {
|
|
7440
|
+
return source.get(name);
|
|
7441
|
+
}
|
|
7442
|
+
const record = source;
|
|
7443
|
+
const value = record[name] ?? record[lower] ?? record[name.toUpperCase()];
|
|
7444
|
+
if (Array.isArray(value))
|
|
7445
|
+
return value[0] ?? null;
|
|
7446
|
+
return value ?? null;
|
|
7447
|
+
}
|
|
7448
|
+
function extractToken(source, headerName = "x-api-key", scheme = "Bearer") {
|
|
7449
|
+
const direct = readHeader(source, headerName);
|
|
7450
|
+
if (direct && direct.trim().length > 0)
|
|
7451
|
+
return direct.trim();
|
|
7452
|
+
const authz = readHeader(source, "authorization");
|
|
7453
|
+
if (authz) {
|
|
7454
|
+
const prefix = `${scheme} `;
|
|
7455
|
+
if (authz.toLowerCase().startsWith(prefix.toLowerCase())) {
|
|
7456
|
+
const token = authz.slice(prefix.length).trim();
|
|
7457
|
+
if (token.length > 0)
|
|
7458
|
+
return token;
|
|
7459
|
+
}
|
|
7460
|
+
}
|
|
7461
|
+
return null;
|
|
7462
|
+
}
|
|
7463
|
+
function ownOption2(bag, name) {
|
|
7464
|
+
return Object.hasOwn(bag, name) ? bag[name] : undefined;
|
|
7465
|
+
}
|
|
7466
|
+
function verifyApiKey(options) {
|
|
7467
|
+
const optionApp = ownOption2(options, "app");
|
|
7468
|
+
const optionSigningSecret = ownOption2(options, "signingSecret");
|
|
7469
|
+
const optionExpectedTid = ownOption2(options, "expectedTid");
|
|
7470
|
+
const optionRequiredScopes = ownOption2(options, "requiredScopes");
|
|
7471
|
+
const optionRequireTenant = ownOption2(options, "requireTenant");
|
|
7472
|
+
const optionLeewaySeconds = ownOption2(options, "leewaySeconds");
|
|
7473
|
+
const audit = ownOption2(options, "audit");
|
|
7474
|
+
const headerName = ownOption2(options, "headerName") ?? "x-api-key";
|
|
7475
|
+
const scheme = ownOption2(options, "scheme") ?? "Bearer";
|
|
7476
|
+
const clock = ownOption2(options, "nowMs") ?? (() => Date.now());
|
|
7477
|
+
if (!optionApp)
|
|
7478
|
+
throw new Error("verifyApiKey requires an 'app' slug.");
|
|
7479
|
+
if (!optionSigningSecret) {
|
|
7480
|
+
throw new Error("verifyApiKey requires a 'signingSecret'. Set it from HASNA_<APP>_API_SIGNING_KEY.");
|
|
7481
|
+
}
|
|
7482
|
+
if (optionExpectedTid !== undefined && !isValidTenantId(optionExpectedTid)) {
|
|
7483
|
+
throw new Error(`verifyApiKey received an invalid 'expectedTid': '${optionExpectedTid}'.`);
|
|
7484
|
+
}
|
|
7485
|
+
const app = optionApp;
|
|
7486
|
+
const signingSecret = optionSigningSecret;
|
|
7487
|
+
const ownKeyStatus = ownOption2(options, "keyStatus");
|
|
7488
|
+
const ownIsRevoked = ownOption2(options, "isRevoked");
|
|
7489
|
+
const allowUnregistered = ownOption2(options, "allowUnregisteredKeys") === true;
|
|
7490
|
+
if (ownKeyStatus && ownIsRevoked) {
|
|
7491
|
+
throw new Error("verifyApiKey received both 'keyStatus' and 'isRevoked'. Supply exactly one \u2014 " + "letting one silently win would hide which check is actually guarding the service. " + "Use 'keyStatus' (store.keyStatus); drop 'isRevoked'.");
|
|
7492
|
+
}
|
|
7493
|
+
if (!ownKeyStatus && !allowUnregistered) {
|
|
7494
|
+
throw new Error(ownIsRevoked ? "verifyApiKey was given only 'isRevoked', which cannot refuse a key this service has " + "no record of: it returns false both for an active key and for one that was never " + "registered, so an unregistered key is irrevocable. Wire 'keyStatus: store.keyStatus' " + "(or 'isRevoked: store.statusChecker()'), or set 'allowUnregisteredKeys: true' to " + "accept that risk explicitly." : "verifyApiKey requires a key-status hook. Without one this service performs NO " + "revocation check and cannot turn any of its keys off. Wire " + "'keyStatus: store.keyStatus', or set 'allowUnregisteredKeys: true' to declare that " + "this service intentionally cannot revoke keys.");
|
|
7495
|
+
}
|
|
7496
|
+
async function emit(event) {
|
|
7497
|
+
if (!audit)
|
|
7498
|
+
return;
|
|
7499
|
+
try {
|
|
7500
|
+
await audit(event);
|
|
7501
|
+
} catch {}
|
|
7502
|
+
}
|
|
7503
|
+
async function authenticate(headers, context = {}) {
|
|
7504
|
+
const method = ownOption2(context, "method") ?? null;
|
|
7505
|
+
const path = ownOption2(context, "path") ?? null;
|
|
7506
|
+
const requiredScopes = [
|
|
7507
|
+
...optionRequiredScopes ?? [],
|
|
7508
|
+
...ownOption2(context, "requiredScopes") ?? []
|
|
7509
|
+
];
|
|
7510
|
+
const at = new Date(clock()).toISOString();
|
|
7511
|
+
const perCallTid = ownOption2(context, "expectedTid");
|
|
7512
|
+
const expectedTid = perCallTid !== undefined ? perCallTid : optionExpectedTid;
|
|
7513
|
+
if (perCallTid !== undefined && optionExpectedTid !== undefined && !tenantIdsEqual(perCallTid, optionExpectedTid)) {
|
|
7514
|
+
await emit({ outcome: "deny", app, kid: null, tid: null, reason: "tenant_mismatch", scopesRequired: requiredScopes, method, path, status: 403, at });
|
|
7515
|
+
return {
|
|
7516
|
+
ok: false,
|
|
7517
|
+
status: 403,
|
|
7518
|
+
reason: "tenant_mismatch",
|
|
7519
|
+
message: "This route addresses a tenant other than the one this service is pinned to."
|
|
7520
|
+
};
|
|
7521
|
+
}
|
|
7522
|
+
const token = extractToken(headers, headerName, scheme);
|
|
7523
|
+
if (!token) {
|
|
7524
|
+
const decision = {
|
|
7525
|
+
ok: false,
|
|
7526
|
+
status: 401,
|
|
7527
|
+
reason: "missing_token",
|
|
7528
|
+
message: `Missing API key. Send it as '${headerName}: <key>' or 'Authorization: ${scheme} <key>'.`
|
|
7529
|
+
};
|
|
7530
|
+
await emit({ outcome: "deny", app, kid: null, tid: null, reason: "missing_token", scopesRequired: requiredScopes, method, path, status: 401, at });
|
|
7531
|
+
return decision;
|
|
7532
|
+
}
|
|
7533
|
+
const verified = verifyApiKeyToken(token, {
|
|
7534
|
+
signingSecret,
|
|
7535
|
+
expectedApp: app,
|
|
7536
|
+
nowMs: clock(),
|
|
7537
|
+
...optionLeewaySeconds !== undefined ? { leewaySeconds: optionLeewaySeconds } : {},
|
|
7538
|
+
...optionRequireTenant !== undefined ? { requireTenant: optionRequireTenant } : {},
|
|
7539
|
+
...expectedTid !== undefined ? { expectedTid } : {},
|
|
7540
|
+
requiredScopes
|
|
7541
|
+
});
|
|
7542
|
+
if (!verified.ok) {
|
|
7543
|
+
const status = verified.reason === "insufficient_scope" || verified.reason === "tenant_mismatch" || verified.reason === "tenant_required" ? 403 : 401;
|
|
7544
|
+
await emit({
|
|
7545
|
+
outcome: "deny",
|
|
7546
|
+
app,
|
|
7547
|
+
kid: ownOption2(verified, "kid") ?? null,
|
|
7548
|
+
tid: ownTenantId(verified) ?? null,
|
|
7549
|
+
...Object.hasOwn(verified, "agent") ? { agent: verified.agent } : {},
|
|
7550
|
+
reason: verified.reason,
|
|
7551
|
+
scopesRequired: requiredScopes,
|
|
7552
|
+
method,
|
|
7553
|
+
path,
|
|
7554
|
+
status,
|
|
7555
|
+
at
|
|
7556
|
+
});
|
|
7557
|
+
return { ok: false, status, reason: verified.reason, message: verified.message };
|
|
7558
|
+
}
|
|
7559
|
+
if (ownKeyStatus) {
|
|
7560
|
+
let status;
|
|
7561
|
+
try {
|
|
7562
|
+
status = await ownKeyStatus(verified.kid);
|
|
7563
|
+
} catch {
|
|
7564
|
+
await emit({ outcome: "deny", app, kid: verified.kid, tid: verified.tid, agent: verified.agent, reason: "status_unavailable", scopesRequired: requiredScopes, method, path, status: 503, at });
|
|
7565
|
+
return {
|
|
7566
|
+
ok: false,
|
|
7567
|
+
status: 503,
|
|
7568
|
+
reason: "status_unavailable",
|
|
7569
|
+
message: "Could not verify API key status. Try again shortly."
|
|
7570
|
+
};
|
|
7571
|
+
}
|
|
7572
|
+
if (status !== "active") {
|
|
7573
|
+
const known = status === "revoked" || status === "expired" || status === "unknown";
|
|
7574
|
+
if (!(status === "unknown" && allowUnregistered)) {
|
|
7575
|
+
const reason = status === "revoked" || status === "expired" ? status : "unknown_key";
|
|
7576
|
+
const message = reason === "unknown_key" ? known ? "API key is not registered with this service." : "API key status could not be recognized." : status === "expired" ? "API key has expired." : "API key has been revoked.";
|
|
7577
|
+
await emit({ outcome: "deny", app, kid: verified.kid, tid: verified.tid, agent: verified.agent, reason, scopesRequired: requiredScopes, method, path, status: 401, at });
|
|
7578
|
+
return { ok: false, status: 401, reason, message };
|
|
7579
|
+
}
|
|
7580
|
+
}
|
|
7581
|
+
} else if (ownIsRevoked) {
|
|
7582
|
+
let revoked;
|
|
7583
|
+
try {
|
|
7584
|
+
revoked = await ownIsRevoked(verified.kid);
|
|
7585
|
+
} catch {
|
|
7586
|
+
await emit({ outcome: "deny", app, kid: verified.kid, tid: verified.tid, agent: verified.agent, reason: "status_unavailable", scopesRequired: requiredScopes, method, path, status: 503, at });
|
|
7587
|
+
return {
|
|
7588
|
+
ok: false,
|
|
7589
|
+
status: 503,
|
|
7590
|
+
reason: "status_unavailable",
|
|
7591
|
+
message: "Could not verify API key status. Try again shortly."
|
|
7592
|
+
};
|
|
7593
|
+
}
|
|
7594
|
+
if (revoked) {
|
|
7595
|
+
await emit({ outcome: "deny", app, kid: verified.kid, tid: verified.tid, agent: verified.agent, reason: "revoked", scopesRequired: requiredScopes, method, path, status: 401, at });
|
|
7596
|
+
return { ok: false, status: 401, reason: "revoked", message: "API key has been revoked." };
|
|
7597
|
+
}
|
|
7598
|
+
}
|
|
7599
|
+
const principal = {
|
|
7600
|
+
kid: verified.kid,
|
|
7601
|
+
app: verified.app,
|
|
7602
|
+
scopes: verified.claims.scopes,
|
|
7603
|
+
agent: verified.agent,
|
|
7604
|
+
tid: verified.tid,
|
|
7605
|
+
claims: verified.claims
|
|
7606
|
+
};
|
|
7607
|
+
await emit({ outcome: "allow", app, kid: verified.kid, tid: verified.tid, agent: verified.agent, reason: null, scopesRequired: requiredScopes, method, path, status: 200, at });
|
|
7608
|
+
return { ok: true, status: 200, principal };
|
|
7609
|
+
}
|
|
7610
|
+
return { authenticate, app };
|
|
7611
|
+
}
|
|
7612
|
+
function envToken2(name) {
|
|
7613
|
+
return name.toUpperCase().replace(/-/g, "_");
|
|
7614
|
+
}
|
|
7615
|
+
var MAX_FLEET_TOKEN_TTL_SECONDS = 24 * 60 * 60;
|
|
7616
|
+
function signingSecretEnvKeys(app) {
|
|
7617
|
+
return [`HASNA_${envToken2(app)}_API_SIGNING_KEY`, "HASNA_API_SIGNING_KEY"];
|
|
7618
|
+
}
|
|
7619
|
+
|
|
7620
|
+
class SigningSecretError extends Error {
|
|
7621
|
+
attempted;
|
|
7622
|
+
constructor(message, attempted) {
|
|
7623
|
+
super(message);
|
|
7624
|
+
this.name = "SigningSecretError";
|
|
7625
|
+
this.attempted = Object.freeze([...attempted]);
|
|
7626
|
+
}
|
|
7627
|
+
}
|
|
7628
|
+
function signingSecretHasSurroundingWhitespace(value) {
|
|
7629
|
+
return value !== value.trim();
|
|
7630
|
+
}
|
|
7631
|
+
function resolveSigningSecret(app, env, options = {}) {
|
|
7632
|
+
const keys = options.envName ? [options.envName] : signingSecretEnvKeys(app);
|
|
7633
|
+
for (const key of keys) {
|
|
7634
|
+
const raw = env[key];
|
|
7635
|
+
if (raw === undefined)
|
|
7636
|
+
continue;
|
|
7637
|
+
const value = raw.trim();
|
|
7638
|
+
if (!value)
|
|
7639
|
+
continue;
|
|
7640
|
+
return { value, source: key, trimmed: signingSecretHasSurroundingWhitespace(raw) };
|
|
7641
|
+
}
|
|
7642
|
+
throw new SigningSecretError(`No signing secret found. Set ${keys.join(" or ")} (openssl rand -hex 32).`, keys);
|
|
7643
|
+
}
|
|
7644
|
+
|
|
7645
|
+
// src/registry-auth.ts
|
|
7646
|
+
function createRegistryVerifier(signingSecret, keyStatus) {
|
|
7647
|
+
return verifyApiKey({ app: "hooks", signingSecret, keyStatus });
|
|
7648
|
+
}
|
|
7649
|
+
function hasRegistrySigningConfiguration() {
|
|
7650
|
+
return process.env.HASNA_HOOKS_API_SIGNING_KEY !== undefined || process.env.HASNA_API_SIGNING_KEY !== undefined;
|
|
7651
|
+
}
|
|
7652
|
+
var keyStore;
|
|
7653
|
+
function registryKeyStatus() {
|
|
7654
|
+
if (!keyStore) {
|
|
7655
|
+
const url = getStorageDatabaseUrl();
|
|
7656
|
+
if (!url)
|
|
7657
|
+
throw new RegistryError(503, "REGISTRY_DATABASE_REQUIRED");
|
|
7658
|
+
const db = new PgAdapterAsync(url, { timeoutMs: 5000 });
|
|
7659
|
+
const client = {
|
|
7660
|
+
many: async (sql, params) => await db.all(sql, ...params ?? []),
|
|
7661
|
+
get: async (sql, params) => (await db.all(sql, ...params ?? []))[0] ?? null,
|
|
7662
|
+
execute: async () => {
|
|
7663
|
+
throw new Error("REGISTRY_AUTH_READ_ONLY");
|
|
7664
|
+
}
|
|
7665
|
+
};
|
|
7666
|
+
keyStore = new ApiKeyStore(client);
|
|
7667
|
+
}
|
|
7668
|
+
return keyStore.keyStatus;
|
|
7669
|
+
}
|
|
7670
|
+
async function authenticateRegistryRequest(request, verifier) {
|
|
7671
|
+
const auth = verifier ?? createRegistryVerifier(resolveSigningSecret("hooks", process.env, process.env.HASNA_HOOKS_API_SIGNING_KEY !== undefined ? { envName: "HASNA_HOOKS_API_SIGNING_KEY" } : {}).value, registryKeyStatus());
|
|
7672
|
+
const decision = await auth.authenticate(request.headers, {
|
|
7673
|
+
method: request.method,
|
|
7674
|
+
path: new URL(request.url).pathname,
|
|
7675
|
+
requiredScopes: [request.method === "GET" ? "hooks:read" : "hooks:write"]
|
|
7676
|
+
});
|
|
7677
|
+
if (!decision.ok)
|
|
7678
|
+
throw new RegistryError(decision.status, "REGISTRY_AUTH_" + decision.reason.toUpperCase());
|
|
7679
|
+
}
|
|
7680
|
+
|
|
7681
|
+
// src/registry-http.ts
|
|
7682
|
+
var serverRegistry;
|
|
7683
|
+
function configuredRegistry() {
|
|
7684
|
+
if (serverRegistry)
|
|
7685
|
+
return serverRegistry;
|
|
7686
|
+
if (getStorageBackend() !== "postgresql")
|
|
7687
|
+
throw new RegistryError(503, "REGISTRY_DATABASE_REQUIRED");
|
|
7688
|
+
const url = getStorageDatabaseUrl();
|
|
7689
|
+
if (!url)
|
|
7690
|
+
throw new RegistryError(503, "REGISTRY_DATABASE_REQUIRED");
|
|
7691
|
+
serverRegistry = new HostedRegistry(new PgRegistryStore(new PgAdapterAsync(url, { timeoutMs: 5000 })));
|
|
7692
|
+
return serverRegistry;
|
|
7693
|
+
}
|
|
7694
|
+
async function registryReady() {
|
|
7695
|
+
try {
|
|
7696
|
+
await configuredRegistry().ready();
|
|
7697
|
+
return true;
|
|
7698
|
+
} catch {
|
|
7699
|
+
return false;
|
|
7700
|
+
}
|
|
7701
|
+
}
|
|
7702
|
+
function json(body, status = 200, headers = {}) {
|
|
7703
|
+
return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", "cache-control": "no-store", ...headers } });
|
|
7704
|
+
}
|
|
7705
|
+
async function boundedJson(request) {
|
|
7706
|
+
if (!request.body)
|
|
7707
|
+
throw new RegistryError(400, "REGISTRY_BODY_REQUIRED");
|
|
7708
|
+
const reader = request.body.getReader(), chunks = [];
|
|
7709
|
+
let length = 0;
|
|
7710
|
+
for (;; ) {
|
|
7711
|
+
const next = await reader.read();
|
|
7712
|
+
if (next.done)
|
|
7713
|
+
break;
|
|
7714
|
+
length += next.value.byteLength;
|
|
7715
|
+
if (length > REGISTRY_MAX_BYTES) {
|
|
7716
|
+
await reader.cancel();
|
|
7717
|
+
throw new RegistryError(413, "REGISTRY_BODY_TOO_LARGE");
|
|
7718
|
+
}
|
|
7719
|
+
chunks.push(next.value);
|
|
7720
|
+
}
|
|
7721
|
+
try {
|
|
7722
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
7723
|
+
} catch {
|
|
7724
|
+
throw new RegistryError(400, "REGISTRY_JSON_INVALID");
|
|
7725
|
+
}
|
|
7726
|
+
}
|
|
7727
|
+
async function handleRegistryRequest(request, key, registry) {
|
|
7728
|
+
try {
|
|
7729
|
+
if (hasRegistrySigningConfiguration())
|
|
7730
|
+
await authenticateRegistryRequest(request);
|
|
7731
|
+
else {
|
|
7732
|
+
if (!isHooksLocalOptIn())
|
|
7733
|
+
throw new RegistryError(503, "REGISTRY_SIGNING_CONFIGURATION_REQUIRED");
|
|
7734
|
+
if (!key)
|
|
7735
|
+
throw new RegistryError(503, "REGISTRY_AUTH_NOT_CONFIGURED");
|
|
7736
|
+
const bearer = request.headers.get("authorization") ?? "";
|
|
7737
|
+
const supplied = bearer.startsWith("Bearer ") ? bearer.slice(7) : request.headers.get("x-api-key") ?? "";
|
|
7738
|
+
if (!secureEqual(supplied, key))
|
|
7739
|
+
throw new RegistryError(401, "REGISTRY_UNAUTHORIZED");
|
|
7740
|
+
}
|
|
7741
|
+
const url = new URL(request.url), path = url.pathname.replace(/^\/api\/v1(?=\/|$)/, "/v1");
|
|
7742
|
+
const owner = registry ?? configuredRegistry();
|
|
7743
|
+
if (path === "/v1/catalog" && request.method === "GET")
|
|
7744
|
+
return json(await owner.catalog());
|
|
7745
|
+
if (path === "/v1/lock" && request.method === "GET")
|
|
7746
|
+
return json(await owner.selection(url.searchParams.get("profile") ?? "fleet"));
|
|
7747
|
+
if (path === "/v1/hooks" && request.method === "PUT")
|
|
7748
|
+
return json(await owner.publish(await boundedJson(request)));
|
|
7749
|
+
const artifact = /^\/v1\/hooks\/([^/]+)\/([^/]+)$/.exec(path);
|
|
7750
|
+
if (artifact && request.method === "GET") {
|
|
7751
|
+
const { body, row, format, portable } = await owner.artifactWire(decodeURIComponent(artifact[1]), decodeURIComponent(artifact[2]));
|
|
7752
|
+
return new Response(body, { status: 200, headers: { "content-type": "application/json", "cache-control": "no-store", "x-hook-sha256": row.script_sha256, "x-hook-bundle-sha256": row.bundle_sha256, "x-hook-artifact-format": format, "x-hook-portable": String(portable) } });
|
|
7753
|
+
}
|
|
7754
|
+
const selection = /^\/v1\/selections\/([^/]+)$/.exec(path);
|
|
7755
|
+
if (selection) {
|
|
7756
|
+
const profile = decodeURIComponent(selection[1]);
|
|
7757
|
+
if (request.method === "GET")
|
|
7758
|
+
return json(await owner.selection(profile));
|
|
7759
|
+
if (request.method === "PUT")
|
|
7760
|
+
return json(await owner.select(profile, await boundedJson(request)));
|
|
7761
|
+
}
|
|
7762
|
+
return json({ error: "REGISTRY_ROUTE_NOT_FOUND" }, 404);
|
|
7763
|
+
} catch (error) {
|
|
7764
|
+
if (error instanceof RegistryError)
|
|
7765
|
+
return json({ error: error.code }, error.status);
|
|
7766
|
+
if (error instanceof URIError)
|
|
7767
|
+
return json({ error: "REGISTRY_PATH_INVALID" }, 400);
|
|
7768
|
+
return json({ error: "REGISTRY_STORAGE_UNAVAILABLE" }, 503);
|
|
7769
|
+
}
|
|
7770
|
+
}
|
|
7771
|
+
|
|
6494
7772
|
// src/serve.ts
|
|
6495
7773
|
var DEFAULT_SERVE_PORT = 39428;
|
|
6496
7774
|
var SERVE_HOST = "127.0.0.1";
|
|
6497
7775
|
var SERVE_SERVICE_NAME = "hooks-registry";
|
|
6498
7776
|
function packageVersion() {
|
|
6499
7777
|
try {
|
|
6500
|
-
const pkgPath =
|
|
7778
|
+
const pkgPath = join9(dirname4(fileURLToPath5(import.meta.url)), "..", "package.json");
|
|
6501
7779
|
return JSON.parse(readFileSync5(pkgPath, "utf-8")).version || "0.0.0";
|
|
6502
7780
|
} catch {
|
|
6503
7781
|
return "0.0.0";
|
|
@@ -6551,7 +7829,8 @@ async function artifactFor(name, version) {
|
|
|
6551
7829
|
script: custom2 ? custom2.manifest.script : `src/hook.ts`,
|
|
6552
7830
|
script_kind: custom2?.manifest.script_kind,
|
|
6553
7831
|
args: custom2?.manifest.args,
|
|
6554
|
-
timeout_ms: custom2?.manifest.timeout_ms
|
|
7832
|
+
timeout_ms: custom2?.manifest.timeout_ms,
|
|
7833
|
+
nativeTargetDispatch: custom2?.manifest.nativeTargetDispatch ?? resolved.meta.nativeTargetDispatch
|
|
6555
7834
|
};
|
|
6556
7835
|
const script = await Bun.file(resolved.scriptPath).text();
|
|
6557
7836
|
return { manifest, script };
|
|
@@ -6564,7 +7843,7 @@ function authorized(req, apiKey) {
|
|
|
6564
7843
|
return secureEqual(header.slice("Bearer ".length), apiKey);
|
|
6565
7844
|
return secureEqual(req.headers.get("x-api-key") ?? "", apiKey);
|
|
6566
7845
|
}
|
|
6567
|
-
function
|
|
7846
|
+
function json2(body, status = 200, headers = {}) {
|
|
6568
7847
|
return new Response(JSON.stringify(body), {
|
|
6569
7848
|
status,
|
|
6570
7849
|
headers: { "content-type": "application/json", ...headers }
|
|
@@ -6572,25 +7851,38 @@ function json(body, status = 200, headers = {}) {
|
|
|
6572
7851
|
}
|
|
6573
7852
|
function handleServeRequest(req, apiKey) {
|
|
6574
7853
|
const url = new URL(req.url);
|
|
7854
|
+
let localSelected = false;
|
|
7855
|
+
try {
|
|
7856
|
+
localSelected = !getStorageDatabaseUrl() && !hasRegistrySigningConfiguration() && getStorageBackend() === "sqlite" && selectsHooksLocalStore();
|
|
7857
|
+
} catch {}
|
|
7858
|
+
if (url.pathname.startsWith("/v1/") && localSelected) {
|
|
7859
|
+
url.pathname = "/api" + url.pathname;
|
|
7860
|
+
return handleServeRequest(new Request(url, req), apiKey);
|
|
7861
|
+
}
|
|
7862
|
+
if (url.pathname.startsWith("/v1/") || url.pathname.startsWith("/api/v1/") && !localSelected) {
|
|
7863
|
+
return handleRegistryRequest(req, apiKey);
|
|
7864
|
+
}
|
|
6575
7865
|
if (url.pathname === "/health" && req.method === "GET") {
|
|
6576
|
-
return Promise.resolve(
|
|
7866
|
+
return Promise.resolve(json2({ status: "ok", name: SERVE_SERVICE_NAME }));
|
|
6577
7867
|
}
|
|
6578
7868
|
if (url.pathname === "/ready" && req.method === "GET") {
|
|
7869
|
+
if (!localSelected)
|
|
7870
|
+
return registryReady().then((ready) => json2({ status: ready ? "ready" : "not-ready", name: SERVE_SERVICE_NAME }, ready ? 200 : 503));
|
|
6579
7871
|
try {
|
|
6580
7872
|
readLock();
|
|
6581
|
-
return Promise.resolve(
|
|
7873
|
+
return Promise.resolve(json2({ status: "ready", name: SERVE_SERVICE_NAME }));
|
|
6582
7874
|
} catch {
|
|
6583
|
-
return Promise.resolve(
|
|
7875
|
+
return Promise.resolve(json2({ status: "not-ready", name: SERVE_SERVICE_NAME }, 503));
|
|
6584
7876
|
}
|
|
6585
7877
|
}
|
|
6586
7878
|
if (url.pathname === "/version" && req.method === "GET") {
|
|
6587
|
-
return Promise.resolve(
|
|
7879
|
+
return Promise.resolve(json2({ version: packageVersion() }));
|
|
6588
7880
|
}
|
|
6589
7881
|
if (url.pathname === "/openapi.json" && req.method === "GET") {
|
|
6590
|
-
return Promise.resolve(
|
|
7882
|
+
return Promise.resolve(json2(buildOpenApiDocument(packageVersion())));
|
|
6591
7883
|
}
|
|
6592
7884
|
if (url.pathname === "/api/v1/catalog" && req.method === "GET") {
|
|
6593
|
-
return buildCatalog().then((catalog) =>
|
|
7885
|
+
return buildCatalog().then((catalog) => json2({ hooks: catalog }));
|
|
6594
7886
|
}
|
|
6595
7887
|
if (url.pathname === "/api/v1/lock" && req.method === "GET") {
|
|
6596
7888
|
return buildCatalog().then((catalog) => {
|
|
@@ -6602,7 +7894,7 @@ function handleServeRequest(req, apiKey) {
|
|
|
6602
7894
|
for (const [name, pin] of Object.entries(lock.hooks)) {
|
|
6603
7895
|
hooks[name] = { ...pin, versions: byVersion[name] ?? [pin.version] };
|
|
6604
7896
|
}
|
|
6605
|
-
return
|
|
7897
|
+
return json2({ hooks });
|
|
6606
7898
|
});
|
|
6607
7899
|
}
|
|
6608
7900
|
const artifactMatch = /^\/api\/v1\/hooks\/([\w-]+)\/([0-9A-Za-z.%+_-]+)$/.exec(url.pathname);
|
|
@@ -6614,37 +7906,37 @@ function handleServeRequest(req, apiKey) {
|
|
|
6614
7906
|
name = decodeURIComponent(rawName);
|
|
6615
7907
|
version = decodeURIComponent(rawVersion);
|
|
6616
7908
|
} catch {
|
|
6617
|
-
return Promise.resolve(
|
|
7909
|
+
return Promise.resolve(json2({ error: "invalid URL encoding" }, 400));
|
|
6618
7910
|
}
|
|
6619
7911
|
if (!SEMVER_PATTERN.test(version)) {
|
|
6620
|
-
return Promise.resolve(
|
|
7912
|
+
return Promise.resolve(json2({ error: `invalid semver version '${version}'` }, 400));
|
|
6621
7913
|
}
|
|
6622
7914
|
return artifactFor(name, version).then(async (artifact) => {
|
|
6623
7915
|
if (!artifact)
|
|
6624
|
-
return
|
|
7916
|
+
return json2({ error: `Hook '${name}@${version}' not found locally` }, 404);
|
|
6625
7917
|
const resolved = resolveHook(name);
|
|
6626
7918
|
const sha = resolved ? await sha256File(resolved.scriptPath) : artifact.manifest.name;
|
|
6627
|
-
return
|
|
7919
|
+
return json2(artifact, 200, { "x-hook-sha256": sha });
|
|
6628
7920
|
});
|
|
6629
7921
|
}
|
|
6630
7922
|
if (url.pathname === "/api/v1/hooks" && req.method === "PUT") {
|
|
6631
7923
|
if (!authorized(req, apiKey)) {
|
|
6632
|
-
return Promise.resolve(
|
|
7924
|
+
return Promise.resolve(json2({ error: "unauthorized: valid API key required to publish" }, 401));
|
|
6633
7925
|
}
|
|
6634
7926
|
return req.json().then((body) => {
|
|
6635
7927
|
const name = body.name ?? "";
|
|
6636
7928
|
const version = body.version ?? "";
|
|
6637
7929
|
const resolved = resolveHook(name);
|
|
6638
7930
|
if (!resolved)
|
|
6639
|
-
return
|
|
7931
|
+
return json2({ error: `Hook '${name}' not found in local store` }, 404);
|
|
6640
7932
|
if (version && version !== resolved.version) {
|
|
6641
|
-
return
|
|
7933
|
+
return json2({ error: `Version mismatch: local '${name}' is ${resolved.version}, requested ${version}` }, 409);
|
|
6642
7934
|
}
|
|
6643
7935
|
const check = retrustHook(name, resolved.scriptPath, resolved.version, "serve");
|
|
6644
|
-
return
|
|
6645
|
-
}, () =>
|
|
7936
|
+
return json2({ ok: true, hook: { name, version: resolved.version, sha256: check.actual } });
|
|
7937
|
+
}, () => json2({ error: "invalid JSON body" }, 400));
|
|
6646
7938
|
}
|
|
6647
|
-
return Promise.resolve(
|
|
7939
|
+
return Promise.resolve(json2({ error: "Not Found" }, 404));
|
|
6648
7940
|
}
|
|
6649
7941
|
function resolveServeOptions(options) {
|
|
6650
7942
|
const envPort = process.env.PORT?.trim();
|