@tama-create/sf-tools 0.0.0-stage → 1.4.0-dev.2

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.
Files changed (118) hide show
  1. package/LICENSE +24 -0
  2. package/README.md +212 -2
  3. package/bin/sft.js +22 -0
  4. package/dist/cli.js +35 -0
  5. package/dist/commands/admin.js +46 -0
  6. package/dist/commands/check.js +20 -0
  7. package/dist/commands/ci.js +123 -0
  8. package/dist/commands/deploy.js +31 -0
  9. package/dist/commands/doctor.js +11 -0
  10. package/dist/commands/dryrun.js +17 -0
  11. package/dist/commands/hook.js +46 -0
  12. package/dist/commands/index.js +36 -0
  13. package/dist/commands/job.js +31 -0
  14. package/dist/commands/launcher.js +40 -0
  15. package/dist/commands/log.js +58 -0
  16. package/dist/commands/metasync.js +21 -0
  17. package/dist/commands/pr.js +32 -0
  18. package/dist/commands/project.js +93 -0
  19. package/dist/commands/push.js +16 -0
  20. package/dist/commands/release.js +19 -0
  21. package/dist/commands/start.js +19 -0
  22. package/dist/commands/switch-org.js +12 -0
  23. package/dist/commands/update-cli.js +11 -0
  24. package/dist/commands/version.js +18 -0
  25. package/dist/core/admin-clone.js +79 -0
  26. package/dist/core/ai-answers.js +40 -0
  27. package/dist/core/branches.js +88 -0
  28. package/dist/core/check-targets.js +170 -0
  29. package/dist/core/check.js +34 -0
  30. package/dist/core/ci-check-branch.js +150 -0
  31. package/dist/core/ci-login-steps.js +73 -0
  32. package/dist/core/ci-release-steps.js +193 -0
  33. package/dist/core/ci-sequence-steps.js +188 -0
  34. package/dist/core/ci-validate-steps.js +140 -0
  35. package/dist/core/command.js +25 -0
  36. package/dist/core/create-connect.js +519 -0
  37. package/dist/core/create-setup.js +314 -0
  38. package/dist/core/create-state.js +82 -0
  39. package/dist/core/delegate.js +45 -0
  40. package/dist/core/deploy.js +66 -0
  41. package/dist/core/diag.js +200 -0
  42. package/dist/core/doctor.js +211 -0
  43. package/dist/core/eca.js +259 -0
  44. package/dist/core/exit-codes.js +12 -0
  45. package/dist/core/gh-identity.js +46 -0
  46. package/dist/core/hook-install.js +130 -0
  47. package/dist/core/hook.js +116 -0
  48. package/dist/core/identity.js +48 -0
  49. package/dist/core/job.js +243 -0
  50. package/dist/core/launcher-status.js +184 -0
  51. package/dist/core/lines.js +25 -0
  52. package/dist/core/log-auto.js +56 -0
  53. package/dist/core/log-box.js +85 -0
  54. package/dist/core/log-collector.js +370 -0
  55. package/dist/core/log-format.js +44 -0
  56. package/dist/core/log-pull.js +565 -0
  57. package/dist/core/log-select.js +126 -0
  58. package/dist/core/log-session.js +362 -0
  59. package/dist/core/log-start.js +421 -0
  60. package/dist/core/log-status.js +223 -0
  61. package/dist/core/log-summarize.js +127 -0
  62. package/dist/core/logger.js +71 -0
  63. package/dist/core/login-url.js +50 -0
  64. package/dist/core/manifest-build.js +118 -0
  65. package/dist/core/mask.js +70 -0
  66. package/dist/core/metadata-types.js +79 -0
  67. package/dist/core/metasync.js +684 -0
  68. package/dist/core/org.js +115 -0
  69. package/dist/core/origin.js +62 -0
  70. package/dist/core/package-xml.js +157 -0
  71. package/dist/core/pr.js +199 -0
  72. package/dist/core/project-create.js +733 -0
  73. package/dist/core/project-reconnect.js +126 -0
  74. package/dist/core/project-status.js +235 -0
  75. package/dist/core/project-tier.js +374 -0
  76. package/dist/core/project-verify.js +517 -0
  77. package/dist/core/promote-check.js +380 -0
  78. package/dist/core/promote.js +141 -0
  79. package/dist/core/push.js +152 -0
  80. package/dist/core/release.js +256 -0
  81. package/dist/core/scoped-box.js +29 -0
  82. package/dist/core/start.js +155 -0
  83. package/dist/core/switch-org.js +49 -0
  84. package/dist/core/test-types.js +212 -0
  85. package/dist/core/toolbox.js +4 -0
  86. package/dist/core/update-cli.js +156 -0
  87. package/dist/core/update-secret.js +301 -0
  88. package/dist/core/update-workflows.js +132 -0
  89. package/dist/core/verify-gh.js +286 -0
  90. package/dist/core/verify-samples.js +152 -0
  91. package/dist/core/windows-shim.js +21 -0
  92. package/dist/io/capability-file.js +11 -0
  93. package/dist/io/create-deps.js +68 -0
  94. package/dist/io/doctor-deps.js +32 -0
  95. package/dist/io/hook-install-deps.js +11 -0
  96. package/dist/io/job-deps.js +31 -0
  97. package/dist/io/key-file.js +17 -0
  98. package/dist/io/keys.js +161 -0
  99. package/dist/io/log-deps.js +106 -0
  100. package/dist/io/metasync-deps.js +21 -0
  101. package/dist/io/open-browser.js +21 -0
  102. package/dist/io/package-version.js +10 -0
  103. package/dist/io/pinned-project.js +111 -0
  104. package/dist/io/promote-deps.js +27 -0
  105. package/dist/io/push-refs.js +20 -0
  106. package/dist/io/resolve.js +74 -0
  107. package/dist/io/run.js +201 -0
  108. package/dist/io/switch-org-deps.js +10 -0
  109. package/dist/io/temp-dir.js +10 -0
  110. package/dist/io/tool-versions.js +14 -0
  111. package/dist/io/toolbox.js +68 -0
  112. package/dist/io/update-cli-deps.js +75 -0
  113. package/dist/io/update-secret-deps.js +27 -0
  114. package/dist/launch.js +152 -0
  115. package/dist/ui/confirm.js +18 -0
  116. package/dist/ui/launcher.js +132 -0
  117. package/dist/ui/prompt.js +66 -0
  118. package/package.json +37 -4
