forgedock 1.52.0 → 1.54.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +51 -0
- package/README.md +8 -2
- package/bin/auth/app-manifest.mjs +89 -0
- package/bin/auth/app-manifest.test.mjs +75 -0
- package/bin/auth/app-token.mjs +256 -0
- package/bin/auth/app-token.test.mjs +232 -0
- package/bin/brand.mjs +7 -0
- package/bin/config-history.mjs +151 -0
- package/bin/config-schema.mjs +115 -0
- package/bin/demo.mjs +65 -11
- package/bin/engine/outcome-codes.mjs +9 -3
- package/bin/engine/telemetry-seam.mjs +11 -3
- package/bin/engine/telemetry-seam.test.mjs +17 -0
- package/bin/engine-cli.mjs +110 -36
- package/bin/experiment.mjs +58 -6
- package/bin/first-run.mjs +122 -0
- package/bin/forge-utils.mjs +6 -2
- package/bin/forgedock.mjs +138 -142
- package/bin/help-text.mjs +144 -0
- package/bin/hooks/pre-tool-use.mjs +7 -0
- package/bin/journey.mjs +82 -83
- package/bin/lean/acceptance.mjs +313 -0
- package/bin/lean/acceptance.test.mjs +215 -0
- package/bin/lean/account-watch.mjs +28 -0
- package/bin/lean/account-watch.test.mjs +30 -0
- package/bin/lean/activation.mjs +38 -0
- package/bin/lean/activation.test.mjs +36 -1
- package/bin/lean/basered.mjs +115 -0
- package/bin/lean/basered.test.mjs +66 -0
- package/bin/lean/batch-health.mjs +114 -7
- package/bin/lean/batch-health.test.mjs +87 -1
- package/bin/lean/batch.mjs +41 -2
- package/bin/lean/batch.test.mjs +115 -11
- package/bin/lean/branchlock.mjs +54 -0
- package/bin/lean/branchlock.test.mjs +49 -0
- package/bin/lean/ceiling.mjs +72 -0
- package/bin/lean/ceiling.test.mjs +54 -0
- package/bin/lean/checkpoint-reconcile.mjs +43 -0
- package/bin/lean/checkpoint-reconcile.test.mjs +95 -0
- package/bin/lean/ci-budget.mjs +366 -0
- package/bin/lean/ci-budget.test.mjs +167 -0
- package/bin/lean/conformance.e2e.test.mjs +8 -1
- package/bin/lean/conformance.mjs +269 -38
- package/bin/lean/conformance.test.mjs +280 -7
- package/bin/lean/context.mjs +35 -6
- package/bin/lean/context.test.mjs +27 -1
- package/bin/lean/depcache.mjs +25 -1
- package/bin/lean/depcache.test.mjs +26 -0
- package/bin/lean/e2e.mjs +18 -2
- package/bin/lean/e2e.test.mjs +26 -1
- package/bin/lean/effects.mjs +47 -14
- package/bin/lean/execution.mjs +19 -3
- package/bin/lean/execution.test.mjs +63 -0
- package/bin/lean/facts.mjs +3 -3
- package/bin/lean/facts.test.mjs +5 -0
- package/bin/lean/findinglabel.mjs +16 -0
- package/bin/lean/findinglabel.test.mjs +39 -0
- package/bin/lean/fixround.mjs +14 -0
- package/bin/lean/fixround.test.mjs +25 -2
- package/bin/lean/gh-assoc.test.mjs +2 -1
- package/bin/lean/integration.mjs +100 -9
- package/bin/lean/integration.test.mjs +98 -0
- package/bin/lean/issuewatch-parity.mjs +64 -0
- package/bin/lean/issuewatch-parity.test.mjs +127 -0
- package/bin/lean/issuewatch-release.mjs +6 -2
- package/bin/lean/issuewatch-release.test.mjs +17 -1
- package/bin/lean/issuewatch.mjs +45 -6
- package/bin/lean/issuewatch.test.mjs +3 -2
- package/bin/lean/lanelock.mjs +14 -0
- package/bin/lean/lean.mjs +473 -100
- package/bin/lean/lean.test.mjs +686 -33
- package/bin/lean/light.mjs +48 -7
- package/bin/lean/light.test.mjs +37 -3
- package/bin/lean/limits.test.mjs +142 -9
- package/bin/lean/mechfix.mjs +124 -0
- package/bin/lean/mechfix.test.mjs +75 -0
- package/bin/lean/orchestrate-cancel.test.mjs +143 -0
- package/bin/lean/orchestrate.mjs +116 -28
- package/bin/lean/phaseledger.mjs +47 -5
- package/bin/lean/phaseledger.test.mjs +30 -1
- package/bin/lean/postdeploy-check.test.mjs +39 -0
- package/bin/lean/precheck.mjs +23 -4
- package/bin/lean/precheck.test.mjs +14 -1
- package/bin/lean/prereq.mjs +28 -0
- package/bin/lean/prereq.test.mjs +20 -0
- package/bin/lean/probe.mjs +4 -2
- package/bin/lean/prodparity.mjs +52 -0
- package/bin/lean/prodparity.test.mjs +67 -0
- package/bin/lean/prompts.mjs +77 -19
- package/bin/lean/quota.mjs +39 -0
- package/bin/lean/recovery.test.mjs +11 -1
- package/bin/lean/relaxation.mjs +73 -0
- package/bin/lean/relaxation.test.mjs +54 -0
- package/bin/lean/release-io.test.mjs +42 -0
- package/bin/lean/release-postmerge.mjs +125 -0
- package/bin/lean/release-preflight.mjs +58 -0
- package/bin/lean/release-preflight.test.mjs +114 -0
- package/bin/lean/release-rehearsal.mjs +64 -0
- package/bin/lean/release-rehearsal.test.mjs +93 -0
- package/bin/lean/release-review.e2e.test.mjs +77 -0
- package/bin/lean/release-review.mjs +254 -0
- package/bin/lean/release-review.test.mjs +307 -0
- package/bin/lean/release-snapshot.mjs +188 -0
- package/bin/lean/release-snapshot.test.mjs +190 -0
- package/bin/lean/release.mjs +296 -0
- package/bin/lean/release.test.mjs +387 -0
- package/bin/lean/render.mjs +1 -1
- package/bin/lean/replan.mjs +184 -0
- package/bin/lean/replan.test.mjs +110 -0
- package/bin/lean/resume.mjs +9 -7
- package/bin/lean/resume.test.mjs +16 -0
- package/bin/lean/rotator.mjs +150 -31
- package/bin/lean/rotator.test.mjs +105 -2
- package/bin/lean/sandbox-remote.mjs +9 -2
- package/bin/lean/schedd.mjs +83 -5
- package/bin/lean/schedd.test.mjs +108 -7
- package/bin/lean/selfreview.mjs +94 -0
- package/bin/lean/selfreview.test.mjs +58 -1
- package/bin/lean/selftest-gate.mjs +22 -0
- package/bin/lean/selftest-gate.test.mjs +18 -1
- package/bin/lean/selftest-journey.mjs +234 -0
- package/bin/lean/selftest-journey.test.mjs +130 -0
- package/bin/lean/selftest-live.mjs +2 -1
- package/bin/lean/seqlease.mjs +35 -1
- package/bin/lean/seqlease.test.mjs +15 -0
- package/bin/lean/seqreserve.e2e.test.mjs +135 -0
- package/bin/lean/seqreserve.mjs +73 -0
- package/bin/lean/seqreserve.test.mjs +134 -0
- package/bin/lean/sequence.mjs +35 -6
- package/bin/lean/seqversioned.mjs +147 -0
- package/bin/lean/stagestamp.mjs +28 -0
- package/bin/lean/stagestamp.test.mjs +32 -0
- package/bin/lean/surfaces.mjs +75 -0
- package/bin/lean/surfaces.test.mjs +59 -0
- package/bin/lean/toolplace.mjs +28 -0
- package/bin/lean/toolplace.test.mjs +24 -0
- package/bin/lean/toolstats.mjs +3 -1
- package/bin/lean/toolstats.test.mjs +11 -0
- package/bin/lean/validatebest.mjs +28 -0
- package/bin/lean/validatebest.test.mjs +27 -0
- package/bin/lean/verifier.mjs +3 -2
- package/bin/lean/verify.mjs +2 -1
- package/bin/lean/verify.test.mjs +6 -0
- package/bin/pool/agent.mjs +27 -4
- package/bin/pool/docker.mjs +5 -0
- package/bin/pool/router.mjs +74 -28
- package/bin/prereqs.mjs +111 -0
- package/bin/replay-timelapse.mjs +149 -0
- package/bin/review-staging.mjs +123 -16
- package/bin/review-staging.test.mjs +18 -0
- package/bin/runner.mjs +43 -6
- package/bin/splash-install.mjs +157 -0
- package/bin/stats/aggregate.mjs +8 -1
- package/bin/stats/conformance-outcomes.mjs +289 -0
- package/bin/stats/conformance-outcomes.test.mjs +274 -0
- package/bin/stats/depth.mjs +275 -0
- package/bin/stats/depth.test.mjs +158 -0
- package/bin/stats/efficiency.mjs +26 -5
- package/bin/stats/efficiency.test.mjs +45 -1
- package/bin/stats/experiment.mjs +7 -5
- package/bin/stats/first-review.mjs +77 -0
- package/bin/stats/first-review.test.mjs +36 -0
- package/bin/stats/firstmerge.mjs +40 -0
- package/bin/stats/firstmerge.test.mjs +41 -0
- package/bin/stats/github-source.mjs +53 -15
- package/bin/stats/index.mjs +147 -9
- package/bin/stats/local-source.mjs +12 -0
- package/bin/stats/origin.mjs +80 -0
- package/bin/stats/origin.test.mjs +58 -0
- package/bin/stats/query.mjs +69 -0
- package/bin/stats/render.mjs +3 -1
- package/bin/stats/scoreboard.mjs +137 -0
- package/bin/stats/scoreboard.test.mjs +87 -0
- package/bin/stats/selffiled.mjs +52 -0
- package/bin/stats/selffiled.test.mjs +71 -0
- package/bin/stats/stats.test.mjs +80 -0
- package/bin/tui.mjs +3 -2
- package/commands/bootstrap.md +15 -14
- package/commands/deploy-pr.md +18 -3
- package/commands/forge-stats.md +1 -1
- package/commands/forgedock-ci-setup.md +28 -0
- package/commands/forgedock-init.md +4 -5
- package/commands/issue.md +2 -0
- package/commands/milestone.md +9 -1
- package/commands/orchestrate.md +1 -1
- package/commands/replay.md +2 -0
- package/commands/review-pr-agents/security.md +4 -0
- package/commands/review-pr-staging.md +6 -1
- package/commands/work-on/build.md +4 -6
- package/commands/work-on/close.md +8 -0
- package/docs/CONFIG.md +170 -18
- package/docs/ISSUE-WATCH.md +25 -0
- package/docs/OUTCOME-CODES.md +4 -0
- package/docs/REPLAY.md +9 -0
- package/docs/SELFTEST.md +11 -0
- package/docs/STATS.md +61 -0
- package/docs/TELEMETRY.md +1 -1
- package/docs/eval/README.md +6 -0
- package/docs/eval/adversarial-bench.md +68 -0
- package/docs/eval/corpus/adversarial-v1.json +285 -0
- package/docs/eval/feature-bench.md +42 -0
- package/docs/eval/feature-specs/crud-auth/journeys/notes-crud-isolated.mjs +21 -0
- package/docs/eval/feature-specs/crud-auth/journeys/register-login.mjs +12 -0
- package/docs/eval/feature-specs/crud-auth/spec.md +15 -0
- package/docs/site/start-a-new-project.md +2 -1
- package/package.json +5 -2
- package/plugins/forgedock-splash/.claude-plugin/plugin.json +10 -0
- package/plugins/forgedock-splash/README.md +27 -0
- package/plugins/forgedock-splash/hooks/hooks.json +1 -0
- package/plugins/forgedock-splash/hooks/register.tsx +74 -0
- package/plugins/forgedock-splash/hooks/scene.ts +222 -0
- package/plugins/forgedock-splash/types/index.d.ts +10 -0
- package/pool/README.md +1 -1
- package/pool/image/cs-cred +14 -1
- package/scripts/backfill-finding-labels.mjs +50 -0
- package/scripts/backfill-finding-labels.test.mjs +36 -0
- package/scripts/bench-adversarial.mjs +216 -0
- package/scripts/bench-feature.mjs +170 -0
- package/scripts/bench-lightlane.mjs +2 -2
- package/scripts/bootstrap-create.mjs +2 -2
- package/scripts/bootstrap-validate.mjs +35 -2
- package/scripts/check-spec-size.sh +4 -3
- package/scripts/check-spec-size.test.sh +3 -0
- package/scripts/doctor-pipeline-state.sh +21 -6
- package/scripts/file-deferred-followups.sh +59 -251
- package/scripts/file-deferred-followups.test.sh +85 -206
- package/scripts/followup-route.mjs +12 -0
- package/scripts/owner-route-parity.test.sh +17 -1
- package/scripts/plan-validate-live.mjs +40 -6
- package/scripts/review-pr-side-effects.test.sh +40 -0
- package/scripts/review-pr-staging-scope.test.sh +1 -1
- package/scripts/review-staging-post.sh +23 -0
- package/scripts/review-staging-post.test.sh +8 -0
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
|
|
3
|
+
"name": "forgedock",
|
|
4
|
+
"description": "ForgeDock — Autonomous AI development pipeline commands for Claude Code. Investigate, architect, build, review, and merge with structured GitHub-backed memory.",
|
|
5
|
+
"owner": {
|
|
6
|
+
"name": "RapierCraft Studios",
|
|
7
|
+
"email": "support@rapiercraftstudios.com"
|
|
8
|
+
},
|
|
9
|
+
"plugins": [
|
|
10
|
+
{
|
|
11
|
+
"name": "forgedock",
|
|
12
|
+
"displayName": "ForgeDock",
|
|
13
|
+
"source": "./",
|
|
14
|
+
"description": "Autonomous AI development pipeline that uses GitHub as a structured knowledge graph. Adds /work-on, /review-pr, /quality-gate, /orchestrate, /autopilot, and 20+ pipeline commands.",
|
|
15
|
+
"author": {
|
|
16
|
+
"name": "RapierCraft Studios"
|
|
17
|
+
},
|
|
18
|
+
"homepage": "https://github.com/RapierCraftStudios/ForgeDock",
|
|
19
|
+
"repository": "https://github.com/RapierCraftStudios/ForgeDock",
|
|
20
|
+
"license": "AGPL-3.0",
|
|
21
|
+
"category": "dev-workflow",
|
|
22
|
+
"tags": [
|
|
23
|
+
"ai-agents",
|
|
24
|
+
"autonomous",
|
|
25
|
+
"github",
|
|
26
|
+
"pipeline",
|
|
27
|
+
"code-review",
|
|
28
|
+
"claude-code"
|
|
29
|
+
]
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
"name": "forgedock-splash",
|
|
33
|
+
"displayName": "ForgeDock Splash",
|
|
34
|
+
"source": "./plugins/forgedock-splash",
|
|
35
|
+
"description": "Startup splash for ForgeDock in Claude Code: the F mark is forged, Clawd bonks it, sparks fly, then it settles on 'supercharged'. Turn off with /plugin disable forgedock-splash.",
|
|
36
|
+
"author": {
|
|
37
|
+
"name": "RapierCraft Studios"
|
|
38
|
+
},
|
|
39
|
+
"homepage": "https://github.com/RapierCraftStudios/ForgeDock",
|
|
40
|
+
"repository": "https://github.com/RapierCraftStudios/ForgeDock",
|
|
41
|
+
"license": "AGPL-3.0",
|
|
42
|
+
"category": "dev-workflow",
|
|
43
|
+
"tags": [
|
|
44
|
+
"forgedock",
|
|
45
|
+
"splash",
|
|
46
|
+
"branding",
|
|
47
|
+
"claude-code"
|
|
48
|
+
]
|
|
49
|
+
}
|
|
50
|
+
]
|
|
51
|
+
}
|
package/README.md
CHANGED
|
@@ -4,7 +4,9 @@
|
|
|
4
4
|
|
|
5
5
|
<h1>ForgeDock</h1>
|
|
6
6
|
|
|
7
|
-
<p><strong>
|
|
7
|
+
<p><strong>An AI engineering team that ships to production</strong></p>
|
|
8
|
+
|
|
9
|
+
<p>From GitHub issues to reviewed, tested, merged changes, autonomously.</p>
|
|
8
10
|
|
|
9
11
|
<p>ForgeDock runs AI coding agents through validation, implementation, review, CI and merge, one issue per lane, many lanes in parallel. Every step is recorded on GitHub, so runs survive crashes, later agents build on earlier ones, and you can audit everything.</p>
|
|
10
12
|
|
|
@@ -128,7 +130,11 @@ Deeper: [How it works](docs/site/how-it-works.md) · [GitHub is your agents' mem
|
|
|
128
130
|
|
|
129
131
|
- [Getting started](docs/site/getting-started.md) · [Install](docs/site/install.md) · [Configuration](docs/CONFIG.md) · [Command reference](docs/site/command-reference.md)
|
|
130
132
|
- [Troubleshooting & recovery](docs/site/troubleshooting.md) · [Outcome codes](docs/OUTCOME-CODES.md) · [Stats](docs/STATS.md)
|
|
131
|
-
- [Start a new project](docs/site/start-a-new-project.md) · [Comparison with other approaches](docs/comparison.md) · [Release eval scorecards](docs/eval/README.md)
|
|
133
|
+
- [Start a new project](docs/site/start-a-new-project.md) · [Comparison with other approaches](docs/comparison.md) · [Release eval scorecards](docs/eval/README.md) · [Adversarial benchmark](docs/eval/adversarial-bench.md)
|
|
134
|
+
|
|
135
|
+
## FAQ
|
|
136
|
+
|
|
137
|
+
**Does it create its own work?** Some issues are pipeline-found (review findings, follow-ups, production signals). `npx forgedock stats --origin` prints the split of requested vs pipeline-generated issues, how the pipeline-found ones closed, and their share of cost; see [Issue origin](docs/STATS.md#issue-origin---origin-forge5294).
|
|
132
138
|
|
|
133
139
|
## For companies
|
|
134
140
|
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* Bring-your-own GitHub App (#5301): GitHub's App manifest flow, then local minting of installation tokens with the
|
|
5
|
+
* App's own private key (RS256 JWT via node:crypto; no dependency). Every network call goes through an injected `fetch`.
|
|
6
|
+
*/
|
|
7
|
+
import { createSign } from "node:crypto";
|
|
8
|
+
import { createServer } from "node:http";
|
|
9
|
+
|
|
10
|
+
export const API = "https://api.github.com";
|
|
11
|
+
|
|
12
|
+
/** The permissions the pipeline uses; installation tokens are scoped down to exactly these. */
|
|
13
|
+
export const PIPELINE_PERMISSIONS = Object.freeze({
|
|
14
|
+
contents: "write", pull_requests: "write", issues: "write", checks: "read", statuses: "read", actions: "read", workflows: "write", metadata: "read",
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
const b64u = (b) => Buffer.from(b).toString("base64url");
|
|
18
|
+
|
|
19
|
+
/** RS256 App JWT: `iat` backdated 60 s for clock skew, `exp` under GitHub's 10 min cap. */
|
|
20
|
+
export function createAppJwt({ appId, pem, now = Date.now() }) {
|
|
21
|
+
const iat = Math.floor(now / 1000) - 60;
|
|
22
|
+
const head = `${b64u(JSON.stringify({ alg: "RS256", typ: "JWT" }))}.${b64u(JSON.stringify({ iat, exp: iat + 600, iss: String(appId) }))}`;
|
|
23
|
+
return `${head}.${createSign("RSA-SHA256").update(head).sign(pem).toString("base64url")}`;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async function ghJson(fetchFn, url, init, what) {
|
|
27
|
+
const res = await fetchFn(url, init);
|
|
28
|
+
if (!res.ok) throw new Error(`${what} failed (HTTP ${res.status})`);
|
|
29
|
+
return res.json();
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const appHeaders = (jwt) => ({ Authorization: `Bearer ${jwt}`, Accept: "application/vnd.github+json", "Content-Type": "application/json", "User-Agent": "forgedock" });
|
|
33
|
+
|
|
34
|
+
/** Mint an installation token locally, scoped to `repositoryIds` (when given) and `permissions`. @returns {{token:string, expiresAt:string}} */
|
|
35
|
+
export async function mintInstallationToken({ appId, pem, installationId, repositoryIds, permissions = PIPELINE_PERMISSIONS, fetch: fetchFn = fetch, now = Date.now() }) {
|
|
36
|
+
const body = { permissions };
|
|
37
|
+
if (repositoryIds?.length) body.repository_ids = repositoryIds;
|
|
38
|
+
const j = await ghJson(fetchFn, `${API}/app/installations/${installationId}/access_tokens`,
|
|
39
|
+
{ method: "POST", headers: appHeaders(createAppJwt({ appId, pem, now })), body: JSON.stringify(body) }, "installation token mint");
|
|
40
|
+
if (!j?.token || !j?.expires_at) throw new Error("installation token mint returned no token");
|
|
41
|
+
return { token: j.token, expiresAt: j.expires_at };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** First installation of the App (for the BYO owner), via the App JWT. */
|
|
45
|
+
export async function findInstallation({ appId, pem, fetch: fetchFn = fetch, now = Date.now() }) {
|
|
46
|
+
const list = await ghJson(fetchFn, `${API}/app/installations`, { headers: appHeaders(createAppJwt({ appId, pem, now })) }, "installation lookup");
|
|
47
|
+
return Array.isArray(list) && list[0]?.id ? list[0].id : null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function buildAppManifest({ redirectUrl, name = "forgedock-self-hosted" }) {
|
|
51
|
+
return {
|
|
52
|
+
name, url: "https://github.com/RapierCraftStudios/forgedock", redirect_url: redirectUrl, public: false,
|
|
53
|
+
default_permissions: { ...PIPELINE_PERMISSIONS }, default_events: [],
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** POST /app-manifests/{code}/conversions: the App id, slug and private key GitHub generated for the user. */
|
|
58
|
+
export async function convertManifestCode({ code, fetch: fetchFn = fetch }) {
|
|
59
|
+
const j = await ghJson(fetchFn, `${API}/app-manifests/${encodeURIComponent(code)}/conversions`,
|
|
60
|
+
{ method: "POST", headers: { Accept: "application/vnd.github+json", "User-Agent": "forgedock" } }, "manifest conversion");
|
|
61
|
+
if (!j?.id || !j?.pem) throw new Error("manifest conversion returned no app id or key");
|
|
62
|
+
return { appId: j.id, slug: j.slug, pem: j.pem };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Loopback receiver: serves an auto-submitting form that posts the manifest to GitHub, then resolves with the `code`
|
|
67
|
+
* GitHub redirects back with (state-checked). `manifest` may be a function of the bound port (for `redirect_url`). `onListening(url)` hands the start URL to the caller (open or print).
|
|
68
|
+
*/
|
|
69
|
+
export function receiveManifestCode({ manifest, state, onListening, timeoutMs = 300000, org }) {
|
|
70
|
+
return new Promise((resolve, reject) => {
|
|
71
|
+
let done = false;
|
|
72
|
+
const finish = (fn, v) => { if (done) return; done = true; clearTimeout(timer); server.close(); fn(v); };
|
|
73
|
+
const server = createServer((req, res) => {
|
|
74
|
+
const u = new URL(req.url, "http://127.0.0.1");
|
|
75
|
+
if (u.pathname === "/callback") {
|
|
76
|
+
const ok = u.searchParams.get("state") === state && u.searchParams.get("code");
|
|
77
|
+
res.writeHead(ok ? 200 : 400, { "Content-Type": "text/plain" }).end(ok ? "ForgeDock: App created, you can close this tab." : "bad state");
|
|
78
|
+
return ok ? finish(resolve, u.searchParams.get("code")) : undefined;
|
|
79
|
+
}
|
|
80
|
+
const target = `https://github.com/${org ? `organizations/${encodeURIComponent(org)}/` : ""}settings/apps/new?state=${state}`;
|
|
81
|
+
const esc = JSON.stringify(typeof manifest === "function" ? manifest(server.address().port) : manifest).replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<");
|
|
82
|
+
res.writeHead(200, { "Content-Type": "text/html" }).end(
|
|
83
|
+
`<form id=f method=post action="${target}"><input type=hidden name=manifest value="${esc}"></form><script>f.submit()</script>`);
|
|
84
|
+
});
|
|
85
|
+
const timer = setTimeout(() => finish(reject, new Error("manifest flow timed out")), timeoutMs);
|
|
86
|
+
server.on("error", (e) => finish(reject, e));
|
|
87
|
+
server.listen(0, "127.0.0.1", () => onListening?.(`http://127.0.0.1:${server.address().port}/`, server.address().port));
|
|
88
|
+
});
|
|
89
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
import { test } from "node:test";
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { generateKeyPairSync, createVerify } from "node:crypto";
|
|
6
|
+
import { readFileSync, statSync } from "node:fs";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { tmpDir } from "../tests/_tmp.mjs";
|
|
9
|
+
import { createAppJwt, mintInstallationToken, findInstallation, buildAppManifest, convertManifestCode, receiveManifestCode, PIPELINE_PERMISSIONS } from "./app-manifest.mjs";
|
|
10
|
+
import { authFromCli, resolveAuth, readState, statePath } from "./app-token.mjs";
|
|
11
|
+
|
|
12
|
+
const { privateKey, publicKey } = generateKeyPairSync("rsa", { modulusLength: 2048, privateKeyEncoding: { type: "pkcs8", format: "pem" }, publicKeyEncoding: { type: "spki", format: "pem" } });
|
|
13
|
+
const json = (body, status = 200) => ({ ok: status < 400, status, json: async () => body });
|
|
14
|
+
const NOW = Date.parse("2026-01-01T00:00:00Z");
|
|
15
|
+
|
|
16
|
+
test("App JWT is RS256, verifies, and expires within 10 minutes", () => {
|
|
17
|
+
const jwt = createAppJwt({ appId: 123, pem: privateKey, now: NOW });
|
|
18
|
+
const [h, p, sig] = jwt.split(".");
|
|
19
|
+
assert.equal(JSON.parse(Buffer.from(h, "base64url")).alg, "RS256");
|
|
20
|
+
const claims = JSON.parse(Buffer.from(p, "base64url"));
|
|
21
|
+
assert.equal(claims.iss, "123");
|
|
22
|
+
assert.ok(claims.exp - claims.iat <= 600);
|
|
23
|
+
assert.ok(createVerify("RSA-SHA256").update(`${h}.${p}`).verify(publicKey, Buffer.from(sig, "base64url")));
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
test("local mint is scoped to repository_ids and pipeline permissions", async () => {
|
|
27
|
+
let seen;
|
|
28
|
+
const r = await mintInstallationToken({ appId: 1, pem: privateKey, installationId: 55, repositoryIds: [9], now: NOW,
|
|
29
|
+
fetch: async (url, init) => { seen = { url, init }; return json({ token: "ghs_L", expires_at: "2026-01-01T01:00:00Z" }); } });
|
|
30
|
+
assert.equal(r.token, "ghs_L");
|
|
31
|
+
assert.equal(seen.url, "https://api.github.com/app/installations/55/access_tokens");
|
|
32
|
+
assert.match(seen.init.headers.Authorization, /^Bearer ey/);
|
|
33
|
+
assert.deepEqual(JSON.parse(seen.init.body), { permissions: PIPELINE_PERMISSIONS, repository_ids: [9] });
|
|
34
|
+
await assert.rejects(mintInstallationToken({ appId: 1, pem: privateKey, installationId: 1, fetch: async () => json({}, 401) }), /HTTP 401/);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
test("findInstallation and manifest conversion", async () => {
|
|
38
|
+
assert.equal(await findInstallation({ appId: 1, pem: privateKey, fetch: async () => json([{ id: 77 }]) }), 77);
|
|
39
|
+
assert.equal(await findInstallation({ appId: 1, pem: privateKey, fetch: async () => json([]) }), null);
|
|
40
|
+
const app = await convertManifestCode({ code: "c/1", fetch: async (u) => { assert.ok(u.endsWith("/app-manifests/c%2F1/conversions")); return json({ id: 5, slug: "mine", pem: "PEM" }); } });
|
|
41
|
+
assert.deepEqual(app, { appId: 5, slug: "mine", pem: "PEM" });
|
|
42
|
+
assert.equal(buildAppManifest({ redirectUrl: "http://127.0.0.1:1/callback" }).default_permissions.contents, "write");
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test("loopback receiver returns the code only for the matching state", async () => {
|
|
46
|
+
let base;
|
|
47
|
+
const p = receiveManifestCode({ state: "S1", manifest: (port) => buildAppManifest({ redirectUrl: `http://127.0.0.1:${port}/callback` }), onListening: (u) => (base = u) });
|
|
48
|
+
while (!base) await new Promise((r) => setTimeout(r, 5));
|
|
49
|
+
const page = await (await fetch(base)).text();
|
|
50
|
+
assert.match(page, /settings\/apps\/new\?state=S1/);
|
|
51
|
+
assert.equal((await fetch(`${base}callback?state=WRONG&code=x`)).status, 400);
|
|
52
|
+
assert.equal((await fetch(`${base}callback?state=S1&code=THECODE`)).status, 200);
|
|
53
|
+
assert.equal(await p, "THECODE");
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
test("auth login --byo end to end: manifest, conversion, PEM 0600, install lookup, local mint on refresh", async () => {
|
|
57
|
+
const env = { FORGE_HOME_DIR: tmpDir("byo-") };
|
|
58
|
+
const lines = [];
|
|
59
|
+
const fetchFn = async (url, init) => {
|
|
60
|
+
if (url.includes("/app-manifests/")) return json({ id: 5, slug: "mine", pem: privateKey });
|
|
61
|
+
if (url.endsWith("/app/installations")) return json([{ id: 88 }]);
|
|
62
|
+
if (url.endsWith("/access_tokens")) return json({ token: "ghs_BYO", expires_at: new Date(Date.now() + 3600000).toISOString() });
|
|
63
|
+
assert.fail(url);
|
|
64
|
+
};
|
|
65
|
+
const run = authFromCli(["login", "--byo"], { env, fetch: fetchFn, out: (m) => lines.push(m), sleep: async () => {},
|
|
66
|
+
openUrl: async (u) => { const state = (await (await fetch(u)).text()).match(/state=(\w+)/)[1]; await fetch(`${u}callback?state=${state}&code=abc`); } });
|
|
67
|
+
assert.equal(await run, 0);
|
|
68
|
+
const s = readState(env);
|
|
69
|
+
assert.deepEqual([s.mode, s.appId, s.slug, s.installationId], ["byo", 5, "mine", 88]);
|
|
70
|
+
assert.equal(statSync(join(env.FORGE_HOME_DIR, "app-byo.pem")).mode & 0o777, 0o600);
|
|
71
|
+
assert.equal(readFileSync(join(env.FORGE_HOME_DIR, "app-byo.pem"), "utf8"), privateKey);
|
|
72
|
+
assert.equal(statSync(statePath(env)).mode & 0o777, 0o600);
|
|
73
|
+
const r = await resolveAuth({ env, fetch: fetchFn });
|
|
74
|
+
assert.deepEqual([r.source, r.env.GH_TOKEN], ["byo", "ghs_BYO"]);
|
|
75
|
+
});
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* Client side of the installation-token broker (#5301, parent #5295). A stored App login yields a short-lived installation
|
|
5
|
+
* token that is handed to pipeline `gh` calls as `GH_TOKEN` in this process's env only: no `gh auth login`, no git
|
|
6
|
+
* credential helper (#4565). No login means no change; any failure falls back to the user's own `gh` auth with one warning.
|
|
7
|
+
*
|
|
8
|
+
* Broker contract (assumed, documented in docs/CONFIG.md): `POST {broker}/v1/token`, `Authorization: Bearer <user token>`,
|
|
9
|
+
* body `{installation_id, repository_ids, permissions}` → `{token, expires_at}`. Tokens are never logged.
|
|
10
|
+
*/
|
|
11
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
12
|
+
import { chmodSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
|
13
|
+
import { execFileSync } from "node:child_process";
|
|
14
|
+
import { join, dirname } from "node:path";
|
|
15
|
+
import { homedir } from "node:os";
|
|
16
|
+
import { PIPELINE_PERMISSIONS, API, mintInstallationToken, findInstallation, buildAppManifest, convertManifestCode, receiveManifestCode } from "./app-manifest.mjs";
|
|
17
|
+
|
|
18
|
+
export const REFRESH_BEFORE_MS = 10 * 60 * 1000;
|
|
19
|
+
const UA = { "User-Agent": "forgedock", Accept: "application/json", "Content-Type": "application/json" };
|
|
20
|
+
|
|
21
|
+
const homeDir = (env) => env.FORGE_HOME_DIR || join(homedir(), ".forge");
|
|
22
|
+
export const statePath = (env = process.env) => join(homeDir(env), "app-auth.json");
|
|
23
|
+
const pemPath = (env) => join(homeDir(env), "app-byo.pem");
|
|
24
|
+
|
|
25
|
+
export function readState(env = process.env) {
|
|
26
|
+
try { return JSON.parse(readFileSync(statePath(env), "utf8")); } catch { return null; }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function writeSecret(path, text) {
|
|
30
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
31
|
+
writeFileSync(path, text, { mode: 0o600 });
|
|
32
|
+
chmodSync(path, 0o600);
|
|
33
|
+
}
|
|
34
|
+
export const writeState = (state, env = process.env) => writeSecret(statePath(env), JSON.stringify(state, null, 2));
|
|
35
|
+
|
|
36
|
+
export function clearState(env = process.env) {
|
|
37
|
+
for (const p of [statePath(env), pemPath(env)]) try { unlinkSync(p); } catch { /* absent */ }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The broker URL: `FORGEDOCK_BROKER_URL`, else the one stored at login. */
|
|
41
|
+
export const brokerUrl = (env = process.env, state = null) => (env.FORGEDOCK_BROKER_URL || state?.brokerUrl || "").replace(/\/+$/, "");
|
|
42
|
+
|
|
43
|
+
/** GitHub App device flow (client id only). `onCode({userCode, verificationUri})` shows the code to the user. */
|
|
44
|
+
export async function deviceFlowLogin({ clientId, fetch: fetchFn = fetch, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), onCode, now = Date.now }) {
|
|
45
|
+
const post = async (url, body) => (await fetchFn(url, { method: "POST", headers: UA, body: JSON.stringify(body) })).json();
|
|
46
|
+
const dc = await post("https://github.com/login/device/code", { client_id: clientId });
|
|
47
|
+
if (!dc?.device_code) throw new Error(`device flow did not start: ${dc?.error ?? "no device code"}`);
|
|
48
|
+
onCode?.({ userCode: dc.user_code, verificationUri: dc.verification_uri });
|
|
49
|
+
let interval = (dc.interval ?? 5) * 1000;
|
|
50
|
+
const deadline = now() + (dc.expires_in ?? 900) * 1000;
|
|
51
|
+
while (now() < deadline) {
|
|
52
|
+
await sleep(interval);
|
|
53
|
+
const t = await post("https://github.com/login/oauth/access_token",
|
|
54
|
+
{ client_id: clientId, device_code: dc.device_code, grant_type: "urn:ietf:params:oauth:grant-type:device_code" });
|
|
55
|
+
if (t?.access_token) return t.access_token;
|
|
56
|
+
if (t?.error === "slow_down") interval += 5000;
|
|
57
|
+
else if (t?.error && t.error !== "authorization_pending") throw new Error(`device flow ${t.error}`);
|
|
58
|
+
}
|
|
59
|
+
throw new Error("device flow code expired");
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Installations the signed-in user can reach, and the repo ids of one. */
|
|
63
|
+
async function userGet(fetchFn, userToken, path) {
|
|
64
|
+
const res = await fetchFn(`${API}${path}`, { headers: { ...UA, Authorization: `Bearer ${userToken}`, Accept: "application/vnd.github+json" } });
|
|
65
|
+
if (!res.ok) throw new Error(`GET ${path} failed (HTTP ${res.status})`);
|
|
66
|
+
return res.json();
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export async function discoverInstallation({ userToken, installationId, fetch: fetchFn = fetch }) {
|
|
70
|
+
let id = installationId;
|
|
71
|
+
if (!id) {
|
|
72
|
+
const list = (await userGet(fetchFn, userToken, "/user/installations"))?.installations ?? [];
|
|
73
|
+
if (!list.length) throw new Error("the signed-in user has no installation of the App; install it first");
|
|
74
|
+
id = list[0].id;
|
|
75
|
+
}
|
|
76
|
+
const repos = (await userGet(fetchFn, userToken, `/user/installations/${id}/repositories?per_page=100`))?.repositories ?? [];
|
|
77
|
+
return { installationId: id, repositoryIds: repos.map((r) => r.id) };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The user token travels as a Bearer: the broker must be https (plain http only for a loopback host). */
|
|
81
|
+
export function assertSecureBroker(url) {
|
|
82
|
+
let u;
|
|
83
|
+
try { u = new URL(url); } catch { throw new Error(`broker URL is not a valid URL: ${url}`); }
|
|
84
|
+
if (u.protocol !== "https:" && !(u.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(u.hostname))) throw new Error("broker URL must be https (the GitHub user token is sent as a Bearer)");
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Ask the broker for a scoped installation token. @returns {{token:string, expiresAt:string}} */
|
|
88
|
+
export async function mintViaBroker({ brokerUrl: url, userToken, installationId, repositoryIds, permissions = PIPELINE_PERMISSIONS, fetch: fetchFn = fetch }) {
|
|
89
|
+
assertSecureBroker(url);
|
|
90
|
+
const res = await fetchFn(`${url}/v1/token`, {
|
|
91
|
+
method: "POST", headers: { ...UA, Authorization: `Bearer ${userToken}` },
|
|
92
|
+
body: JSON.stringify({ installation_id: installationId, repository_ids: repositoryIds, permissions }),
|
|
93
|
+
});
|
|
94
|
+
if (!res.ok) throw new Error(`broker returned HTTP ${res.status}`);
|
|
95
|
+
const j = await res.json();
|
|
96
|
+
if (!j?.token || !j?.expires_at) throw new Error("broker returned no token");
|
|
97
|
+
return { token: j.token, expiresAt: j.expires_at };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Decide the env for pipeline `gh` calls. @returns {{env:object, source:"broker"|"byo"|"personal", warning?:string, expiresAt?:string}}
|
|
102
|
+
* `env` is `{GH_TOKEN}` only when an App identity is active; otherwise `{}` (the user's own auth, unchanged).
|
|
103
|
+
*/
|
|
104
|
+
export async function resolveAuth({ env = process.env, now = Date.now(), fetch: fetchFn = fetch, persist = true } = {}) {
|
|
105
|
+
const personal = { env: {}, source: "personal" };
|
|
106
|
+
if (env.FORGEDOCK_NO_APP_AUTH === "1") return personal;
|
|
107
|
+
const state = readState(env);
|
|
108
|
+
if (!state?.mode) return personal;
|
|
109
|
+
const exp = Date.parse(state.expiresAt);
|
|
110
|
+
if (state.token && Number.isFinite(exp) && exp - now > REFRESH_BEFORE_MS) return { env: { GH_TOKEN: state.token }, source: state.mode, expiresAt: state.expiresAt };
|
|
111
|
+
try {
|
|
112
|
+
let minted;
|
|
113
|
+
if (state.mode === "byo") {
|
|
114
|
+
minted = await mintInstallationToken({ appId: state.appId, pem: readFileSync(pemPath(env), "utf8"), installationId: state.installationId, repositoryIds: state.repositoryIds, fetch: fetchFn, now });
|
|
115
|
+
} else {
|
|
116
|
+
const url = brokerUrl(env, state);
|
|
117
|
+
if (!url) throw new Error("no broker URL configured");
|
|
118
|
+
minted = await mintViaBroker({ brokerUrl: url, userToken: state.userToken, installationId: state.installationId, repositoryIds: state.repositoryIds, fetch: fetchFn });
|
|
119
|
+
}
|
|
120
|
+
if (persist) try { writeState({ ...state, ...minted }, env); } catch { /* cache only */ }
|
|
121
|
+
return { env: { GH_TOKEN: minted.token }, source: state.mode, expiresAt: minted.expiresAt };
|
|
122
|
+
} catch (e) {
|
|
123
|
+
return { ...personal, warning: `ForgeDock: App token unavailable (${String(e?.message ?? e).slice(0, 120)}); using your own gh auth.` };
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// The token this module last wrote to an env: a GH_TOKEN that differs from it was exported by the operator and is never touched (#5381).
|
|
128
|
+
// Ownership crosses exec as a fingerprint in FORGEDOCK_APP_TOKEN_FP (#5392): a child that inherits the env (auto-spawned schedd,
|
|
129
|
+
// its version respawn, a spawned watch) recognises the App token as ForgeDock's and keeps refreshing it. Never the raw token.
|
|
130
|
+
export const OWNED_FP_VAR = "FORGEDOCK_APP_TOKEN_FP";
|
|
131
|
+
let ownedToken = null;
|
|
132
|
+
let ownedExpiry = 0;
|
|
133
|
+
const fingerprint = (token) => createHash("sha256").update(String(token)).digest("hex").slice(0, 16);
|
|
134
|
+
const inheritedOwned = (env) => Boolean(env.GH_TOKEN) && Boolean(env[OWNED_FP_VAR]) && fingerprint(env.GH_TOKEN) === env[OWNED_FP_VAR];
|
|
135
|
+
const operatorOwns = (env) => Boolean(env.GH_TOKEN) && env.GH_TOKEN !== ownedToken && !inheritedOwned(env);
|
|
136
|
+
|
|
137
|
+
function adopt(env, r) {
|
|
138
|
+
if (!r.env.GH_TOKEN) return;
|
|
139
|
+
env.GH_TOKEN = r.env.GH_TOKEN;
|
|
140
|
+
env[OWNED_FP_VAR] = fingerprint(r.env.GH_TOKEN);
|
|
141
|
+
ownedToken = r.env.GH_TOKEN;
|
|
142
|
+
ownedExpiry = Date.parse(r.expiresAt) || 0;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function drop(env) {
|
|
146
|
+
delete env.GH_TOKEN;
|
|
147
|
+
delete env[OWNED_FP_VAR];
|
|
148
|
+
ownedToken = null;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Startup hook: put the App token in `env` (the CLI process env, inherited by child `gh` calls). Prints one warning on fallback. An operator-exported GH_TOKEN wins. */
|
|
152
|
+
export async function applyAuthEnv({ env = process.env, warn = (m) => process.stderr.write(`${m}\n`), ...rest } = {}) {
|
|
153
|
+
if (operatorOwns(env)) return { env: {}, source: "personal", operator: true };
|
|
154
|
+
const inherited = Boolean(env.GH_TOKEN) && env.GH_TOKEN !== ownedToken; // not operator-owned here, so a token a parent ForgeDock set
|
|
155
|
+
const r = await resolveAuth({ env, ...rest });
|
|
156
|
+
if (r.env.GH_TOKEN) adopt(env, r);
|
|
157
|
+
else if (inherited) drop(env); // the inherited App token can no longer be refreshed: fall back to the user's own gh auth
|
|
158
|
+
if (r.warning) warn(r.warning);
|
|
159
|
+
return r;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Keep the App token in `env` fresh for long-running commands (#5381): a timer re-resolves it before expiry and reassigns
|
|
164
|
+
* `env.GH_TOKEN`, which later `gh` calls and lanes inherit. No-op unless this module owns the env token. @returns {() => void} stop
|
|
165
|
+
*/
|
|
166
|
+
export function startAuthRefresh({ env = process.env, now = Date.now, fetch: fetchFn = fetch, setTimer = setTimeout, clearTimer = clearTimeout, warn = (m) => process.stderr.write(`${m}\n`) } = {}) {
|
|
167
|
+
if (!ownedToken || operatorOwns(env)) return () => {};
|
|
168
|
+
let timer = null;
|
|
169
|
+
let stopped = false;
|
|
170
|
+
let warned = false;
|
|
171
|
+
const schedule = (ms) => {
|
|
172
|
+
if (stopped) return;
|
|
173
|
+
timer = setTimer(tick, Math.max(30000, ms));
|
|
174
|
+
timer?.unref?.();
|
|
175
|
+
};
|
|
176
|
+
const tick = async () => {
|
|
177
|
+
if (stopped || operatorOwns(env)) return;
|
|
178
|
+
const t = now();
|
|
179
|
+
const r = await resolveAuth({ env, now: t, fetch: fetchFn });
|
|
180
|
+
if (r.env.GH_TOKEN) {
|
|
181
|
+
adopt(env, r);
|
|
182
|
+
return schedule(ownedExpiry - now() - REFRESH_BEFORE_MS + 1000);
|
|
183
|
+
}
|
|
184
|
+
if (!warned && r.warning) { warned = true; warn(r.warning); }
|
|
185
|
+
if (ownedExpiry <= t) drop(env); // expired: let gh fall back to the user's own auth
|
|
186
|
+
schedule(60000);
|
|
187
|
+
};
|
|
188
|
+
schedule(ownedExpiry - now() - REFRESH_BEFORE_MS + 1000);
|
|
189
|
+
return () => { stopped = true; if (timer) clearTimer(timer); };
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const defaultGh = (args, env) => execFileSync("gh", args, { encoding: "utf8", env: { ...process.env, ...env }, stdio: ["ignore", "pipe", "ignore"], timeout: 15000 });
|
|
193
|
+
|
|
194
|
+
/** Doctor Check 12 input: the active identity, its source and rate limit. @returns {{configured:boolean, status?:"pass"|"warn", detail?:string}} */
|
|
195
|
+
export async function doctorAppAuth({ env = process.env, gh = defaultGh, ...rest } = {}) {
|
|
196
|
+
const state = readState(env);
|
|
197
|
+
if (!state?.mode) return { configured: false };
|
|
198
|
+
const r = await resolveAuth({ env, persist: true, ...rest });
|
|
199
|
+
let limit = "unknown";
|
|
200
|
+
try { limit = String(JSON.parse(gh(["api", "rate_limit"], r.env)).resources.core.limit); } catch { /* offline */ }
|
|
201
|
+
if (r.source === "personal") {
|
|
202
|
+
let who = "unknown";
|
|
203
|
+
try { who = gh(["api", "user", "--jq", ".login"], {}).trim() || who; } catch { /* no gh auth */ }
|
|
204
|
+
return { configured: true, status: "warn", detail: `App login stored but not active, using personal gh auth as ${who} (core.limit ${limit}): ${r.warning ?? "token not refreshed"}` };
|
|
205
|
+
}
|
|
206
|
+
const who = state.slug ? `${state.slug}[bot]` : "App installation bot";
|
|
207
|
+
return { configured: true, status: "pass", detail: `${who} active via ${r.source} (core.limit ${limit}, token expires ${r.expiresAt})` };
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** `forgedock auth login|status|logout [--byo] [--broker-url U] [--client-id ID] [--installation N] [--org O]`. @returns exit code */
|
|
211
|
+
export async function authFromCli(args, { env = process.env, out = (m) => console.log(m), fetch: fetchFn = fetch, ...io } = {}) {
|
|
212
|
+
const [sub, ...rest] = args;
|
|
213
|
+
const flag = (n) => { const i = rest.indexOf(`--${n}`); return i >= 0 ? rest[i + 1] : undefined; };
|
|
214
|
+
if (sub === "logout") { clearState(env); out("ForgeDock App login removed; pipeline calls use your own gh auth."); return 0; }
|
|
215
|
+
if (sub === "status") {
|
|
216
|
+
const d = await doctorAppAuth({ env, fetch: fetchFn, ...io });
|
|
217
|
+
out(d.configured ? `${d.status}: ${d.detail}` : "No App login; pipeline calls use your own gh auth.");
|
|
218
|
+
return d.configured && d.status !== "pass" ? 1 : 0;
|
|
219
|
+
}
|
|
220
|
+
if (sub !== "login") { out("usage: forgedock auth login [--byo] [--broker-url URL] [--client-id ID] [--installation N] [--org ORG] | status | logout"); return 1; }
|
|
221
|
+
try {
|
|
222
|
+
if (rest.includes("--byo")) return await byoLogin({ env, out, fetchFn, org: flag("org"), installationId: flag("installation"), ...io });
|
|
223
|
+
const url = brokerUrl(env) || (flag("broker-url") ?? "").replace(/\/+$/, "");
|
|
224
|
+
const clientId = flag("client-id") || env.FORGEDOCK_APP_CLIENT_ID;
|
|
225
|
+
if (!url || !clientId) throw new Error("set --broker-url and --client-id (or FORGEDOCK_BROKER_URL and FORGEDOCK_APP_CLIENT_ID)");
|
|
226
|
+
assertSecureBroker(url);
|
|
227
|
+
const userToken = await deviceFlowLogin({ clientId, fetch: fetchFn, sleep: io.sleep, onCode: ({ userCode, verificationUri }) => out(`Open ${verificationUri} and enter code ${userCode}`) });
|
|
228
|
+
const inst = await discoverInstallation({ userToken, installationId: flag("installation"), fetch: fetchFn });
|
|
229
|
+
writeState({ mode: "broker", brokerUrl: url, clientId, userToken, ...inst }, env);
|
|
230
|
+
out("Signed in. Run `forgedock doctor` to see the active identity.");
|
|
231
|
+
return 0;
|
|
232
|
+
} catch (e) {
|
|
233
|
+
out(`auth login failed: ${String(e?.message ?? e)}`);
|
|
234
|
+
return 1;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async function byoLogin({ env, out, fetchFn, org, installationId, openUrl, ...io }) {
|
|
239
|
+
const state = randomBytes(16).toString("hex");
|
|
240
|
+
const code = await receiveManifestCode({
|
|
241
|
+
state, org, manifest: (port) => buildAppManifest({ redirectUrl: `http://127.0.0.1:${port}/callback` }),
|
|
242
|
+
onListening: (url) => (openUrl ? openUrl(url) : out(`Open ${url} to create your GitHub App`)),
|
|
243
|
+
});
|
|
244
|
+
const app = await convertManifestCode({ code, fetch: fetchFn });
|
|
245
|
+
writeSecret(pemPath(env), app.pem);
|
|
246
|
+
out(`App ${app.slug} created. Install it: https://github.com/apps/${app.slug}/installations/new`);
|
|
247
|
+
let id = installationId;
|
|
248
|
+
for (let i = 0; !id && i < (io.attempts ?? 60); i++) {
|
|
249
|
+
id = await findInstallation({ appId: app.appId, pem: app.pem, fetch: fetchFn }).catch(() => null);
|
|
250
|
+
if (!id) await (io.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(5000);
|
|
251
|
+
}
|
|
252
|
+
if (!id) throw new Error("App not installed yet; rerun `forgedock auth login --byo --installation N` after installing");
|
|
253
|
+
writeState({ mode: "byo", appId: app.appId, slug: app.slug, installationId: id }, env);
|
|
254
|
+
out("BYO App configured; tokens are minted locally.");
|
|
255
|
+
return 0;
|
|
256
|
+
}
|