@leitwerk-dev/git-ssh 0.1.9 → 0.2.1

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 CHANGED
@@ -1,3 +1,13 @@
1
1
  # Git SSH
2
2
 
3
3
  Provides pinned, non-interactive Git-over-SSH credential profiles to repository processes. Configure profiles under `extensions.git-ssh.credentials`. Private keys and `known_hosts` are delivered only in authenticated `worker.start` IPC; ambient SSH configuration and agents are not used.
4
+
5
+ Dependent server extensions can use `gitSshIntegration.preflight()` before launch. The preflight verifies the repository's base ref with `git ls-remote`. When write access is required, it fetches that ref and performs a dry-run push to a unique probe branch. The check uses only the selected profile, does not create the probe branch, and never returns credential material.
6
+
7
+ ## API support
8
+
9
+ The following exported declarations are `@public`:
10
+
11
+ - `@leitwerk-dev/git-ssh`: `GitSshIntegration`, `default`, `gitSshIntegration`.
12
+
13
+ See the [SDK compatibility policy](../../docs/process-sdk.md#api-compatibility) for member classifications and support guarantees.
@@ -0,0 +1,18 @@
1
+ import type { GitSshCredentialMaterial } from "@leitwerk-dev/process-sdk";
2
+ type GitSshPreflightResult = {
3
+ ok: true;
4
+ } | {
5
+ ok: false;
6
+ access: "read" | "write";
7
+ detail: string;
8
+ };
9
+ /** @internal */
10
+ export declare function preflightGitSshAccess(input: {
11
+ repoLocator: string;
12
+ baseBranch: string;
13
+ requireWrite: boolean;
14
+ }, material: GitSshCredentialMaterial, gitBinary?: string): Promise<GitSshPreflightResult>;
15
+ /** @internal */
16
+ export declare function parseProfiles(raw: unknown): Map<string, GitSshCredentialMaterial>;
17
+ export {};
18
+ //# sourceMappingURL=git-ssh-internal.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"git-ssh-internal.d.ts","sourceRoot":"","sources":["../src/git-ssh-internal.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AAI1E,KAAK,qBAAqB,GACvB;IACA,EAAE,EAAE,IAAI,CAAC;CACR,GACD;IACA,EAAE,EAAE,KAAK,CAAC;IACV,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC;IACzB,MAAM,EAAE,MAAM,CAAC;CACd,CAAC;AAgBL,gBAAgB;AAChB,wBAAsB,qBAAqB,CAC1C,KAAK,EAAE;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,OAAO,CAAA;CAAE,EACzE,QAAQ,EAAE,wBAAwB,EAClC,SAAS,SAAQ,GACf,OAAO,CAAC,qBAAqB,CAAC,CAoDhC;AAED,gBAAgB;AAChB,wBAAgB,aAAa,CAAC,GAAG,EAAE,OAAO,GAAG,GAAG,CAAC,MAAM,EAAE,wBAAwB,CAAC,CAiCjF"}
package/dist/index.d.ts CHANGED
@@ -1,10 +1,37 @@
1
- import { type GitSshCredentialMaterial, type LeitwerkExtensionModule } from "@leitwerk-dev/process-sdk";
2
- export declare const manifest: {
3
- readonly id: "git-ssh";
4
- readonly version: "0.1.0";
1
+ import { type LeitwerkExtensionModule } from "@leitwerk-dev/process-sdk";
2
+ /** @public */
3
+ interface GitSshAuthorizationPreflightInput {
4
+ /** @public */
5
+ credentialRef: string;
6
+ /** @public */
7
+ repoLocator: string;
8
+ /** @public */
9
+ baseBranch: string;
10
+ /** @public */
11
+ requireWrite: boolean;
12
+ }
13
+ /** @public */
14
+ type GitSshAuthorizationPreflightResult = {
15
+ /** @public */
16
+ ok: true;
17
+ } | {
18
+ /** @public */
19
+ ok: false;
20
+ /** @public */
21
+ access: "read" | "write";
22
+ /** @public */
23
+ detail: string;
5
24
  };
6
- declare function parseProfiles(raw: unknown): Map<string, GitSshCredentialMaterial>;
25
+ /** @public */
26
+ export interface GitSshIntegration {
27
+ /** @public */
28
+ profiles(): readonly string[];
29
+ /** @public */
30
+ preflight(input: GitSshAuthorizationPreflightInput): Promise<GitSshAuthorizationPreflightResult>;
31
+ }
32
+ /** @public */
33
+ export declare const gitSshIntegration: import("@leitwerk-dev/process-sdk").CapabilityToken<GitSshIntegration>;
34
+ /** @public */
7
35
  declare const extension: LeitwerkExtensionModule;
8
- export { parseProfiles };
9
36
  export default extension;
10
37
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,KAAK,wBAAwB,EAC7B,KAAK,uBAAuB,EAC5B,MAAM,2BAA2B,CAAC;AAEnC,eAAO,MAAM,QAAQ;;;CAA+C,CAAC;AAErE,iBAAS,aAAa,CAAC,GAAG,EAAE,OAAO,GAAG,GAAG,CAAC,MAAM,EAAE,wBAAwB,CAAC,CAiC1E;AAED,QAAA,MAAM,SAAS,EAAE,uBAWhB,CAAC;AAEF,OAAO,EAAE,aAAa,EAAE,CAAC;AACzB,eAAe,SAAS,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,KAAK,uBAAuB,EAC5B,MAAM,2BAA2B,CAAC;AAWnC,cAAc;AACd,UAAU,iCAAiC;IAC1C,cAAc;IACd,aAAa,EAAE,MAAM,CAAC;IACtB,cAAc;IACd,WAAW,EAAE,MAAM,CAAC;IACpB,cAAc;IACd,UAAU,EAAE,MAAM,CAAC;IACnB,cAAc;IACd,YAAY,EAAE,OAAO,CAAC;CACtB;AAED,cAAc;AACd,KAAK,kCAAkC,GACpC;IACA,cAAc;IACd,EAAE,EAAE,IAAI,CAAC;CACR,GACD;IACA,cAAc;IACd,EAAE,EAAE,KAAK,CAAC;IACV,cAAc;IACd,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC;IACzB,cAAc;IACd,MAAM,EAAE,MAAM,CAAC;CACd,CAAC;AAEL,cAAc;AACd,MAAM,WAAW,iBAAiB;IACjC,cAAc;IACd,QAAQ,IAAI,SAAS,MAAM,EAAE,CAAC;IAC9B,cAAc;IACd,SAAS,CAAC,KAAK,EAAE,iCAAiC,GAAG,OAAO,CAAC,kCAAkC,CAAC,CAAC;CACjG;AAED,cAAc;AACd,eAAO,MAAM,iBAAiB,wEAE7B,CAAC;AAEF,cAAc;AACd,QAAA,MAAM,SAAS,EAAE,uBAyBhB,CAAC;AAEF,eAAe,SAAS,CAAC"}
package/dist/index.js CHANGED
@@ -1,47 +1,143 @@
1
- import { coreHostCapabilities, } from "@leitwerk-dev/process-sdk";
2
- export const manifest = { id: "git-ssh", version: "0.1.0" };
3
- function parseProfiles(raw) {
4
- const root = raw && typeof raw === "object" ? raw : {};
5
- const credentials = root.credentials && typeof root.credentials === "object"
6
- ? root.credentials
7
- : {};
8
- const profiles = new Map();
9
- for (const [ref, value] of Object.entries(credentials)) {
10
- const profile = value && typeof value === "object" ? value : {};
11
- const privateKey = typeof profile.private_key === "string" ? profile.private_key.trim() : "";
12
- const knownHosts = typeof profile.known_hosts === "string" ? profile.known_hosts.trim() : "";
13
- if (!privateKey.includes("BEGIN OPENSSH PRIVATE KEY"))
14
- throw new Error(`Invalid git_ssh credential '${ref}': an OpenSSH private key is required`);
15
- const encodedBody = privateKey
16
- .split(/\r?\n/)
17
- .filter((line) => !line.startsWith("-----"))
18
- .join("");
19
- const decodedHeader = Buffer.from(encodedBody, "base64").subarray(0, 96).toString("latin1");
20
- if (/ENCRYPTED/.test(privateKey) || decodedHeader.includes("bcrypt"))
21
- throw new Error(`Invalid git_ssh credential '${ref}': encrypted keys requiring a passphrase are unsupported`);
22
- const hostLines = knownHosts
23
- .split(/\r?\n/)
24
- .map((line) => line.trim())
25
- .filter((line) => line && !line.startsWith("#"));
26
- if (hostLines.length === 0 || hostLines.some((line) => line.split(/\s+/).length < 3))
27
- throw new Error(`Invalid git_ssh credential '${ref}': pinned known_hosts entries are required`);
28
- profiles.set(ref, { privateKey, knownHosts });
1
+ // src/index.ts
2
+ import {
3
+ coreHostCapabilities,
4
+ createCapabilityToken
5
+ } from "@leitwerk-dev/process-sdk";
6
+
7
+ // src/git-ssh-internal.ts
8
+ import { execFile } from "child_process";
9
+ import { mkdtemp, rm, writeFile } from "fs/promises";
10
+ import { tmpdir } from "os";
11
+ import { join } from "path";
12
+ import { promisify } from "util";
13
+ var execFileAsync = promisify(execFile);
14
+ function gitFailureDetail(error) {
15
+ if (!error || typeof error !== "object") return "Git SSH access check failed";
16
+ const value = error;
17
+ const output = typeof value.stderr === "string" && value.stderr.trim() ? value.stderr : typeof value.stdout === "string" && value.stdout.trim() ? value.stdout : typeof value.message === "string" ? value.message : "Git SSH access check failed";
18
+ return output.replace(/\s+/g, " ").trim().slice(0, 500);
19
+ }
20
+ async function preflightGitSshAccess(input, material, gitBinary = "git") {
21
+ const directory = await mkdtemp(join(tmpdir(), "leitwerk-git-ssh-preflight-"));
22
+ try {
23
+ const keyPath = join(directory, "identity");
24
+ const knownHostsPath = join(directory, "known_hosts");
25
+ const sshPath = join(directory, "ssh");
26
+ await Promise.all([
27
+ writeFile(keyPath, `${material.privateKey.trim()}
28
+ `, { mode: 384 }),
29
+ writeFile(knownHostsPath, `${material.knownHosts.trim()}
30
+ `, { mode: 384 }),
31
+ writeFile(
32
+ sshPath,
33
+ `#!/bin/sh
34
+ exec ssh -F /dev/null -i "${keyPath}" -o IdentitiesOnly=yes -o UserKnownHostsFile="${knownHostsPath}" -o StrictHostKeyChecking=yes -o BatchMode=yes "$@"
35
+ `,
36
+ { mode: 448 }
37
+ )
38
+ ]);
39
+ const env = {
40
+ ...process.env,
41
+ GIT_SSH: sshPath,
42
+ // This also overrides ambient core.sshCommand, which takes precedence over GIT_SSH.
43
+ GIT_SSH_COMMAND: `'${sshPath.replaceAll("'", "'\\''")}'`,
44
+ SSH_AUTH_SOCK: ""
45
+ };
46
+ const ref = `refs/heads/${input.baseBranch}`;
47
+ try {
48
+ await execFileAsync(gitBinary, ["ls-remote", "--exit-code", input.repoLocator, ref], {
49
+ env
50
+ });
51
+ } catch (error) {
52
+ return { ok: false, access: "read", detail: gitFailureDetail(error) };
29
53
  }
30
- return profiles;
54
+ if (!input.requireWrite) return { ok: true };
55
+ try {
56
+ await execFileAsync(gitBinary, ["init", "--quiet", directory], { env });
57
+ await execFileAsync(
58
+ gitBinary,
59
+ ["-C", directory, "fetch", "--quiet", "--depth=1", input.repoLocator, ref],
60
+ { env }
61
+ );
62
+ const probeBranch = `refs/heads/leitwerk/preflight-${process.pid}-${Date.now()}`;
63
+ await execFileAsync(
64
+ gitBinary,
65
+ ["-C", directory, "push", "--dry-run", input.repoLocator, `FETCH_HEAD:${probeBranch}`],
66
+ { env }
67
+ );
68
+ return { ok: true };
69
+ } catch (error) {
70
+ return { ok: false, access: "write", detail: gitFailureDetail(error) };
71
+ }
72
+ } finally {
73
+ await rm(directory, { recursive: true, force: true });
74
+ }
31
75
  }
32
- const extension = {
33
- manifest,
34
- setupServer(api, config) {
35
- const deps = api.get(coreHostCapabilities.serverSetup);
36
- if (!deps || Array.isArray(deps))
37
- return;
38
- const profiles = parseProfiles(config);
39
- deps.repositoryCredentials.register({
40
- kind: "git_ssh",
41
- resolve: (ref) => profiles.get(ref) ?? null,
42
- });
43
- },
76
+ function parseProfiles(raw) {
77
+ const root = raw && typeof raw === "object" ? raw : {};
78
+ const credentials = root.credentials && typeof root.credentials === "object" ? root.credentials : {};
79
+ const profiles = /* @__PURE__ */ new Map();
80
+ for (const [ref, value] of Object.entries(credentials)) {
81
+ const profile = value && typeof value === "object" ? value : {};
82
+ const privateKey = typeof profile.private_key === "string" ? profile.private_key.trim() : "";
83
+ const knownHosts = typeof profile.known_hosts === "string" ? profile.known_hosts.trim() : "";
84
+ if (!privateKey.includes("BEGIN OPENSSH PRIVATE KEY"))
85
+ throw new Error(`Invalid git_ssh credential '${ref}': an OpenSSH private key is required`);
86
+ const encodedBody = privateKey.split(/\r?\n/).filter((line) => !line.startsWith("-----")).join("");
87
+ const decodedHeader = Buffer.from(encodedBody, "base64").subarray(0, 96).toString("latin1");
88
+ if (/ENCRYPTED/.test(privateKey) || decodedHeader.includes("bcrypt"))
89
+ throw new Error(
90
+ `Invalid git_ssh credential '${ref}': encrypted keys requiring a passphrase are unsupported`
91
+ );
92
+ const hostLines = knownHosts.split(/\r?\n/).map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
93
+ if (hostLines.length === 0 || hostLines.some((line) => line.split(/\s+/).length < 3))
94
+ throw new Error(
95
+ `Invalid git_ssh credential '${ref}': pinned known_hosts entries are required`
96
+ );
97
+ profiles.set(ref, { privateKey, knownHosts });
98
+ }
99
+ return profiles;
100
+ }
101
+
102
+ // src/index.ts
103
+ var manifest = {
104
+ /** @internal */
105
+ id: "git-ssh",
106
+ /** @internal */
107
+ version: "0.1.0"
108
+ };
109
+ var gitSshIntegration = createCapabilityToken(
110
+ "@leitwerk-dev/git-ssh.integration"
111
+ );
112
+ var extension = {
113
+ manifest,
114
+ setupServer(api, config) {
115
+ const deps = api.get(coreHostCapabilities.serverSetup);
116
+ if (!deps || Array.isArray(deps)) return;
117
+ const profiles = parseProfiles(config);
118
+ deps.repositoryCredentials.register({
119
+ kind: "git_ssh",
120
+ resolve: (ref) => profiles.get(ref) ?? null
121
+ });
122
+ api.provide(gitSshIntegration, {
123
+ profiles: () => [...profiles.keys()].sort(),
124
+ async preflight(input) {
125
+ const material = profiles.get(input.credentialRef);
126
+ if (!material) {
127
+ return {
128
+ ok: false,
129
+ access: "read",
130
+ detail: `Unknown git_ssh credential '${input.credentialRef}'`
131
+ };
132
+ }
133
+ return preflightGitSshAccess(input, material);
134
+ }
135
+ });
136
+ }
137
+ };
138
+ var index_default = extension;
139
+ export {
140
+ index_default as default,
141
+ gitSshIntegration
44
142
  };
45
- export { parseProfiles };
46
- export default extension;
47
143
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,oBAAoB,GAGpB,MAAM,2BAA2B,CAAC;AAEnC,MAAM,CAAC,MAAM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,CAAC,CAAC;QACvC,IAAI,CAAC,qBAAqB,CAAC,QAAQ,CAAC;YACnC,IAAI,EAAE,SAAS;YACf,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,IAAI;SAC3C,CAAC,CAAC;IACJ,CAAC;CACD,CAAC;AAEF,OAAO,EAAE,aAAa,EAAE,CAAC;AACzB,eAAe,SAAS,CAAC"}
1
+ {"version":3,"sources":["../src/index.ts","../src/git-ssh-internal.ts"],"sourcesContent":["import {\n\tcoreHostCapabilities,\n\tcreateCapabilityToken,\n\ttype LeitwerkExtensionModule,\n} from \"@leitwerk-dev/process-sdk\";\nimport { parseProfiles, preflightGitSshAccess } from \"./git-ssh-internal.js\";\n\n/** @internal */\nconst manifest = {\n\t/** @internal */\n\tid: \"git-ssh\",\n\t/** @internal */\n\tversion: \"0.1.0\",\n} as const;\n\n/** @public */\ninterface GitSshAuthorizationPreflightInput {\n\t/** @public */\n\tcredentialRef: string;\n\t/** @public */\n\trepoLocator: string;\n\t/** @public */\n\tbaseBranch: string;\n\t/** @public */\n\trequireWrite: boolean;\n}\n\n/** @public */\ntype GitSshAuthorizationPreflightResult =\n\t| {\n\t\t\t/** @public */\n\t\t\tok: true;\n\t }\n\t| {\n\t\t\t/** @public */\n\t\t\tok: false;\n\t\t\t/** @public */\n\t\t\taccess: \"read\" | \"write\";\n\t\t\t/** @public */\n\t\t\tdetail: string;\n\t };\n\n/** @public */\nexport interface GitSshIntegration {\n\t/** @public */\n\tprofiles(): readonly string[];\n\t/** @public */\n\tpreflight(input: GitSshAuthorizationPreflightInput): Promise<GitSshAuthorizationPreflightResult>;\n}\n\n/** @public */\nexport const gitSshIntegration = createCapabilityToken<GitSshIntegration>(\n\t\"@leitwerk-dev/git-ssh.integration\",\n);\n\n/** @public */\nconst extension: LeitwerkExtensionModule = {\n\tmanifest,\n\tsetupServer(api, config) {\n\t\tconst deps = api.get(coreHostCapabilities.serverSetup);\n\t\tif (!deps || Array.isArray(deps)) return;\n\t\tconst profiles = parseProfiles(config);\n\t\tdeps.repositoryCredentials.register({\n\t\t\tkind: \"git_ssh\",\n\t\t\tresolve: (ref) => profiles.get(ref) ?? null,\n\t\t});\n\t\tapi.provide(gitSshIntegration, {\n\t\t\tprofiles: () => [...profiles.keys()].sort(),\n\t\t\tasync preflight(input) {\n\t\t\t\tconst material = profiles.get(input.credentialRef);\n\t\t\t\tif (!material) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\taccess: \"read\",\n\t\t\t\t\t\tdetail: `Unknown git_ssh credential '${input.credentialRef}'`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn preflightGitSshAccess(input, material);\n\t\t\t},\n\t\t});\n\t},\n};\n\nexport default extension;\n","import { execFile } from \"node:child_process\";\nimport { mkdtemp, rm, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport type { GitSshCredentialMaterial } from \"@leitwerk-dev/process-sdk\";\n\nconst execFileAsync = promisify(execFile);\n\ntype GitSshPreflightResult =\n\t| {\n\t\t\tok: true;\n\t }\n\t| {\n\t\t\tok: false;\n\t\t\taccess: \"read\" | \"write\";\n\t\t\tdetail: string;\n\t };\n\nfunction gitFailureDetail(error: unknown): string {\n\tif (!error || typeof error !== \"object\") return \"Git SSH access check failed\";\n\tconst value = error as { stderr?: unknown; stdout?: unknown; message?: unknown };\n\tconst output =\n\t\ttypeof value.stderr === \"string\" && value.stderr.trim()\n\t\t\t? value.stderr\n\t\t\t: typeof value.stdout === \"string\" && value.stdout.trim()\n\t\t\t\t? value.stdout\n\t\t\t\t: typeof value.message === \"string\"\n\t\t\t\t\t? value.message\n\t\t\t\t\t: \"Git SSH access check failed\";\n\treturn output.replace(/\\s+/g, \" \").trim().slice(0, 500);\n}\n\n/** @internal */\nexport async function preflightGitSshAccess(\n\tinput: { repoLocator: string; baseBranch: string; requireWrite: boolean },\n\tmaterial: GitSshCredentialMaterial,\n\tgitBinary = \"git\",\n): Promise<GitSshPreflightResult> {\n\tconst directory = await mkdtemp(join(tmpdir(), \"leitwerk-git-ssh-preflight-\"));\n\ttry {\n\t\tconst keyPath = join(directory, \"identity\");\n\t\tconst knownHostsPath = join(directory, \"known_hosts\");\n\t\tconst sshPath = join(directory, \"ssh\");\n\t\tawait Promise.all([\n\t\t\twriteFile(keyPath, `${material.privateKey.trim()}\\n`, { mode: 0o600 }),\n\t\t\twriteFile(knownHostsPath, `${material.knownHosts.trim()}\\n`, { mode: 0o600 }),\n\t\t\twriteFile(\n\t\t\t\tsshPath,\n\t\t\t\t`#!/bin/sh\\nexec ssh -F /dev/null -i \"${keyPath}\" -o IdentitiesOnly=yes -o UserKnownHostsFile=\"${knownHostsPath}\" -o StrictHostKeyChecking=yes -o BatchMode=yes \"$@\"\\n`,\n\t\t\t\t{ mode: 0o700 },\n\t\t\t),\n\t\t]);\n\t\tconst env = {\n\t\t\t...process.env,\n\t\t\tGIT_SSH: sshPath,\n\t\t\t// This also overrides ambient core.sshCommand, which takes precedence over GIT_SSH.\n\t\t\tGIT_SSH_COMMAND: `'${sshPath.replaceAll(\"'\", \"'\\\\''\")}'`,\n\t\t\tSSH_AUTH_SOCK: \"\",\n\t\t};\n\t\tconst ref = `refs/heads/${input.baseBranch}`;\n\t\ttry {\n\t\t\tawait execFileAsync(gitBinary, [\"ls-remote\", \"--exit-code\", input.repoLocator, ref], {\n\t\t\t\tenv,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\treturn { ok: false, access: \"read\", detail: gitFailureDetail(error) };\n\t\t}\n\t\tif (!input.requireWrite) return { ok: true };\n\n\t\ttry {\n\t\t\tawait execFileAsync(gitBinary, [\"init\", \"--quiet\", directory], { env });\n\t\t\tawait execFileAsync(\n\t\t\t\tgitBinary,\n\t\t\t\t[\"-C\", directory, \"fetch\", \"--quiet\", \"--depth=1\", input.repoLocator, ref],\n\t\t\t\t{ env },\n\t\t\t);\n\t\t\tconst probeBranch = `refs/heads/leitwerk/preflight-${process.pid}-${Date.now()}`;\n\t\t\tawait execFileAsync(\n\t\t\t\tgitBinary,\n\t\t\t\t[\"-C\", directory, \"push\", \"--dry-run\", input.repoLocator, `FETCH_HEAD:${probeBranch}`],\n\t\t\t\t{ env },\n\t\t\t);\n\t\t\treturn { ok: true };\n\t\t} catch (error) {\n\t\t\treturn { ok: false, access: \"write\", detail: gitFailureDetail(error) };\n\t\t}\n\t} finally {\n\t\tawait rm(directory, { recursive: true, force: true });\n\t}\n}\n\n/** @internal */\nexport function parseProfiles(raw: unknown): Map<string, GitSshCredentialMaterial> {\n\tconst root = raw && typeof raw === \"object\" ? (raw as Record<string, unknown>) : {};\n\tconst credentials =\n\t\troot.credentials && typeof root.credentials === \"object\"\n\t\t\t? (root.credentials as Record<string, unknown>)\n\t\t\t: {};\n\tconst profiles = new Map<string, GitSshCredentialMaterial>();\n\tfor (const [ref, value] of Object.entries(credentials)) {\n\t\tconst profile = value && typeof value === \"object\" ? (value as Record<string, unknown>) : {};\n\t\tconst privateKey = typeof profile.private_key === \"string\" ? profile.private_key.trim() : \"\";\n\t\tconst knownHosts = typeof profile.known_hosts === \"string\" ? profile.known_hosts.trim() : \"\";\n\t\tif (!privateKey.includes(\"BEGIN OPENSSH PRIVATE KEY\"))\n\t\t\tthrow new Error(`Invalid git_ssh credential '${ref}': an OpenSSH private key is required`);\n\t\tconst encodedBody = privateKey\n\t\t\t.split(/\\r?\\n/)\n\t\t\t.filter((line) => !line.startsWith(\"-----\"))\n\t\t\t.join(\"\");\n\t\tconst decodedHeader = Buffer.from(encodedBody, \"base64\").subarray(0, 96).toString(\"latin1\");\n\t\tif (/ENCRYPTED/.test(privateKey) || decodedHeader.includes(\"bcrypt\"))\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid git_ssh credential '${ref}': encrypted keys requiring a passphrase are unsupported`,\n\t\t\t);\n\t\tconst hostLines = knownHosts\n\t\t\t.split(/\\r?\\n/)\n\t\t\t.map((line) => line.trim())\n\t\t\t.filter((line) => line && !line.startsWith(\"#\"));\n\t\tif (hostLines.length === 0 || hostLines.some((line) => line.split(/\\s+/).length < 3))\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid git_ssh credential '${ref}': pinned known_hosts entries are required`,\n\t\t\t);\n\t\tprofiles.set(ref, { privateKey, knownHosts });\n\t}\n\treturn profiles;\n}\n"],"mappings":";AAAA;AAAA,EACC;AAAA,EACA;AAAA,OAEM;;;ACJP,SAAS,gBAAgB;AACzB,SAAS,SAAS,IAAI,iBAAiB;AACvC,SAAS,cAAc;AACvB,SAAS,YAAY;AACrB,SAAS,iBAAiB;AAG1B,IAAM,gBAAgB,UAAU,QAAQ;AAYxC,SAAS,iBAAiB,OAAwB;AACjD,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAChD,QAAM,QAAQ;AACd,QAAM,SACL,OAAO,MAAM,WAAW,YAAY,MAAM,OAAO,KAAK,IACnD,MAAM,SACN,OAAO,MAAM,WAAW,YAAY,MAAM,OAAO,KAAK,IACrD,MAAM,SACN,OAAO,MAAM,YAAY,WACxB,MAAM,UACN;AACN,SAAO,OAAO,QAAQ,QAAQ,GAAG,EAAE,KAAK,EAAE,MAAM,GAAG,GAAG;AACvD;AAGA,eAAsB,sBACrB,OACA,UACA,YAAY,OACqB;AACjC,QAAM,YAAY,MAAM,QAAQ,KAAK,OAAO,GAAG,6BAA6B,CAAC;AAC7E,MAAI;AACH,UAAM,UAAU,KAAK,WAAW,UAAU;AAC1C,UAAM,iBAAiB,KAAK,WAAW,aAAa;AACpD,UAAM,UAAU,KAAK,WAAW,KAAK;AACrC,UAAM,QAAQ,IAAI;AAAA,MACjB,UAAU,SAAS,GAAG,SAAS,WAAW,KAAK,CAAC;AAAA,GAAM,EAAE,MAAM,IAAM,CAAC;AAAA,MACrE,UAAU,gBAAgB,GAAG,SAAS,WAAW,KAAK,CAAC;AAAA,GAAM,EAAE,MA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AA,EAEhB,IAAI;AAAA;AAAA,EAEJ,SAAS;AACV;AAsCO,IAAM,oBAAoB;AAAA,EAChC;AACD;AAGA,IAAM,YAAqC;AAAA,EAC1C;AAAA,EACA,YAAY,KAAK,QAAQ;AACxB,UAAM,OAAO,IAAI,IAAI,qBAAqB,WAAW;AACrD,QAAI,CAAC,QAAQ,MAAM,QAAQ,IAAI,EAAG;AAClC,UAAM,WAAW,cAAc,MAAM;AACrC,SAAK,sBAAsB,SAAS;AAAA,MACnC,MAAM;AAAA,MACN,SAAS,CAAC,QAAQ,SAAS,IAAI,GAAG,KAAK;AAAA,IACxC,CAAC;AACD,QAAI,QAAQ,mBAAmB;AAAA,MAC9B,UAAU,MAAM,CAAC,GAAG,SAAS,KAAK,CAAC,EAAE,KAAK;AAAA,MAC1C,MAAM,UAAU,OAAO;AACtB,cAAM,WAAW,SAAS,IAAI,MAAM,aAAa;AACjD,YAAI,CAAC,UAAU;AACd,iBAAO;AAAA,YACN,IAAI;AAAA,YACJ,QAAQ;AAAA,YACR,QAAQ,+BAA+B,MAAM,aAAa;AAAA,UAC3D;AAAA,QACD;AACA,eAAO,sBAAsB,OAAO,QAAQ;AAAA,MAC7C;AAAA,IACD,CAAC;AAAA,EACF;AACD;AAEA,IAAO,gBAAQ;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leitwerk-dev/git-ssh",
3
- "version": "0.1.9",
3
+ "version": "0.2.1",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/leitwerk-dev/leitwerk.git",
@@ -25,7 +25,7 @@
25
25
  "build": "tsup --silent"
26
26
  },
27
27
  "dependencies": {
28
- "@leitwerk-dev/process-sdk": "0.1.9"
28
+ "@leitwerk-dev/process-sdk": "0.2.1"
29
29
  },
30
30
  "devDependencies": {
31
31
  "tsup": "^8.5.1"
@@ -35,7 +35,7 @@
35
35
  "access": "public"
36
36
  },
37
37
  "engines": {
38
- "node": ">=22"
38
+ "node": ">=26 <27"
39
39
  },
40
40
  "files": [
41
41
  "dist/**",
@@ -0,0 +1,127 @@
1
+ import { execFile } from "node:child_process";
2
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { promisify } from "node:util";
6
+ import type { GitSshCredentialMaterial } from "@leitwerk-dev/process-sdk";
7
+
8
+ const execFileAsync = promisify(execFile);
9
+
10
+ type GitSshPreflightResult =
11
+ | {
12
+ ok: true;
13
+ }
14
+ | {
15
+ ok: false;
16
+ access: "read" | "write";
17
+ detail: string;
18
+ };
19
+
20
+ function gitFailureDetail(error: unknown): string {
21
+ if (!error || typeof error !== "object") return "Git SSH access check failed";
22
+ const value = error as { stderr?: unknown; stdout?: unknown; message?: unknown };
23
+ const output =
24
+ typeof value.stderr === "string" && value.stderr.trim()
25
+ ? value.stderr
26
+ : typeof value.stdout === "string" && value.stdout.trim()
27
+ ? value.stdout
28
+ : typeof value.message === "string"
29
+ ? value.message
30
+ : "Git SSH access check failed";
31
+ return output.replace(/\s+/g, " ").trim().slice(0, 500);
32
+ }
33
+
34
+ /** @internal */
35
+ export async function preflightGitSshAccess(
36
+ input: { repoLocator: string; baseBranch: string; requireWrite: boolean },
37
+ material: GitSshCredentialMaterial,
38
+ gitBinary = "git",
39
+ ): Promise<GitSshPreflightResult> {
40
+ const directory = await mkdtemp(join(tmpdir(), "leitwerk-git-ssh-preflight-"));
41
+ try {
42
+ const keyPath = join(directory, "identity");
43
+ const knownHostsPath = join(directory, "known_hosts");
44
+ const sshPath = join(directory, "ssh");
45
+ await Promise.all([
46
+ writeFile(keyPath, `${material.privateKey.trim()}\n`, { mode: 0o600 }),
47
+ writeFile(knownHostsPath, `${material.knownHosts.trim()}\n`, { mode: 0o600 }),
48
+ writeFile(
49
+ sshPath,
50
+ `#!/bin/sh\nexec ssh -F /dev/null -i "${keyPath}" -o IdentitiesOnly=yes -o UserKnownHostsFile="${knownHostsPath}" -o StrictHostKeyChecking=yes -o BatchMode=yes "$@"\n`,
51
+ { mode: 0o700 },
52
+ ),
53
+ ]);
54
+ const env = {
55
+ ...process.env,
56
+ GIT_SSH: sshPath,
57
+ // This also overrides ambient core.sshCommand, which takes precedence over GIT_SSH.
58
+ GIT_SSH_COMMAND: `'${sshPath.replaceAll("'", "'\\''")}'`,
59
+ SSH_AUTH_SOCK: "",
60
+ };
61
+ const ref = `refs/heads/${input.baseBranch}`;
62
+ try {
63
+ await execFileAsync(gitBinary, ["ls-remote", "--exit-code", input.repoLocator, ref], {
64
+ env,
65
+ });
66
+ } catch (error) {
67
+ return { ok: false, access: "read", detail: gitFailureDetail(error) };
68
+ }
69
+ if (!input.requireWrite) return { ok: true };
70
+
71
+ try {
72
+ await execFileAsync(gitBinary, ["init", "--quiet", directory], { env });
73
+ await execFileAsync(
74
+ gitBinary,
75
+ ["-C", directory, "fetch", "--quiet", "--depth=1", input.repoLocator, ref],
76
+ { env },
77
+ );
78
+ const probeBranch = `refs/heads/leitwerk/preflight-${process.pid}-${Date.now()}`;
79
+ await execFileAsync(
80
+ gitBinary,
81
+ ["-C", directory, "push", "--dry-run", input.repoLocator, `FETCH_HEAD:${probeBranch}`],
82
+ { env },
83
+ );
84
+ return { ok: true };
85
+ } catch (error) {
86
+ return { ok: false, access: "write", detail: gitFailureDetail(error) };
87
+ }
88
+ } finally {
89
+ await rm(directory, { recursive: true, force: true });
90
+ }
91
+ }
92
+
93
+ /** @internal */
94
+ export function parseProfiles(raw: unknown): Map<string, GitSshCredentialMaterial> {
95
+ const root = raw && typeof raw === "object" ? (raw as Record<string, unknown>) : {};
96
+ const credentials =
97
+ root.credentials && typeof root.credentials === "object"
98
+ ? (root.credentials as Record<string, unknown>)
99
+ : {};
100
+ const profiles = new Map<string, GitSshCredentialMaterial>();
101
+ for (const [ref, value] of Object.entries(credentials)) {
102
+ const profile = value && typeof value === "object" ? (value as Record<string, unknown>) : {};
103
+ const privateKey = typeof profile.private_key === "string" ? profile.private_key.trim() : "";
104
+ const knownHosts = typeof profile.known_hosts === "string" ? profile.known_hosts.trim() : "";
105
+ if (!privateKey.includes("BEGIN OPENSSH PRIVATE KEY"))
106
+ throw new Error(`Invalid git_ssh credential '${ref}': an OpenSSH private key is required`);
107
+ const encodedBody = privateKey
108
+ .split(/\r?\n/)
109
+ .filter((line) => !line.startsWith("-----"))
110
+ .join("");
111
+ const decodedHeader = Buffer.from(encodedBody, "base64").subarray(0, 96).toString("latin1");
112
+ if (/ENCRYPTED/.test(privateKey) || decodedHeader.includes("bcrypt"))
113
+ throw new Error(
114
+ `Invalid git_ssh credential '${ref}': encrypted keys requiring a passphrase are unsupported`,
115
+ );
116
+ const hostLines = knownHosts
117
+ .split(/\r?\n/)
118
+ .map((line) => line.trim())
119
+ .filter((line) => line && !line.startsWith("#"));
120
+ if (hostLines.length === 0 || hostLines.some((line) => line.split(/\s+/).length < 3))
121
+ throw new Error(
122
+ `Invalid git_ssh credential '${ref}': pinned known_hosts entries are required`,
123
+ );
124
+ profiles.set(ref, { privateKey, knownHosts });
125
+ }
126
+ return profiles;
127
+ }
package/src/index.ts CHANGED
@@ -1,46 +1,59 @@
1
1
  import {
2
2
  coreHostCapabilities,
3
- type GitSshCredentialMaterial,
3
+ createCapabilityToken,
4
4
  type LeitwerkExtensionModule,
5
5
  } from "@leitwerk-dev/process-sdk";
6
+ import { parseProfiles, preflightGitSshAccess } from "./git-ssh-internal.js";
6
7
 
7
- export const manifest = { id: "git-ssh", version: "0.1.0" } as const;
8
+ /** @internal */
9
+ const manifest = {
10
+ /** @internal */
11
+ id: "git-ssh",
12
+ /** @internal */
13
+ version: "0.1.0",
14
+ } as const;
8
15
 
9
- function parseProfiles(raw: unknown): Map<string, GitSshCredentialMaterial> {
10
- const root = raw && typeof raw === "object" ? (raw as Record<string, unknown>) : {};
11
- const credentials =
12
- root.credentials && typeof root.credentials === "object"
13
- ? (root.credentials as Record<string, unknown>)
14
- : {};
15
- const profiles = new Map<string, GitSshCredentialMaterial>();
16
- for (const [ref, value] of Object.entries(credentials)) {
17
- const profile = value && typeof value === "object" ? (value as Record<string, unknown>) : {};
18
- const privateKey = typeof profile.private_key === "string" ? profile.private_key.trim() : "";
19
- const knownHosts = typeof profile.known_hosts === "string" ? profile.known_hosts.trim() : "";
20
- if (!privateKey.includes("BEGIN OPENSSH PRIVATE KEY"))
21
- throw new Error(`Invalid git_ssh credential '${ref}': an OpenSSH private key is required`);
22
- const encodedBody = privateKey
23
- .split(/\r?\n/)
24
- .filter((line) => !line.startsWith("-----"))
25
- .join("");
26
- const decodedHeader = Buffer.from(encodedBody, "base64").subarray(0, 96).toString("latin1");
27
- if (/ENCRYPTED/.test(privateKey) || decodedHeader.includes("bcrypt"))
28
- throw new Error(
29
- `Invalid git_ssh credential '${ref}': encrypted keys requiring a passphrase are unsupported`,
30
- );
31
- const hostLines = knownHosts
32
- .split(/\r?\n/)
33
- .map((line) => line.trim())
34
- .filter((line) => line && !line.startsWith("#"));
35
- if (hostLines.length === 0 || hostLines.some((line) => line.split(/\s+/).length < 3))
36
- throw new Error(
37
- `Invalid git_ssh credential '${ref}': pinned known_hosts entries are required`,
38
- );
39
- profiles.set(ref, { privateKey, knownHosts });
40
- }
41
- return profiles;
16
+ /** @public */
17
+ interface GitSshAuthorizationPreflightInput {
18
+ /** @public */
19
+ credentialRef: string;
20
+ /** @public */
21
+ repoLocator: string;
22
+ /** @public */
23
+ baseBranch: string;
24
+ /** @public */
25
+ requireWrite: boolean;
42
26
  }
43
27
 
28
+ /** @public */
29
+ type GitSshAuthorizationPreflightResult =
30
+ | {
31
+ /** @public */
32
+ ok: true;
33
+ }
34
+ | {
35
+ /** @public */
36
+ ok: false;
37
+ /** @public */
38
+ access: "read" | "write";
39
+ /** @public */
40
+ detail: string;
41
+ };
42
+
43
+ /** @public */
44
+ export interface GitSshIntegration {
45
+ /** @public */
46
+ profiles(): readonly string[];
47
+ /** @public */
48
+ preflight(input: GitSshAuthorizationPreflightInput): Promise<GitSshAuthorizationPreflightResult>;
49
+ }
50
+
51
+ /** @public */
52
+ export const gitSshIntegration = createCapabilityToken<GitSshIntegration>(
53
+ "@leitwerk-dev/git-ssh.integration",
54
+ );
55
+
56
+ /** @public */
44
57
  const extension: LeitwerkExtensionModule = {
45
58
  manifest,
46
59
  setupServer(api, config) {
@@ -51,8 +64,21 @@ const extension: LeitwerkExtensionModule = {
51
64
  kind: "git_ssh",
52
65
  resolve: (ref) => profiles.get(ref) ?? null,
53
66
  });
67
+ api.provide(gitSshIntegration, {
68
+ profiles: () => [...profiles.keys()].sort(),
69
+ async preflight(input) {
70
+ const material = profiles.get(input.credentialRef);
71
+ if (!material) {
72
+ return {
73
+ ok: false,
74
+ access: "read",
75
+ detail: `Unknown git_ssh credential '${input.credentialRef}'`,
76
+ };
77
+ }
78
+ return preflightGitSshAccess(input, material);
79
+ },
80
+ });
54
81
  },
55
82
  };
56
83
 
57
- export { parseProfiles };
58
84
  export default extension;