@@ -0,0 +1,519 @@
1
+ // sft project create の Phase 6〜10(phases/init/06〜10 の移し先)。
2
+ // 6. GitHub の Token: Classic の PAT(repo・workflow)を作るページを開き、貼り付けてもらって確かめる(ログイン名・X-OAuth-Scopes・
3
+ // リポジトリの管理者)。3 回まで。Secret PAT_TOKEN に標準入力で登録し、Phase 8 の push のため、状態ファイルに PAT_TOKEN_VALUE を追記する
4
+ // 7. Slack: App の作り方を出してページを開く → Bot Token(xoxb-。* で表示)→ Secret SLACK_BOT_TOKEN。チャンネル ID(C… / G…)→
5
+ // Variable SLACK_CHANNEL_ID。Bot の招待(/invite @sf-notify-<XXXX>)を案内して Enter を待つ
6
+ // 8. 初回のコミット: git add -A → 差分があれば commit(pre-commit フックは動く)→ PAT で main を push → branches.txt の main 以外の
7
+ // ブランチを、なければ作って push → 状態ファイルから PAT_TOKEN_VALUE の行を消す(残れば止める)→ フックを入れ直す。
8
+ // PAT は、URL・引数・.git/config に入れない(git の認証ヘルパーを、この 1 回だけ差し替え、環境変数 SF_INIT_PUSH_TOKEN から渡す)
9
+ // 9. リポジトリの設定: gh repo edit(既定のブランチ・マージの方法など)・Ruleset protect-main / protect-staging(同名を消してから作る。
10
+ // 必須のチェックは、ジョブ名だけ)・開発版のときだけ Variable SF_TOOLS_BRANCH=development。失敗は WARNING で続ける
11
+ // 10. Salesforce の接続: ~/.sf-jwt/<REPO_NAME>/server.key・server.crt(あれば再利用を聞く。発行先が空なら証明書だけ作り直す)→
12
+ // SF_PRIVATE_KEY(base64 の 1 行。標準入力)→ 段階ごとに registerJwtSecretEca(eca.ts)。前回完了した段階は飛ばす(進捗の記録と、
13
+ // Secret SF_CONSUMER_KEY_<接尾辞> があるとき。鍵を作り直したときは飛ばさない)
14
+ import { requiredStatusCheckNames } from "./branches.js";
15
+ import { BRANCHES_REL, nonMainBranches, repoBox } from "./create-setup.js";
16
+ import { appendState, CreateStop, confirmYes, dropStateLines, exec, must, state } from "./create-state.js";
17
+ import { setupHooks } from "./doctor.js";
18
+ import { registerJwtSecretEca } from "./eca.js";
19
+ import { base64 } from "./verify-gh.js";
20
+ const lines = (box, ls) => {
21
+ for (const l of ls)
22
+ box.output.err(l);
23
+ };
24
+ /** Classic の PAT の作成ページ(説明・権限・期限を、URL で入れておく) */
25
+ export const patNewUrl = (project) => `https://github.com/settings/tokens/new?description=sf-metasync-${project}&scopes=repo,workflow&default_expires_at=none`;
26
+ /** Token を確かめる。使えなければ、理由と直し方を出して false(Token は GH_TOKEN で渡し、引数に出さない) */
27
+ export async function verifyPat(box, token, repo, project) {
28
+ const w = (s) => box.output.err(`[WARNING] ${s}`);
29
+ const env = { GH_TOKEN: token };
30
+ const url = patNewUrl(project);
31
+ const login = (await exec(box, "gh", ["api", "user", "--jq", ".login"], { env }))?.stdout.trim() ?? "";
32
+ if (login === "") {
33
+ w("Token を確認できませんでした。コピーした Token が、途中で切れていないか、確認してください(有効期限切れ・通信の失敗の可能性もあります)。");
34
+ return false;
35
+ }
36
+ const head = (await exec(box, "gh", ["api", "user", "--include"], { env }))?.stdout.replace(/\r/g, "") ?? "";
37
+ const scopeLine = head.split("\n").find((l) => /^x-oauth-scopes:/i.test(l));
38
+ const scopes = scopeLine === undefined ? "" : scopeLine.replace(/^[^:]*:\s*/, "").replace(/ /g, "");
39
+ if (scopes === "") {
40
+ w(`この Token は、種類が違います(Classic の Token が必要です)。作成ページから、作り直してください: ${url}`);
41
+ return false;
42
+ }
43
+ const list = scopes.split(",");
44
+ for (const need of ["repo", "workflow"])
45
+ if (!list.includes(need)) {
46
+ w(`この Token には、「${need}」の権限がありません。作成ページで、${need} にチェックが入っていることを確認して、作り直してください: ${url}`);
47
+ return false;
48
+ }
49
+ const admin = (await exec(box, "gh", ["api", `repos/${repo}`, "--jq", ".permissions.admin"], { env }))?.stdout.trim() ?? "";
50
+ if (admin !== "true") {
51
+ w(`この Token は ${login} さんのものですが、${repo} の管理者ではありません。${repo.split("/")[0]}(組織の場合は、その組織の管理者)のアカウントで、作り直してください: ${url}`);
52
+ return false;
53
+ }
54
+ box.output.err(`[SUCCESS] Token を確認できました(${login} さんの Token / 権限: ${scopes})。`);
55
+ return true;
56
+ }
57
+ export async function phasePatToken(ctx) {
58
+ const box = ctx.admin;
59
+ const s = state(ctx, "REPO_FULL_NAME", "PROJECT_NAME");
60
+ const repo = s.REPO_FULL_NAME;
61
+ const project = s.PROJECT_NAME;
62
+ const owner = repo.split("/")[0] ?? "";
63
+ const url = patNewUrl(project);
64
+ box.output.err("[HEADER] PAT_TOKEN の設定");
65
+ lines(box, [
66
+ "",
67
+ " GitHub の Token(アクセス用の合言葉)を作って、登録します。",
68
+ " 自動で動くワークフローが、このリポジトリを更新するために必要です。",
69
+ " (sf-tools が公開リポジトリであることとは、関係ありません)",
70
+ "",
71
+ ` 【作るアカウント】 ${owner}`,
72
+ " ・組織のリポジトリの場合は、その組織の管理者のアカウントです",
73
+ " ・ブラウザが別のアカウントでログインしている場合は、先に、切り替えてください",
74
+ "",
75
+ " いま、ブラウザで Token の作成ページを開きます。やることは 3 つです。",
76
+ " 1. ページの一番下の「Generate token」ボタンを押す",
77
+ " (入力済みの内容は、そのままで構いません)",
78
+ ` Note: sf-metasync-${project} / Expiration: No expiration / Scopes: repo, workflow`,
79
+ " 2. 表示された Token(ghp_ で始まる文字列)を、コピーする",
80
+ " ※ Token は、この 1 回しか表示されません",
81
+ " 3. このターミナルに戻って、貼り付けて、Enter を押す",
82
+ " ※ 貼り付けると、文字の数だけ * が並びます(Token の中身は、画面に出ません)。そのまま Enter を押してください",
83
+ " ※ Git Bash は、右クリックで貼り付けます(Shift+Insert でも貼り付けられます)",
84
+ "",
85
+ " ブラウザが開かない場合は、次の URL を開いてください:",
86
+ ` ${url}`,
87
+ "",
88
+ " (以前に作って、保存してある Token があれば、それを貼り付けても構いません)",
89
+ "",
90
+ ]);
91
+ await ctx.deps.openBrowser(url).catch(() => undefined);
92
+ let token = "";
93
+ for (let attempt = 1;; attempt++) {
94
+ const v = await ctx.deps.prompts.secret(" ▶ ここに Token を貼り付けて、Enter を押してください(* で表示されます・q で中断):");
95
+ if (v === "quit")
96
+ throw new CreateStop(1, "中断しました。");
97
+ box.output.err("[INFO] Token を受け取りました。GitHub に問い合わせて、確認しています...");
98
+ if (await verifyPat(box, v, repo, project)) {
99
+ token = v;
100
+ break;
101
+ }
102
+ if (attempt >= 3)
103
+ throw new CreateStop(1, `PAT_TOKEN の検証に ${attempt} 回失敗しました。`);
104
+ box.output.err(`[WARNING] もう一度、貼り付けてください(あと ${3 - attempt} 回)。Token を作り直した場合は、新しい Token を貼り付けてください。`);
105
+ }
106
+ box.output.err("");
107
+ await must(box, "gh", ["secret", "set", "PAT_TOKEN", "-R", repo], "PAT_TOKEN の登録に失敗しました。", { input: token });
108
+ // Phase 8 の push で使う(Phase 8 が push のあとに消す。後処理でも消す)
109
+ appendState(ctx, "PAT_TOKEN_VALUE", token);
110
+ box.output.err("[SUCCESS] 完了: PAT_TOKEN の設定 OK。");
111
+ }
112
+ export async function phaseSlack(ctx) {
113
+ const box = ctx.admin;
114
+ const s = state(ctx, "REPO_FULL_NAME", "PROJECT_NAME");
115
+ const repo = s.REPO_FULL_NAME;
116
+ const project = s.PROJECT_NAME;
117
+ const { prompts } = ctx.deps;
118
+ box.output.err("[HEADER] Slack 連携の設定");
119
+ lines(box, [
120
+ "",
121
+ " ブラウザで Slack API ページを開きます。",
122
+ " 以下の手順で Bot Token を取得してください:",
123
+ "",
124
+ " 1. 「Create New App」→「From scratch」をクリック",
125
+ " 2. 以下を設定して「Create App」をクリック:",
126
+ ` App Name : sf-notify-${project}`,
127
+ " Workspace : 通知先のワークスペースを選択",
128
+ " 3. 左メニュー「OAuth & Permissions」をクリック",
129
+ " 4. 「ボットトークンのスコープ」→「OAuth スコープを追加する」をクリック",
130
+ " chat:write と入力して追加",
131
+ " 5. 左メニュー「Install App」→「Install to <ワークスペース名>」をクリック",
132
+ " 6. 「許可する」をクリック",
133
+ " → 「Installed App Settings」ページが表示される",
134
+ " 7. ページ内「Bot User OAuth Token」(xoxb-...)をコピー",
135
+ "",
136
+ ]);
137
+ await ctx.deps.openBrowser("https://api.slack.com/apps").catch(() => undefined);
138
+ if (!(await prompts.enter("Bot Token を取得したら Enter を押してください...")))
139
+ throw new CreateStop(1, "中断しました。");
140
+ let token = "";
141
+ for (;;) {
142
+ const v = await prompts.secret(" Bot User OAuth Token を貼り付けてください(* で表示されます・q で中断):");
143
+ if (v === "quit")
144
+ throw new CreateStop(1, "中断しました。");
145
+ if (/^xoxb-[A-Za-z0-9-]+$/.test(v)) {
146
+ token = v;
147
+ break;
148
+ }
149
+ box.output.err("[WARNING] Bot User OAuth Token の形式ではありません(xoxb- で始まる文字列です)。入力し直してください。");
150
+ }
151
+ box.output.err("");
152
+ await must(box, "gh", ["secret", "set", "SLACK_BOT_TOKEN", "-R", repo], "SLACK_BOT_TOKEN の登録に失敗しました。", { input: token });
153
+ box.output.err("[SUCCESS] SLACK_BOT_TOKEN を登録しました。");
154
+ lines(box, [
155
+ "",
156
+ " 通知先 Slack チャンネルの ID を入力します。",
157
+ "",
158
+ " 通知先は、このプロジェクトを使う全員が参加する共有チャンネルにしてください。",
159
+ " チャンネルがまだ無い場合は、Slack で先に作成しておいてください(既存のチャンネルでも構いません)。",
160
+ " ダイレクトメッセージ(DM)は、本人にしか届かないため使えません。",
161
+ "",
162
+ " 確認方法: チャンネルを開く → チャンネル名をクリック → 最下部に「チャンネル ID」",
163
+ " C から始まる文字列(例: C01ABCDEFGH)",
164
+ "",
165
+ ]);
166
+ // 通知が共有されない D(DM)・U(ユーザー)などは受け付けない
167
+ let channel = "";
168
+ for (;;) {
169
+ const v = await prompts.text(" チャンネル ID(q で中断):");
170
+ if (v === "quit")
171
+ throw new CreateStop(1, "中断しました。");
172
+ if (/^[CG][A-Z0-9]{8,}$/.test(v)) {
173
+ channel = v;
174
+ break;
175
+ }
176
+ box.output.err(`[WARNING] 「${v}」はチャンネル ID の形式ではありません(チャンネル ID は C または G で始まります。D はダイレクトメッセージ、U はユーザーの ID で、通知先には使えません)。入力し直してください。`);
177
+ }
178
+ await must(box, "gh", ["variable", "set", "SLACK_CHANNEL_ID", "-R", repo], "SLACK_CHANNEL_ID の登録に失敗しました。", { input: channel });
179
+ box.output.err("[SUCCESS] SLACK_CHANNEL_ID を登録しました。");
180
+ box.output.err("");
181
+ box.output.err("[WARNING] 【重要】Slack チャンネルへの Bot 招待が必要です");
182
+ lines(box, [
183
+ " 通知先チャンネルで以下のコマンドを実行してください:",
184
+ "",
185
+ ` /invite @sf-notify-${project}`,
186
+ "",
187
+ " Bot がチャンネルに参加していないと通知が届きません。",
188
+ " また、通知を見る人は、このチャンネルに参加してください。",
189
+ "",
190
+ ]);
191
+ if (!(await prompts.enter("Bot の招待が完了したら Enter を押してください...")))
192
+ throw new CreateStop(1, "中断しました。");
193
+ box.output.err("[SUCCESS] 完了: Slack 連携の設定 OK。");
194
+ }
195
+ /**
196
+ * PAT で push するための git の設定(引数の前に付ける)。認証ヘルパーを空にしてから、環境変数 SF_INIT_PUSH_TOKEN を返すヘルパーだけにする
197
+ * (Token は URL・引数・.git/config に入らない。ヘルパーは git 付属の sh が動かす)
198
+ */
199
+ export const PUSH_AUTH = [
200
+ "-c",
201
+ "credential.helper=",
202
+ "-c",
203
+ 'credential.helper=!f() { echo username=x-access-token; echo "password=$SF_INIT_PUSH_TOKEN"; }; f',
204
+ ];
205
+ export async function phaseInitialCommit(ctx) {
206
+ const s = state(ctx, "REPO_DIR", "REPO_FULL_NAME");
207
+ const token = s.PAT_TOKEN_VALUE ?? "";
208
+ if (token === "")
209
+ throw new CreateStop(1, "PAT_TOKEN_VALUE が未設定です。Phase 6 が完了しているか確認してください。");
210
+ const repo = repoBox(ctx, s.REPO_DIR);
211
+ const err = (l) => repo.output.err(l);
212
+ err("[HEADER] 初回コミット&プッシュ");
213
+ err("[INFO] 初回コミット&プッシュを実行中...");
214
+ await must(repo, "git", ["add", "-A"], "git add に失敗しました。");
215
+ if ((await exec(repo, "git", ["diff", "--cached", "--quiet"]))?.code === 0)
216
+ err("[INFO] コミットする変更がありません。コミットをスキップします。");
217
+ else {
218
+ err("[INFO] 変更ファイル:");
219
+ for (const l of ((await exec(repo, "git", ["status", "--short"]))?.stdout ?? "").split("\n").filter((x) => x !== ""))
220
+ err(` ${l}`);
221
+ // --no-verify を付けない(Phase 4 で入れた pre-commit フックを動かす)
222
+ await must(repo, "git", ["commit", "-m", "chore: sf-tools 初期セットアップ"], "git commit に失敗しました。");
223
+ }
224
+ const env = { SF_INIT_PUSH_TOKEN: token, GIT_TERMINAL_PROMPT: "0" };
225
+ // .github/workflows/ を含むため、workflow の権限を持つ PAT で push する(gh の OAuth は workflow の権限を持たない)
226
+ await must(repo, "git", [...PUSH_AUTH, "push", "--no-verify", "origin", "main"], "git push に失敗しました。", { env });
227
+ const text = repo.files.exists(BRANCHES_REL) ? repo.files.readText(BRANCHES_REL) : "";
228
+ for (const b of nonMainBranches(text)) {
229
+ if ((await exec(repo, "git", [...PUSH_AUTH, "ls-remote", "--exit-code", "--heads", "origin", b], { env }))?.code === 0) {
230
+ err(`[INFO] ${b} — スキップ(既に存在)`);
231
+ continue;
232
+ }
233
+ await must(repo, "git", ["checkout", "-B", b], `${b} ブランチの作成に失敗しました。`);
234
+ await must(repo, "git", [...PUSH_AUTH, "push", "--no-verify", "-u", "origin", b], `${b} ブランチのプッシュに失敗しました。`, { env });
235
+ await must(repo, "git", ["checkout", "main"], "main への切り替えに失敗しました。");
236
+ err(`[SUCCESS] ${b} ブランチを作成しました。`);
237
+ }
238
+ // push が終わったら、Token を状態ファイルに残さない(消せなければ止める)
239
+ try {
240
+ dropStateLines(ctx.admin, ctx.envFile, /^PAT_TOKEN_VALUE=/);
241
+ }
242
+ catch {
243
+ throw new CreateStop(1, `状態ファイルから PAT_TOKEN_VALUE の行を削除できませんでした: ${ctx.adminDir}/${ctx.envFile}`);
244
+ }
245
+ if ((state(ctx).PAT_TOKEN_VALUE ?? "") !== "")
246
+ throw new CreateStop(1, `状態ファイルに PAT_TOKEN_VALUE の行が残っています: ${ctx.adminDir}/${ctx.envFile}`);
247
+ err("[SUCCESS] 初回コミット&プッシュ完了。");
248
+ // フックを入れ直す(この Phase の push は --no-verify のため、フックを動かしていない)
249
+ await setupHooks(repo, ctx.deps.doctor);
250
+ err("[SUCCESS] 完了: 初回コミット&プッシュ OK。");
251
+ }
252
+ /** Ruleset の本文(protect-main / protect-staging。必須のチェックは、ワークフローの「ジョブ名」だけ。integration_id 15368 = GitHub Actions) */
253
+ export function rulesetBody(name, branch) {
254
+ return JSON.stringify({
255
+ name,
256
+ target: "branch",
257
+ enforcement: "active",
258
+ conditions: { ref_name: { include: [`refs/heads/${branch}`], exclude: [] } },
259
+ bypass_actors: [{ actor_id: 5, actor_type: "RepositoryRole", bypass_mode: "always" }],
260
+ rules: [
261
+ { type: "deletion" },
262
+ { type: "non_fast_forward" },
263
+ {
264
+ type: "required_status_checks",
265
+ parameters: {
266
+ strict_required_status_checks_policy: false,
267
+ do_not_enforce_on_create: false,
268
+ required_status_checks: requiredStatusCheckNames().map((context) => ({ context, integration_id: 15368 })),
269
+ },
270
+ },
271
+ ],
272
+ }, null, 2);
273
+ }
274
+ /** 同名の Ruleset を消す(再実行のため)。一覧を読めない・数字以外の行があれば、消さずに WARNING */
275
+ export async function deleteExistingRuleset(box, repo, name) {
276
+ const r = await exec(box, "gh", ["api", `repos/${repo}/rulesets`, "--paginate", "--jq", `.[] | select(.name=="${name}") | .id`]);
277
+ if (r === null || r.code !== 0) {
278
+ box.output.err(`[WARNING] 既存の ${name} を確認できなかったため、削除をスキップします(プランの制限などの可能性があります)。`);
279
+ return;
280
+ }
281
+ const ids = r.stdout
282
+ .replace(/\r/g, "")
283
+ .split("\n")
284
+ .filter((l) => l !== "");
285
+ if (ids.some((id) => !/^[0-9]+$/.test(id))) {
286
+ box.output.err(`[WARNING] 既存の ${name} を確認できなかったため、削除をスキップします(想定外の応答です)。`);
287
+ return;
288
+ }
289
+ for (const id of ids) {
290
+ if ((await exec(box, "gh", ["api", "--method", "DELETE", `repos/${repo}/rulesets/${id}`]))?.code === 0)
291
+ box.output.err(`[INFO] 既存の ${name} (id: ${id}) を削除しました。`);
292
+ else
293
+ box.output.err(`[WARNING] 既存の ${name} (id: ${id}) の削除に失敗しました。`);
294
+ }
295
+ }
296
+ export async function phaseRepoRules(ctx) {
297
+ const box = ctx.admin;
298
+ const err = (l) => box.output.err(l);
299
+ const s = state(ctx, "REPO_FULL_NAME");
300
+ const repo = s.REPO_FULL_NAME;
301
+ err("[HEADER] GitHub リポジトリ設定・Ruleset の適用");
302
+ err("[INFO] [1/4] リポジトリ基本設定を適用中...");
303
+ const edit = await exec(box, "gh", [
304
+ "repo",
305
+ "edit",
306
+ repo,
307
+ "--default-branch",
308
+ "main",
309
+ "--enable-issues",
310
+ "--enable-projects",
311
+ "--enable-wiki",
312
+ "--enable-discussions=false",
313
+ "--enable-merge-commit",
314
+ "--enable-squash-merge",
315
+ "--enable-rebase-merge",
316
+ "--delete-branch-on-merge=false",
317
+ ]);
318
+ if (edit?.code === 0)
319
+ err("[SUCCESS] リポジトリ基本設定を適用しました。");
320
+ else
321
+ err("[WARNING] リポジトリ基本設定の適用に失敗しました。手動で設定してください。");
322
+ // 失敗を WARNING にする理由: 無料プランの Private リポジトリなど、Ruleset が使えない場合があるため
323
+ for (const [i, branch] of [
324
+ [2, "main"],
325
+ [3, "staging"],
326
+ ]) {
327
+ const name = `protect-${branch}`;
328
+ err(`[INFO] [${i}/4] Ruleset: ${name} を作成中...`);
329
+ await deleteExistingRuleset(box, repo, name);
330
+ const r = await exec(box, "gh", ["api", "--method", "POST", `repos/${repo}/rulesets`, "--input", "-"], {
331
+ input: rulesetBody(name, branch),
332
+ });
333
+ if (r?.code === 0)
334
+ err(`[SUCCESS] ${name} を作成しました。`);
335
+ else
336
+ err(`[WARNING] ${name} の作成に失敗しました(無料プランでは利用不可の場合があります)。`);
337
+ }
338
+ if ((s.SF_TOOLS_BRANCH || "main") === "development") {
339
+ err("[INFO] [4/4] SF_TOOLS_BRANCH=development を GitHub Variable に登録中...");
340
+ if ((await exec(box, "gh", ["variable", "set", "SF_TOOLS_BRANCH", "--body", "development", "-R", repo]))?.code === 0)
341
+ err("[SUCCESS] SF_TOOLS_BRANCH=development を登録しました。GitHub Actions は sf-tools development ブランチを使用します。");
342
+ else {
343
+ err("[WARNING] SF_TOOLS_BRANCH の登録に失敗しました。手動で設定してください:");
344
+ err(`[WARNING] gh variable set SF_TOOLS_BRANCH --body "development" -R "${repo}"`);
345
+ }
346
+ }
347
+ else
348
+ err("[INFO] [4/4] SF_TOOLS_BRANCH: 配布版(main)のため、登録しません。");
349
+ err("[SUCCESS] 完了: GitHub リポジトリ設定・Ruleset の適用 OK。");
350
+ }
351
+ const OPENSSL_ENV = { MSYS_NO_PATHCONV: "1" };
352
+ /** 証明書の発行先(subject): "ok" 入っている / "empty" 空 / "unreadable" 読めない */
353
+ async function certSubject(box, crt) {
354
+ const r = await exec(box, "openssl", ["x509", "-in", crt, "-noout", "-subject"], { env: OPENSSL_ENV });
355
+ if (r === null || r.code !== 0)
356
+ return "unreadable";
357
+ return r.stdout.replace(/^subject=/, "").replace(/\s/g, "") === "" ? "empty" : "ok";
358
+ }
359
+ /** 秘密鍵から、発行先つきの自己署名証明書(10 年)を作る(Node から直接 openssl を動かすので、-subj は / のままでよい) */
360
+ const issueCert = (box, key, crt, repoName) => exec(box, "openssl", ["req", "-new", "-x509", "-days", "3650", "-key", key, "-out", crt, "-subj", `/CN=sf-jwt-${repoName}`], {
361
+ env: OPENSSL_ENV,
362
+ });
363
+ /** 既存の証明書の発行先が空なら、秘密鍵はそのままで、証明書だけを作り直す(以前の sf-tools の Mac・Linux の不具合の直し) */
364
+ export async function ensureCertSubject(box, dir, repoName) {
365
+ const crt = `${dir}/server.crt`;
366
+ if ((await certSubject(box, crt)) !== "empty")
367
+ return;
368
+ box.output.err("[WARNING] 既存の証明書の発行先(subject)が空です。このままでは、Salesforce が「証明書ではありません」と拒否します。");
369
+ box.output.err(`[WARNING] 秘密鍵はそのままで、証明書だけを作り直します: ${crt}`);
370
+ const tmp = `${crt}.tmp`;
371
+ const r = await issueCert(box, `${dir}/server.key`, tmp, repoName);
372
+ if (r === null || r.code !== 0) {
373
+ box.files.removeFile(tmp);
374
+ throw new CreateStop(1, "証明書の再発行に失敗しました。");
375
+ }
376
+ if ((await certSubject(box, tmp)) !== "ok") {
377
+ box.files.removeFile(tmp);
378
+ throw new CreateStop(1, "再発行した証明書の発行先(subject)が空、または読み取れません。");
379
+ }
380
+ box.files.writeText(crt, box.files.readText(tmp));
381
+ box.files.removeFile(tmp);
382
+ box.output.err("[SUCCESS] 証明書を作り直しました(秘密鍵は、そのままです)。");
383
+ }
384
+ /** JWT 用の秘密鍵(RSA 2048・PKCS#1)と証明書(自己署名・3650 日・CN=sf-jwt-<REPO_NAME>)を作る。両方あれば、発行先だけを直す */
385
+ export async function generateJwtCert(box, restrict, dir, repoName) {
386
+ const err = (l) => box.output.err(l);
387
+ try {
388
+ box.files.makeDir(dir);
389
+ }
390
+ catch {
391
+ throw new CreateStop(1, `JWT 用証明書の保存先を作成できません: ${dir}`);
392
+ }
393
+ restrict(dir);
394
+ const key = `${dir}/server.key`;
395
+ const crt = `${dir}/server.crt`;
396
+ if (box.files.exists(key) && box.files.exists(crt)) {
397
+ err(`[INFO] 既存の証明書を使用します(スキップ): ${dir}/`);
398
+ err(`[INFO] 秘密鍵: ${key}`);
399
+ err(`[INFO] 証明書: ${crt}`);
400
+ await ensureCertSubject(box, dir, repoName);
401
+ return;
402
+ }
403
+ err(`[INFO] JWT 用証明書を生成中: ${dir}/`);
404
+ const tmp = `${key}.tmp`;
405
+ const g = await exec(box, "openssl", ["genrsa", "-out", tmp, "2048"], { env: OPENSSL_ENV });
406
+ if (g === null || g.code !== 0)
407
+ throw new CreateStop(1, "秘密鍵の生成に失敗しました。openssl がインストールされているか確認してください。");
408
+ // OpenSSL 3.x の genrsa は PKCS#8 を出すため、-traditional で PKCS#1 にする(Salesforce の JWT は PKCS#1 を求める)。1.x は元から PKCS#1
409
+ const t = await exec(box, "openssl", ["rsa", "-traditional", "-in", tmp, "-out", key], { env: OPENSSL_ENV });
410
+ try {
411
+ if (t === null || t.code !== 0)
412
+ box.files.writeText(key, box.files.readText(tmp));
413
+ box.files.removeFile(tmp);
414
+ }
415
+ catch {
416
+ throw new CreateStop(1, `秘密鍵の保存に失敗しました: ${key}`);
417
+ }
418
+ const c = await issueCert(box, key, crt, repoName);
419
+ if (c === null || c.code !== 0)
420
+ throw new CreateStop(1, "証明書の生成に失敗しました。");
421
+ // openssl は、発行先が空でも成功を返す(Salesforce が拒否するため、ここで確かめる)
422
+ if ((await certSubject(box, crt)) !== "ok")
423
+ throw new CreateStop(1, `生成した証明書の発行先(subject)が空、または読み取れません: ${crt}`);
424
+ restrict(key);
425
+ err("[SUCCESS] 証明書を生成しました。");
426
+ err(`[INFO] 秘密鍵: ${key}`);
427
+ err(`[INFO] 証明書: ${crt}`);
428
+ }
429
+ const TIERS = [
430
+ { min: 1, alias: "prod", suffix: "PROD", tier: "main", label: "メイン組織" },
431
+ { min: 2, alias: "staging", suffix: "STG", tier: "staging", label: "ステージング組織" },
432
+ { min: 3, alias: "develop", suffix: "DEV", tier: "develop", label: "開発組織" },
433
+ ];
434
+ export async function phaseSfAuth(ctx) {
435
+ const box = ctx.admin;
436
+ const err = (l) => box.output.err(l);
437
+ const s = state(ctx, "REPO_FULL_NAME", "REPO_NAME");
438
+ const repo = s.REPO_FULL_NAME;
439
+ const repoName = s.REPO_NAME;
440
+ const count = Number(s.BRANCH_COUNT || "1") || 1;
441
+ const dir = `${ctx.deps.home}/.sf-jwt/${repoName}`;
442
+ let tierResume = ctx.tierResume;
443
+ err("[HEADER] JWT 認証情報の設定");
444
+ err("[HEADER] JWT 用証明書を生成します。");
445
+ if (box.files.exists(`${dir}/server.key`) && box.files.exists(`${dir}/server.crt`)) {
446
+ err(`[INFO] 既存の証明書が見つかりました: ${dir}/`);
447
+ if (await confirmYes(ctx.ask, " 既存の証明書を再利用しますか?(N を選ぶと再生成します)")) {
448
+ err("[INFO] 既存の証明書を使用します。");
449
+ await ensureCertSubject(box, dir, repoName);
450
+ }
451
+ else {
452
+ box.files.removeFile(`${dir}/server.key`);
453
+ box.files.removeFile(`${dir}/server.crt`);
454
+ await generateJwtCert(box, ctx.deps.restrict, dir, repoName);
455
+ // 秘密鍵が新しくなる。前回完了した段階を飛ばすと、その組織のアプリに古い証明書が残るため、全部設定し直す
456
+ if (tierResume) {
457
+ tierResume = false;
458
+ err("[INFO] 証明書を作り直したため、前回、設定が完了した段階も、設定しなおします。");
459
+ }
460
+ }
461
+ }
462
+ else
463
+ await generateJwtCert(box, ctx.deps.restrict, dir, repoName);
464
+ err("[HEADER] 外部クライアントアプリケーションは自動で作成します。");
465
+ err("[INFO] 各組織で、ブラウザでのログインが必要です(接続ユーザー=管理者権限のユーザー)。");
466
+ err("[INFO] アプリの作成・証明書の登録・ポリシーとプロファイルの設定・コンシューマー鍵の取得は、sft が自動で行います。");
467
+ err("[HEADER] SF_PRIVATE_KEY を GitHub Secrets に登録します。");
468
+ // 値はログ・画面に出さない(CR を除いて base64 の 1 行にし、標準入力で渡す)
469
+ const keyText = box.files.readText(`${dir}/server.key`).replace(/\r/g, "");
470
+ await must(box, "gh", ["secret", "set", "SF_PRIVATE_KEY", "-R", repo], "SF_PRIVATE_KEY の登録に失敗しました。", {
471
+ input: base64(keyText),
472
+ });
473
+ err("[SUCCESS] SF_PRIVATE_KEY を登録しました。");
474
+ err("[HEADER] 各組織の JWT 認証情報を設定します。");
475
+ for (const t of TIERS) {
476
+ if (count < t.min)
477
+ continue;
478
+ if (await tierDone(ctx, tierResume, repo, t.suffix)) {
479
+ err(`[INFO] ${t.label}(${t.suffix})は、前回、設定が完了しているため、スキップします(付け替えるときは、sft project reconnect <段階>)。`);
480
+ continue;
481
+ }
482
+ await registerJwtSecretEca(box, ctx.deps, ctx.ask, {
483
+ repo,
484
+ suffix: t.suffix,
485
+ tier: t.tier,
486
+ label: t.label,
487
+ alias: t.alias,
488
+ keyFile: `${dir}/server.key`,
489
+ certFile: `${dir}/server.crt`,
490
+ });
491
+ // この段階が終わったことを記録する(途中で失敗しても、終わった段階をやり直さないため)
492
+ if (tierResume) {
493
+ try {
494
+ box.files.appendText(ctx.progressFile, `SF_INIT_DONE_TIER_${t.suffix}=1\n`);
495
+ }
496
+ catch {
497
+ err("[WARNING] 進捗の記録に失敗しました(次回、この段階を、やり直します)。");
498
+ }
499
+ }
500
+ }
501
+ err("[SUCCESS] 完了: JWT 認証情報の設定 OK。");
502
+ }
503
+ /** 前回、この段階を終えたか(進捗の記録があり、Secret SF_CONSUMER_KEY_<接尾辞> が今もある。一覧を読めなければ、やり直す) */
504
+ async function tierDone(ctx, resume, repo, suffix) {
505
+ const box = ctx.admin;
506
+ if (!resume || !box.files.exists(ctx.progressFile))
507
+ return false;
508
+ if (!box.files.readText(ctx.progressFile).replace(/\r/g, "").split("\n").includes(`SF_INIT_DONE_TIER_${suffix}=1`))
509
+ return false;
510
+ const r = await exec(box, "gh", ["secret", "list", "-R", repo]);
511
+ if (r === null || r.code !== 0) {
512
+ box.output.err(`[INFO] Secret の一覧を確認できないため、${suffix} の段階は、スキップせずに、実行します。`);
513
+ return false;
514
+ }
515
+ return r.stdout
516
+ .replace(/\r/g, "")
517
+ .split("\n")
518
+ .some((l) => l.split(/\s+/)[0] === `SF_CONSUMER_KEY_${suffix}`);
519
+ }