create-clis 0.1.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/LICENSE +21 -0
- package/README.md +113 -0
- package/README.zh-CN.md +113 -0
- package/assets/manifest.json +99 -0
- package/assets/template/.editorconfig +12 -0
- package/assets/template/.gitattributes +18 -0
- package/assets/template/.github/ISSUE_TEMPLATE/bug_report.yml +86 -0
- package/assets/template/.github/ISSUE_TEMPLATE/feature_request.yml +45 -0
- package/assets/template/.github/PULL_REQUEST_TEMPLATE.md +26 -0
- package/assets/template/.github/workflows/ci.yml +42 -0
- package/assets/template/.github/workflows/release.yml +65 -0
- package/assets/template/.gitignorerc.json +21 -0
- package/assets/template/.nvmrc +1 -0
- package/assets/template/.oxlintrc.json +52 -0
- package/assets/template/.prettierignore +11 -0
- package/assets/template/.prettierrc +11 -0
- package/assets/template/.releaserc.json +17 -0
- package/assets/template/.vscode/extensions.json +8 -0
- package/assets/template/.vscode/launch.json +13 -0
- package/assets/template/.vscode/settings.json +14 -0
- package/assets/template/AGENTS.md +25 -0
- package/assets/template/CODE_OF_CONDUCT.md +91 -0
- package/assets/template/CONTRIBUTING.md +85 -0
- package/assets/template/CONTRIBUTING.zh-CN.md +85 -0
- package/assets/template/LICENSE +21 -0
- package/assets/template/README.md +22 -0
- package/assets/template/README.zh-CN.md +22 -0
- package/assets/template/SECURITY.md +21 -0
- package/assets/template/_gitignore +409 -0
- package/assets/template/_npmrc +6 -0
- package/assets/template/bunfig.toml +16 -0
- package/assets/template/docs/README.md +30 -0
- package/assets/template/docs/adrs/README.md +7 -0
- package/assets/template/docs/designs/README.md +11 -0
- package/assets/template/docs/designs/tech-debt.md +22 -0
- package/assets/template/docs/development.md +59 -0
- package/assets/template/lefthook.yml +55 -0
- package/assets/template/package.json +38 -0
- package/assets/template/packages/{{NAME}}/CHANGELOG.md +3 -0
- package/assets/template/packages/{{NAME}}/LICENSE +21 -0
- package/assets/template/packages/{{NAME}}/README.md +33 -0
- package/assets/template/packages/{{NAME}}/README.zh-CN.md +33 -0
- package/assets/template/packages/{{NAME}}/docs/README.md +21 -0
- package/assets/template/packages/{{NAME}}/package.json +40 -0
- package/assets/template/packages/{{NAME}}/scripts/build.ts +82 -0
- package/assets/template/packages/{{NAME}}/scripts/verify-release.test.ts +214 -0
- package/assets/template/packages/{{NAME}}/scripts/verify-release.ts +152 -0
- package/assets/template/packages/{{NAME}}/src/index.ts +15 -0
- package/assets/template/packages/{{NAME}}/tsconfig.build.json +12 -0
- package/assets/template/packages/{{NAME}}/tsconfig.json +5 -0
- package/assets/template/packages/{{NAME}}-cli/CHANGELOG.md +3 -0
- package/assets/template/packages/{{NAME}}-cli/LICENSE +21 -0
- package/assets/template/packages/{{NAME}}-cli/README.md +35 -0
- package/assets/template/packages/{{NAME}}-cli/README.zh-CN.md +35 -0
- package/assets/template/packages/{{NAME}}-cli/bin/{{BIN_NAME}} +30 -0
- package/assets/template/packages/{{NAME}}-cli/bin/{{BIN_NAME}}.cmd +30 -0
- package/assets/template/packages/{{NAME}}-cli/bin/{{BIN_NAME}}.d.mts +23 -0
- package/assets/template/packages/{{NAME}}-cli/bin/{{BIN_NAME}}.mjs +212 -0
- package/assets/template/packages/{{NAME}}-cli/docs/README.md +21 -0
- package/assets/template/packages/{{NAME}}-cli/package.json +48 -0
- package/assets/template/packages/{{NAME}}-cli/scripts/release-artifact.ts +141 -0
- package/assets/template/packages/{{NAME}}-cli/scripts/release.fixtures.ts +70 -0
- package/assets/template/packages/{{NAME}}-cli/scripts/verify-release.test.ts +444 -0
- package/assets/template/packages/{{NAME}}-cli/scripts/verify-release.ts +72 -0
- package/assets/template/packages/{{NAME}}-cli/scripts/write-dist-manifest.test.ts +126 -0
- package/assets/template/packages/{{NAME}}-cli/scripts/write-dist-manifest.ts +81 -0
- package/assets/template/packages/{{NAME}}-cli/src/cli.ts +36 -0
- package/assets/template/packages/{{NAME}}-cli/tsconfig.json +4 -0
- package/assets/template/scripts/ci.ts +163 -0
- package/assets/template/scripts/install-git-hooks.mjs +122 -0
- package/assets/template/scripts/install-git-hooks.test.ts +418 -0
- package/assets/template/scripts/lib/git-env.ts +21 -0
- package/assets/template/scripts/lib/release-verify.ts +431 -0
- package/assets/template/scripts/lib/tmp-root.ts +17 -0
- package/assets/template/scripts/lib/workspace.test.ts +92 -0
- package/assets/template/scripts/lib/workspace.ts +100 -0
- package/assets/template/scripts/lint-doc-examples.test.ts +129 -0
- package/assets/template/scripts/lint-doc-examples.ts +249 -0
- package/assets/template/scripts/lint-doc-references.test.ts +158 -0
- package/assets/template/scripts/lint-doc-references.ts +308 -0
- package/assets/template/scripts/lint-doc-shared.ts +59 -0
- package/assets/template/scripts/lint-stray-backups.test.ts +53 -0
- package/assets/template/scripts/lint-stray-backups.ts +39 -0
- package/assets/template/scripts/npm-trust-guard.test.ts +253 -0
- package/assets/template/scripts/npm-trust-guard.ts +533 -0
- package/assets/template/scripts/safe-install.ts +39 -0
- package/assets/template/scripts/transcription/api-harness.ts +219 -0
- package/assets/template/scripts/transcription/compare.ts +421 -0
- package/assets/template/scripts/transcription/corpus.ts +208 -0
- package/assets/template/scripts/transcription/fixture.ts +290 -0
- package/assets/template/scripts/transcription/make-mutants.ts +425 -0
- package/assets/template/scripts/transcription/report.ts +86 -0
- package/assets/template/scripts/transcription/run-conformance.ts +344 -0
- package/assets/template/scripts/transcription/validate-coverage.test.ts +119 -0
- package/assets/template/scripts/transcription/validate-coverage.ts +144 -0
- package/assets/template/scripts/transcription/validate.ts +366 -0
- package/assets/template/tsconfig.json +46 -0
- package/assets/template/turbo.jsonc +60 -0
- package/bin/create-clis +35 -0
- package/bin/create-clis.cmd +32 -0
- package/bin/create-clis.mjs +219 -0
- package/dist/create-clis.js +87682 -0
- package/dist/manifest.json +7 -0
- package/package.json +57 -0
|
@@ -0,0 +1,533 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 发布凭据闸门: 核对 npm 侧 Trusted Publisher 登记与当前仓库形态是否一致。
|
|
3
|
+
*
|
|
4
|
+
* 动机: 2026-09-30 仓库改名 {{OWNER}}/{{NAME}} 后, npm 侧两包的登记 (repository 字段) 仍指旧仓库名,
|
|
5
|
+
* 发布链在 release job 以误导性的 ENONPMTOKEN 挂掉 (OIDC 换证被拒后回落到 token 检查)。
|
|
6
|
+
* 「改名」是平台动作不进 git diff, npm 侧登记是仓库外状态, 本地预演触碰不到, 失配发生时
|
|
7
|
+
* 没有任何机制会喊一声。本闸门分两个场景补上这道声音:
|
|
8
|
+
*
|
|
9
|
+
* - CI (`verify-oidc`): 用 GitHub OIDC 对每包试一次 token exchange。这一步本身就是 npm 拿
|
|
10
|
+
* OIDC 令牌与登记表 (repository / workflow file / environment) 逐字段核对的过程: 换到
|
|
11
|
+
* 凭证即全对, 被拒即失配。零密钥, 走的是发布链同一条 OIDC 通道。核对面 = 仓内可发布包
|
|
12
|
+
* (非 private, 与发布链的 ignorePrivate 排除面同源)。
|
|
13
|
+
* - 本地 (`check` / `fix`): 经 `npm trust list` 对账; fix 删旧建新 (npm 侧已存配置不支持
|
|
14
|
+
* 就地修改, 只能 revoke + 重建)。需要 npm 登录态与交互式终端; npm 对这类敏感操作逐步
|
|
15
|
+
* 要求网页一次性认证, 且认证只对当次调用有效, 一次 fix 可能要在浏览器确认多轮。
|
|
16
|
+
* npm 的 web 认证交互要求 stdin 与 stdout 都是 TTY (非 TTY 直接把 EOTP 抛给你), 故对
|
|
17
|
+
* npm 的调用一律经 pty 包装 (`script`), 输出流式透传给操作者。
|
|
18
|
+
*
|
|
19
|
+
* 期望值: repository 从 git origin 派生; workflow 文件名与环境名取下方常量 (与 release.yml 同步)。
|
|
20
|
+
*
|
|
21
|
+
* 用法:
|
|
22
|
+
* bun scripts/npm-trust-guard.ts verify-oidc # CI: OIDC 换证预检 (需 id-token: write)
|
|
23
|
+
* bun scripts/npm-trust-guard.ts check # 本地: 只读对账
|
|
24
|
+
* bun scripts/npm-trust-guard.ts fix # 本地: 对账并修复 (revoke + 重建)
|
|
25
|
+
* 退出码: 0 通过 (或环境不适用); 1 失配或失败。
|
|
26
|
+
*/
|
|
27
|
+
import { spawn } from 'node:child_process';
|
|
28
|
+
|
|
29
|
+
import { readGitText } from './lib/release-verify.ts';
|
|
30
|
+
import {
|
|
31
|
+
type WorkspacePackage,
|
|
32
|
+
listWorkspacePackages,
|
|
33
|
+
} from './lib/workspace.ts';
|
|
34
|
+
import { REPO_ROOT } from './lint-doc-shared.ts';
|
|
35
|
+
|
|
36
|
+
/** npm 官方 registry (OIDC 换证与 trust 管理端点只存在于官方源, 镜像源没有) */
|
|
37
|
+
const OFFICIAL_REGISTRY = 'https://registry.npmjs.org/';
|
|
38
|
+
|
|
39
|
+
/** 发布 workflow 文件名: 常量单点, 与 `.github/workflows/release.yml` 同步 */
|
|
40
|
+
const RELEASE_WORKFLOW = 'release.yml';
|
|
41
|
+
|
|
42
|
+
/** 发布环境名: 常量单点, 与 release.yml 的 `environment: release` 同步 */
|
|
43
|
+
const RELEASE_ENVIRONMENT = 'release';
|
|
44
|
+
|
|
45
|
+
/** OIDC 令牌 audience: npm 约定值, 与发布链 @semantic-release/npm 的换证请求一致 */
|
|
46
|
+
const OIDC_AUDIENCE = 'npm:registry.npmjs.org';
|
|
47
|
+
|
|
48
|
+
/** npm trust list 解析出的登记条目 (缺行字段落成 null) */
|
|
49
|
+
export interface TrustEntry {
|
|
50
|
+
type: string | null;
|
|
51
|
+
id: string | null;
|
|
52
|
+
file: string | null;
|
|
53
|
+
environment: string | null;
|
|
54
|
+
repository: string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** 期望的登记形态 (owner/repo 从 git origin 派生, 其余为常量) */
|
|
58
|
+
export interface TrustExpectation {
|
|
59
|
+
repository: string;
|
|
60
|
+
file: string;
|
|
61
|
+
environment: string;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** OIDC 运行环境判定: ready = 可预检; missing-permission = Actions 里漏配 id-token; not-ci = 本地 */
|
|
65
|
+
export type OidcEnvVerdict = 'ready' | 'missing-permission' | 'not-ci';
|
|
66
|
+
|
|
67
|
+
/** 剥终端 CSI 序列 (颜色着色与 spinner 的光标控制; 参数段 [0-9;?]*, 末字符为任意字母) */
|
|
68
|
+
const stripCsi = (text: string): string =>
|
|
69
|
+
text.replace(
|
|
70
|
+
new RegExp(String.fromCharCode(27) + '\\[[0-9;?]*[A-Za-z]', 'g'),
|
|
71
|
+
'',
|
|
72
|
+
);
|
|
73
|
+
|
|
74
|
+
/** 剥控制字符并收拢空白 (npm 输出属低信任输入, 落进人读文案前先降噪) */
|
|
75
|
+
const cleanText = (text: string): string =>
|
|
76
|
+
text.replace(/[\p{Cc}]+/gu, ' ').trim();
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* 剥 pty 伪影: `script` 开场的 ^D + 退格序列、CRLF 行尾与孤立终端控制符。
|
|
80
|
+
* 须在 stripCsi 之后调用: 本函数的控制符剥离面覆盖 ESC 本身, 先把完整 CSI 序列剥掉再除残留。
|
|
81
|
+
*/
|
|
82
|
+
const stripPtyNoise = (text: string): string =>
|
|
83
|
+
text
|
|
84
|
+
.replace(/\r/g, '')
|
|
85
|
+
// eslint-disable-next-line no-control-regex -- 此处刻意匹配 pty 残留控制符 (script 开场的 ^D 与退格), 属预期匹配
|
|
86
|
+
.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g, '');
|
|
87
|
+
|
|
88
|
+
/** 从 git remote 原文派生 owner/repo; 非 GitHub 远端或形状不符返回 null */
|
|
89
|
+
export function deriveRepoFromRemoteUrl(raw: string): string | null {
|
|
90
|
+
const cleaned = raw.trim().replace(/\.git$/, '');
|
|
91
|
+
const match = cleaned.match(/github\.com[:/]([^/\s]+)\/([^/\s]+)$/);
|
|
92
|
+
if (match === null || match[1] === undefined || match[2] === undefined) {
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
return `${match[1]}/${match[2]}`;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* 解析 `npm trust list` 的人读输出 (键值行形态)。
|
|
100
|
+
* 噪音行 (认证提示、npm notice) 天然不含键名冒号行, 不干扰解析; 未见 repository 行时返回 null
|
|
101
|
+
* (认不出核心字段即视为形状不符, 不猜测)。
|
|
102
|
+
*/
|
|
103
|
+
export function parseTrustListOutput(raw: string): TrustEntry | null {
|
|
104
|
+
const text = stripPtyNoise(stripCsi(raw));
|
|
105
|
+
const pick = (key: string): string | null => {
|
|
106
|
+
const match = new RegExp(`^${key}:[ \\t]*(.+)$`, 'm').exec(text);
|
|
107
|
+
if (match === null || match[1] === undefined) return null;
|
|
108
|
+
return cleanText(match[1]);
|
|
109
|
+
};
|
|
110
|
+
const repository = pick('repository');
|
|
111
|
+
if (repository === null || repository === '') return null;
|
|
112
|
+
return {
|
|
113
|
+
type: pick('type'),
|
|
114
|
+
id: pick('id'),
|
|
115
|
+
file: pick('file'),
|
|
116
|
+
environment: pick('environment'),
|
|
117
|
+
repository,
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** 登记比对 (纯函数): 逐字段列出与期望值的差异, 全一致返回空列表 */
|
|
122
|
+
export function diffTrust(
|
|
123
|
+
actual: TrustEntry,
|
|
124
|
+
expected: TrustExpectation,
|
|
125
|
+
): string[] {
|
|
126
|
+
const problems: string[] = [];
|
|
127
|
+
if (actual.repository !== expected.repository) {
|
|
128
|
+
problems.push(
|
|
129
|
+
`repository: ${actual.repository} → 期望 ${expected.repository}`,
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
if (actual.file !== expected.file) {
|
|
133
|
+
problems.push(
|
|
134
|
+
`workflow 文件: ${actual.file ?? '(未设置)'} → 期望 ${expected.file}`,
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
if (actual.environment !== expected.environment) {
|
|
138
|
+
problems.push(
|
|
139
|
+
`environment: ${actual.environment ?? '(未设置)'} → 期望 ${expected.environment}`,
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
return problems;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** OIDC 环境判定 (纯函数): 三分支各自对应不同出口, 防「权限漏配」被静默放过 */
|
|
146
|
+
export function classifyOidcEnv(
|
|
147
|
+
env: Record<string, string | undefined>,
|
|
148
|
+
): OidcEnvVerdict {
|
|
149
|
+
if (env.GITHUB_ACTIONS !== 'true') return 'not-ci';
|
|
150
|
+
return env.ACTIONS_ID_TOKEN_REQUEST_URL !== undefined &&
|
|
151
|
+
env.ACTIONS_ID_TOKEN_REQUEST_TOKEN !== undefined
|
|
152
|
+
? 'ready'
|
|
153
|
+
: 'missing-permission';
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* 生成经 pty 包装的 npm 调用坐标。npm 的 web 认证交互 (npm 源码 lib/utils/auth.js 的 otplease)
|
|
158
|
+
* 要求 stdin 与 stdout 都是 TTY, 非 TTY 会直接把 EOTP 抛给调用方 (附 URL 让你自己去认证, 会话内
|
|
159
|
+
* 无法完成); `script` 起 pty 后既保交互又保捕获。
|
|
160
|
+
* - darwin: `script -q /dev/null <cmd...>` (退出码透传, Darwin 25 实测);
|
|
161
|
+
* - linux: `script -qec "<cmd 串>" /dev/null` (util-linux 语法; 调用点参数值全部受控:
|
|
162
|
+
* 包名 / UUID / 常量, 无空白字符);
|
|
163
|
+
* - 其余平台 (如 win32) 无 script, 降级直跑 (会话内认证可能不可用, 由 mainLocal 的预警兜底)。
|
|
164
|
+
*/
|
|
165
|
+
export function ptyWrapArgs(
|
|
166
|
+
platform: NodeJS.Platform,
|
|
167
|
+
npm: string,
|
|
168
|
+
args: string[],
|
|
169
|
+
): { command: string; args: string[] } {
|
|
170
|
+
if (platform === 'darwin') {
|
|
171
|
+
return { command: 'script', args: ['-q', '/dev/null', npm, ...args] };
|
|
172
|
+
}
|
|
173
|
+
if (platform === 'linux') {
|
|
174
|
+
return {
|
|
175
|
+
command: 'script',
|
|
176
|
+
args: ['-qec', [npm, ...args].join(' '), '/dev/null'],
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
return { command: npm, args };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** npm 可执行名 (Windows 是 npm.cmd, execFile/spawn 不走 shell 时不会自动补扩展名) */
|
|
183
|
+
const npmBin = (): string => (process.platform === 'win32' ? 'npm.cmd' : 'npm');
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* 经 pty 跑一条 npm 命令并流式收输出: stdout 逐块透传给操作者 (认证提示 "Press ENTER..." 必须
|
|
187
|
+
* 实时可见) 同时累积供解析; stdin 与 stderr 直通。
|
|
188
|
+
* 不设超时: 网页认证与人工按键的耗时不可控, 等待即预期行为。
|
|
189
|
+
*/
|
|
190
|
+
function runNpmCaptured(
|
|
191
|
+
args: string[],
|
|
192
|
+
): Promise<{ status: number | null; stdout: string; error?: Error }> {
|
|
193
|
+
const wrapped = ptyWrapArgs(process.platform, npmBin(), args);
|
|
194
|
+
return new Promise((resolve) => {
|
|
195
|
+
const child = spawn(wrapped.command, wrapped.args, {
|
|
196
|
+
stdio: ['inherit', 'pipe', 'inherit'],
|
|
197
|
+
env: { ...process.env, NO_COLOR: '1' },
|
|
198
|
+
});
|
|
199
|
+
let captured = '';
|
|
200
|
+
child.stdout?.on('data', (chunk: Buffer) => {
|
|
201
|
+
captured += chunk.toString('utf8');
|
|
202
|
+
process.stdout.write(chunk);
|
|
203
|
+
});
|
|
204
|
+
child.on('error', (error) =>
|
|
205
|
+
resolve({ status: null, stdout: captured, error }),
|
|
206
|
+
);
|
|
207
|
+
child.on('close', (status) => resolve({ status, stdout: captured }));
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* 预检核对面 (纯函数): 可发布 (非 private) 的包。
|
|
213
|
+
* 核对面与发布链 (multi-semantic-release) 的「可发布包」定义保持单源一致: mrs 默认开启
|
|
214
|
+
* ignorePrivate, private 包不进它的加载面。旧设计曾按根 package.json 的
|
|
215
|
+
* multi-release.ignorePackages 豁免预检, 依据是「与发布链同源」; 该依据经 2026-10-01 实测
|
|
216
|
+
* 证伪: mrs 把名单映射为 topo 的 workspacesExtra 负 glob (形如 !<包名>), 对包名形式不生效,
|
|
217
|
+
* 被列入的包照旧被加载处理。包隔离以 npm 原生字段 private: true 为准 (首发前的新包即以此隔离)。
|
|
218
|
+
*/
|
|
219
|
+
export function filterPublishable(
|
|
220
|
+
packages: readonly WorkspacePackage[],
|
|
221
|
+
): WorkspacePackage[] {
|
|
222
|
+
return packages.filter((pkg) => pkg.manifest.private !== true);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** 可发布的 workspace 包 (预检核对面, 见 filterPublishable) */
|
|
226
|
+
function publishablePackages(): WorkspacePackage[] {
|
|
227
|
+
return filterPublishable(listWorkspacePackages(REPO_ROOT));
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** 从 git origin 派生 owner/repo; 读不到或非 GitHub 返回 null */
|
|
231
|
+
function originRepo(): string | null {
|
|
232
|
+
const raw = readGitText(REPO_ROOT, ['remote', 'get-url', 'origin']);
|
|
233
|
+
return raw === null ? null : deriveRepoFromRemoteUrl(raw);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** 异常转人话 (网络类错误的 message 也过一遍降噪) */
|
|
237
|
+
function describeError(error: unknown): string {
|
|
238
|
+
return error instanceof Error ? cleanText(error.message) : String(error);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** 读 npm 换证失败的响应 message (取不到返回空串; 截长防刷屏) */
|
|
242
|
+
async function readErrorMessage(response: Response): Promise<string> {
|
|
243
|
+
try {
|
|
244
|
+
const body = (await response.json()) as { message?: unknown };
|
|
245
|
+
return typeof body.message === 'string'
|
|
246
|
+
? cleanText(body.message).slice(0, 300)
|
|
247
|
+
: '';
|
|
248
|
+
} catch {
|
|
249
|
+
return '';
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* 对单包试一次 OIDC 换证: 通过返回 null, 否则返回人话原因。
|
|
255
|
+
* 换到的短期凭证只用于证明「登记对得上」, 随即丢弃: 不打印、不落盘、不传递 (发布链自己会再换一次)。
|
|
256
|
+
*/
|
|
257
|
+
async function tryExchange(pkgName: string): Promise<string | null> {
|
|
258
|
+
const requestUrl = process.env.ACTIONS_ID_TOKEN_REQUEST_URL;
|
|
259
|
+
const requestToken = process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;
|
|
260
|
+
if (requestUrl === undefined || requestToken === undefined) {
|
|
261
|
+
return '缺少 OIDC 请求变量 (工作流需授予 id-token: write)';
|
|
262
|
+
}
|
|
263
|
+
let idToken: string;
|
|
264
|
+
try {
|
|
265
|
+
const url = new URL(requestUrl);
|
|
266
|
+
url.searchParams.append('audience', OIDC_AUDIENCE);
|
|
267
|
+
const response = await fetch(url, {
|
|
268
|
+
headers: { authorization: `Bearer ${requestToken}` },
|
|
269
|
+
});
|
|
270
|
+
if (!response.ok) {
|
|
271
|
+
return `获取 GitHub OIDC 令牌失败 (HTTP ${response.status})`;
|
|
272
|
+
}
|
|
273
|
+
const body = (await response.json()) as { value?: unknown };
|
|
274
|
+
if (typeof body.value !== 'string' || body.value === '') {
|
|
275
|
+
return 'GitHub OIDC 响应形状不符 (缺 value)';
|
|
276
|
+
}
|
|
277
|
+
idToken = body.value;
|
|
278
|
+
} catch (error) {
|
|
279
|
+
return `获取 GitHub OIDC 令牌失败 (${describeError(error)})`;
|
|
280
|
+
}
|
|
281
|
+
try {
|
|
282
|
+
const response = await fetch(
|
|
283
|
+
`${OFFICIAL_REGISTRY}-/npm/v1/oidc/token/exchange/package/${encodeURIComponent(pkgName)}`,
|
|
284
|
+
{ method: 'POST', headers: { authorization: `Bearer ${idToken}` } },
|
|
285
|
+
);
|
|
286
|
+
if (response.ok) return null;
|
|
287
|
+
const message = await readErrorMessage(response);
|
|
288
|
+
return `换证被拒 (HTTP ${response.status}${message === '' ? '' : `: ${message}`})`;
|
|
289
|
+
} catch (error) {
|
|
290
|
+
return `请求 npm 换证端点失败 (${describeError(error)})`;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** 失配后的排查清单 (指向本地修复入口与文档) */
|
|
295
|
+
function printRemediation(repo: string | null): void {
|
|
296
|
+
const repoText = repo === null ? '(读不到 git origin)' : repo;
|
|
297
|
+
process.stderr.write(
|
|
298
|
+
[
|
|
299
|
+
'',
|
|
300
|
+
'排查清单 (按可能性排序):',
|
|
301
|
+
` 1. 仓库改名后 npm 侧登记未更新: 登记须与当前仓库 ${repoText} 一致, 改名不会自动跟改`,
|
|
302
|
+
` 2. workflow 文件名不符: 登记应为 ${RELEASE_WORKFLOW}`,
|
|
303
|
+
` 3. environment 名不符: 登记应为 ${RELEASE_ENVIRONMENT}`,
|
|
304
|
+
' 4. 包尚未在 npm 配置 Trusted Publisher (或包不存在)',
|
|
305
|
+
'',
|
|
306
|
+
'修复: 在交互式终端跑 bun scripts/npm-trust-guard.ts fix (需 npm 登录态, 按提示在浏览器完成认证)',
|
|
307
|
+
'背景: 见 docs/development.md 「发布」章节',
|
|
308
|
+
'',
|
|
309
|
+
].join('\n'),
|
|
310
|
+
);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** CI 预检: 对每个可发布包试 OIDC 换证, 任一被拒即红灯 (改名后的第一次 CI 即被拦下并点名) */
|
|
314
|
+
async function mainVerifyOidc(): Promise<void> {
|
|
315
|
+
const verdict = classifyOidcEnv(process.env);
|
|
316
|
+
if (verdict === 'not-ci') {
|
|
317
|
+
process.stdout.write(
|
|
318
|
+
'非 GitHub Actions 环境, OIDC 预检不适用; 本地登记核对请用 npm-trust-guard.ts check\n',
|
|
319
|
+
);
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
if (verdict === 'missing-permission') {
|
|
323
|
+
process.stderr.write(
|
|
324
|
+
'GitHub Actions 环境缺少 OIDC 请求变量: 该 job 需授予 id-token: write 权限\n',
|
|
325
|
+
);
|
|
326
|
+
process.exitCode = 1;
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
const failures: { packageName: string; reason: string }[] = [];
|
|
330
|
+
for (const pkg of publishablePackages()) {
|
|
331
|
+
const reason = await tryExchange(pkg.name);
|
|
332
|
+
if (reason === null) {
|
|
333
|
+
process.stdout.write(
|
|
334
|
+
`✔ ${pkg.name}: OIDC 换证通过 (npm 侧登记与当前仓库匹配)\n`,
|
|
335
|
+
);
|
|
336
|
+
} else {
|
|
337
|
+
failures.push({ packageName: pkg.name, reason });
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
if (failures.length === 0) return;
|
|
341
|
+
process.stderr.write(
|
|
342
|
+
'npm Trusted Publisher 预检未通过 (发布会在 npm 认证处失败, 这里提前拦下):\n',
|
|
343
|
+
);
|
|
344
|
+
for (const failure of failures) {
|
|
345
|
+
process.stderr.write(` ✘ ${failure.packageName}: ${failure.reason}\n`);
|
|
346
|
+
}
|
|
347
|
+
printRemediation(originRepo());
|
|
348
|
+
process.exitCode = 1;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** 本地读单包登记: ok = 解析成功; error = npm 跑不起来 / 退出非零 / 输出形状不符 */
|
|
352
|
+
type TrustRead =
|
|
353
|
+
{ kind: 'ok'; entry: TrustEntry } | { kind: 'error'; detail: string };
|
|
354
|
+
|
|
355
|
+
/** 跑 `npm trust list` 读登记 (经 pty 包装, 见 runNpmCaptured) */
|
|
356
|
+
async function readTrustEntry(pkgName: string): Promise<TrustRead> {
|
|
357
|
+
const result = await runNpmCaptured([
|
|
358
|
+
'trust',
|
|
359
|
+
'list',
|
|
360
|
+
pkgName,
|
|
361
|
+
`--registry=${OFFICIAL_REGISTRY}`,
|
|
362
|
+
]);
|
|
363
|
+
if (result.error !== undefined) {
|
|
364
|
+
return {
|
|
365
|
+
kind: 'error',
|
|
366
|
+
detail: `npm 跑不起来 (${describeError(result.error)})`,
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
if (result.status !== 0) {
|
|
370
|
+
return {
|
|
371
|
+
kind: 'error',
|
|
372
|
+
detail: `npm trust list 失败 (退出码 ${String(result.status)}); 若上方提示了网页认证, 请按提示完成后重试`,
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
const entry = parseTrustListOutput(result.stdout);
|
|
376
|
+
if (entry === null) {
|
|
377
|
+
return {
|
|
378
|
+
kind: 'error',
|
|
379
|
+
detail: 'npm trust list 输出无法解析 (未见 repository 行)',
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
return { kind: 'ok', entry };
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/** 跑一条需要交互的 npm 命令 (经 pty, 认证提示与输入都透传), 返回是否成功 */
|
|
386
|
+
async function runNpmInteractive(args: string[]): Promise<boolean> {
|
|
387
|
+
const result = await runNpmCaptured(args);
|
|
388
|
+
if (result.error !== undefined) {
|
|
389
|
+
process.stderr.write(
|
|
390
|
+
` ✘ npm ${args[0] ?? ''} 跑不起来 (${describeError(result.error)})\n`,
|
|
391
|
+
);
|
|
392
|
+
return false;
|
|
393
|
+
}
|
|
394
|
+
if (result.status !== 0) {
|
|
395
|
+
process.stderr.write(
|
|
396
|
+
` ✘ npm ${args.slice(0, 2).join(' ')} 失败 (退出码 ${String(result.status)})\n`,
|
|
397
|
+
);
|
|
398
|
+
return false;
|
|
399
|
+
}
|
|
400
|
+
return true;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* 重建单包登记: 先 revoke 旧记录 (npm 侧一条包只支持一份登记, 不支持就地修改), 再按期望值创建。
|
|
405
|
+
* 新登记取最小权限: 仅 publish (stage publish 未使用, 不勾)。
|
|
406
|
+
*/
|
|
407
|
+
async function repairPackage(
|
|
408
|
+
pkgName: string,
|
|
409
|
+
entry: TrustEntry,
|
|
410
|
+
expected: TrustExpectation,
|
|
411
|
+
): Promise<boolean> {
|
|
412
|
+
process.stdout.write(` → 重建 ${pkgName} 的 Trusted Publisher 登记:\n`);
|
|
413
|
+
// 两个动作都执行 (revoke 失败仍尝试 create), 结果取合
|
|
414
|
+
const revoked =
|
|
415
|
+
entry.id === null
|
|
416
|
+
? true
|
|
417
|
+
: await runNpmInteractive([
|
|
418
|
+
'trust',
|
|
419
|
+
'revoke',
|
|
420
|
+
pkgName,
|
|
421
|
+
`--id=${entry.id}`,
|
|
422
|
+
`--registry=${OFFICIAL_REGISTRY}`,
|
|
423
|
+
]);
|
|
424
|
+
const created = await runNpmInteractive([
|
|
425
|
+
'trust',
|
|
426
|
+
'github',
|
|
427
|
+
pkgName,
|
|
428
|
+
'--file',
|
|
429
|
+
expected.file,
|
|
430
|
+
'--repo',
|
|
431
|
+
expected.repository,
|
|
432
|
+
'--env',
|
|
433
|
+
expected.environment,
|
|
434
|
+
'--allow-publish',
|
|
435
|
+
`--registry=${OFFICIAL_REGISTRY}`,
|
|
436
|
+
]);
|
|
437
|
+
return revoked && created;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/** 本地对账 (check) 与修复 (fix) 的主流程 */
|
|
441
|
+
async function mainLocal(command: 'check' | 'fix'): Promise<void> {
|
|
442
|
+
// npm 的认证交互要求 TTY; 非交互环境 (管道 / 钩子) 里会卡在等待输入, 先在入口预警
|
|
443
|
+
if (process.stdin.isTTY !== true || process.stdout.isTTY !== true) {
|
|
444
|
+
process.stderr.write(
|
|
445
|
+
'提示: 当前不是交互式终端; npm 的网页认证需要 TTY, 请在交互式终端重跑本命令\n',
|
|
446
|
+
);
|
|
447
|
+
}
|
|
448
|
+
const repo = originRepo();
|
|
449
|
+
if (repo === null) {
|
|
450
|
+
process.stderr.write(
|
|
451
|
+
'读不到 git origin 的 GitHub 坐标 (git remote get-url origin), 无法派生期望的 repository\n',
|
|
452
|
+
);
|
|
453
|
+
process.exitCode = 1;
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
const expected: TrustExpectation = {
|
|
457
|
+
repository: repo,
|
|
458
|
+
file: RELEASE_WORKFLOW,
|
|
459
|
+
environment: RELEASE_ENVIRONMENT,
|
|
460
|
+
};
|
|
461
|
+
let failed = false;
|
|
462
|
+
for (const pkg of publishablePackages()) {
|
|
463
|
+
const read = await readTrustEntry(pkg.name);
|
|
464
|
+
if (read.kind === 'error') {
|
|
465
|
+
process.stderr.write(`✘ ${pkg.name}: ${read.detail}\n`);
|
|
466
|
+
failed = true;
|
|
467
|
+
continue;
|
|
468
|
+
}
|
|
469
|
+
const problems = diffTrust(read.entry, expected);
|
|
470
|
+
if (problems.length === 0) {
|
|
471
|
+
process.stdout.write(`✔ ${pkg.name}: npm 侧登记与当前仓库一致\n`);
|
|
472
|
+
continue;
|
|
473
|
+
}
|
|
474
|
+
process.stderr.write(`✘ ${pkg.name}: npm 侧登记与当前仓库不一致:\n`);
|
|
475
|
+
for (const problem of problems) process.stderr.write(` ${problem}\n`);
|
|
476
|
+
if (command === 'check') {
|
|
477
|
+
failed = true;
|
|
478
|
+
continue;
|
|
479
|
+
}
|
|
480
|
+
if (!(await repairPackage(pkg.name, read.entry, expected))) {
|
|
481
|
+
failed = true;
|
|
482
|
+
}
|
|
483
|
+
const after = await readTrustEntry(pkg.name);
|
|
484
|
+
if (after.kind === 'ok' && diffTrust(after.entry, expected).length === 0) {
|
|
485
|
+
process.stdout.write(` ✔ ${pkg.name}: 重建后复查通过\n`);
|
|
486
|
+
} else {
|
|
487
|
+
process.stderr.write(
|
|
488
|
+
` ✘ ${pkg.name}: 重建后复查未通过, 请人工检查 npm 侧配置\n`,
|
|
489
|
+
);
|
|
490
|
+
failed = true;
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
if (!failed) return;
|
|
494
|
+
if (command === 'check') {
|
|
495
|
+
process.stderr.write(
|
|
496
|
+
'\n修复: 在交互式终端跑 bun scripts/npm-trust-guard.ts fix (需 npm 登录态)\n',
|
|
497
|
+
);
|
|
498
|
+
}
|
|
499
|
+
process.exitCode = 1;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/** 用法说明 */
|
|
503
|
+
function printUsage(): void {
|
|
504
|
+
process.stderr.write(
|
|
505
|
+
[
|
|
506
|
+
'发布凭据闸门: 核对 npm 侧 Trusted Publisher 登记与当前仓库形态是否一致',
|
|
507
|
+
'',
|
|
508
|
+
'用法: bun scripts/npm-trust-guard.ts <命令>',
|
|
509
|
+
' verify-oidc CI 预检: 用 GitHub OIDC 对每包试一次 token exchange (需 id-token: write)',
|
|
510
|
+
' check 本地对账: npm trust list 与期望值比对, 只读',
|
|
511
|
+
' fix 本地修复: 对失配项 revoke + 重建 (需 npm 登录态与交互式终端)',
|
|
512
|
+
'',
|
|
513
|
+
].join('\n'),
|
|
514
|
+
);
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/** 入口: 分发子命令 (未知命令打用法并退 2) */
|
|
518
|
+
async function main(): Promise<void> {
|
|
519
|
+
const command = process.argv[2];
|
|
520
|
+
if (command === 'verify-oidc') {
|
|
521
|
+
await mainVerifyOidc();
|
|
522
|
+
return;
|
|
523
|
+
}
|
|
524
|
+
if (command === 'check' || command === 'fix') {
|
|
525
|
+
await mainLocal(command);
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
528
|
+
printUsage();
|
|
529
|
+
process.exitCode = 2;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
// 仅作为入口执行时跑主流程 (被 import 时不执行, 供测试)
|
|
533
|
+
if (import.meta.main) await main();
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* safe-install: 干净重装 — 清掉可再生的构建产物与锁文件, 再按 package.json 重新安装。
|
|
3
|
+
*
|
|
4
|
+
* 为什么: ① dist 是带"身份绑定"的构建产物 (见 ADR 0009), 陈旧产物会让入口优先跑到
|
|
5
|
+
* 与源码不一致的字节; ② 锁文件漂移或手改后, 声明与实装可能脱钩。两步合起来把依赖态
|
|
6
|
+
* 重置回"由 package.json 唯一决定"的干净点。
|
|
7
|
+
* 形态参考个人项目 buffett 的 `safe-install` (`clean report dist bunlock && bun i`);
|
|
8
|
+
* 这里以仓库内实现替代其全局 `clean` 工具, 保持本仓库对贡献者零私有依赖。
|
|
9
|
+
*/
|
|
10
|
+
import { spawnSync } from 'node:child_process';
|
|
11
|
+
import { rmSync } from 'node:fs';
|
|
12
|
+
import { fileURLToPath } from 'node:url';
|
|
13
|
+
|
|
14
|
+
const root = fileURLToPath(new URL('..', import.meta.url));
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* 本仓的可再生面: 构建产物、锁文件与依赖树本身
|
|
18
|
+
* (与 buffett `clean` 的 `dist` / `bunlock` / `modules` 任务对应; 树小, 连树清才修得掉
|
|
19
|
+
* bun install 只对齐、修不了的深脏: 被改过的包内容、平台错配残留等)。
|
|
20
|
+
* 构建产物: CLI 包产物 (packages/{{NAME}}-cli/dist) 在本脚本清理面内;
|
|
21
|
+
* API 包产物 (packages/{{NAME}}/dist) 不在清理面, 重建经 `bun run build`;
|
|
22
|
+
* 依赖树走 hoisted linker (bunfig.toml), 集中在一处, 清根即够。
|
|
23
|
+
*/
|
|
24
|
+
for (const target of [
|
|
25
|
+
'packages/{{NAME}}-cli/dist',
|
|
26
|
+
'bun.lock',
|
|
27
|
+
'node_modules',
|
|
28
|
+
]) {
|
|
29
|
+
rmSync(`${root}${target}`, { recursive: true, force: true });
|
|
30
|
+
console.log(`[safe-install] 已清理: ${target}`);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
console.log('[safe-install] 重新安装依赖 (bun install)…');
|
|
34
|
+
const result = spawnSync('bun', ['install'], { cwd: root, stdio: 'inherit' });
|
|
35
|
+
|
|
36
|
+
console.log(
|
|
37
|
+
'[safe-install] CLI 包 dist 已清 (API 包 dist 不在清理面); 跑测试 / 推送前先 bun run build 重建产物',
|
|
38
|
+
);
|
|
39
|
+
process.exit(result.status ?? 1);
|