@intra-mart/accel 0.4.0-dev.202607140628 → 0.4.0-dev.202607170346

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -316,6 +316,22 @@ ACCEL_API_KEY=*** accel deploy \
316
316
  - MCP 同期は best-effort で、いずれの段階で失敗してもコマンド自体の成否には影響しません。
317
317
  - 対象ファイル/対象エントリが無い場合や処理に失敗した場合も**ログは表示しません**。
318
318
 
319
+ ### pre-commit フックの自動配置
320
+
321
+ MCP 設定ファイルに反映された API キーを誤って git にコミット・pushしてしまう事故を防ぐため、接続情報の保存時(前述「[MCP 設定の自動同期](#mcp-設定の自動同期)」と同じタイミング)に pre-commit フックをプロジェクトへ自動配置します。
322
+
323
+ - 配置されるファイル:
324
+ - `.githooks/pre-commit` — コミット前チェックスクリプト
325
+ - `.githooks/.gitattributes` — フックスクリプトの改行コードを LF に固定
326
+ - 配置後、git の `core.hooksPath` に `.githooks` を自動設定し、フックを有効化します。
327
+ - `core.hooksPath` が既に**別の値**に設定されている場合(husky 等を利用中)は上書きせず、警告メッセージで手動組み込みを案内します。
328
+ - `.githooks` 配下に CLI が配置した以外のファイルが存在する場合も自動設定は行わず、警告メッセージで手動設定を案内します(リポジトリにコミットされた第三者のフックを意図せず有効化しないため)。
329
+ - フックは、ステージされた `.json` / `.toml` ファイルの追加行に intra-mart OAuth クライアントキー形式の文字列が含まれる場合、コミットをブロックします。
330
+ - 検出内容に問題がないことを確認した上でコミットしたい場合は `git commit --no-verify` で回避できます。
331
+ - 既に `.githooks/pre-commit` が存在する場合、CLI が配置したもの(マーカーコメントで判定)であれば最新版へ上書き更新し、ユーザーが独自に配置したものであればスキップして警告を表示します。
332
+ - プロジェクトが git リポジトリでない場合は何も行いません。
333
+ - この機能を無効化するには `.accel/settings.json` に `"gitHooks": false` を設定します(配置済みのフックは削除されないため、不要な場合は手動で削除してください)。
334
+
319
335
  ## IM-Juggling連携
320
336
 
321
337
  `--juggling-project` オプションでIM-Jugglingプロジェクトのパスを指定すると、`juggling.im` からiAPバージョンと使用モジュールを自動検出します。
@@ -353,6 +369,7 @@ my-project/
353
369
  - `.accel/settings.json` — プロジェクト設定。git管理対象、手動編集可。資材リポジトリのURL・ref・配備時のコミットSHA(`assetSource`)を記録し、`accel update` が参照
354
370
  - `.accel/hashsum.txt` — 配備ファイルのハッシュ。`update` / `detach` 時のユーザー編集検出に使用
355
371
  - `.accel/credentials.json` — iAP接続情報(endpoint / APIキー)。`accel deploy` 初回実行時に生成。APIキーを含むため `.gitignore` 対象(git管理対象外)
372
+ - `.githooks/` — APIキーの誤コミットを防ぐ pre-commit フック。`accel login` / `accel deploy` による接続情報の保存時に配置(詳細は「[pre-commit フックの自動配置](#pre-commit-フックの自動配置)」)
356
373
 
357
374
  `credentials.json` の保存/更新時には、エージェント別の MCP 設定ファイル(`.mcp.json` / `.codex/config.toml` / `.vscode/mcp.json` のうち、存在し、かつ `agents` に含まれるエージェントのもの)に対しても API キーが反映されます。詳細は「[MCP 設定の自動同期](#mcp-設定の自動同期)」を参照してください。
358
375
 
@@ -0,0 +1,2 @@
1
+ # @accel-cli-managed
2
+ * text eol=lf
@@ -0,0 +1,24 @@
1
+ {
2
+ "version": "1.0.0",
3
+ "type": "file",
4
+ "rename": [
5
+ {
6
+ "condition": {
7
+ "locale": "ja"
8
+ },
9
+ "from": "pre-commit_ja",
10
+ "to": "pre-commit"
11
+ },
12
+ {
13
+ "condition": {
14
+ "locale": "zh_CN"
15
+ },
16
+ "from": "pre-commit_zh_CN",
17
+ "to": "pre-commit"
18
+ },
19
+ {
20
+ "from": "pre-commit_en",
21
+ "to": "pre-commit"
22
+ }
23
+ ]
24
+ }
@@ -0,0 +1,268 @@
1
+ #!/usr/bin/env bash
2
+ # @accel-cli-managed
3
+ #
4
+ # pre-commit:
5
+ # A hook script that scans the staged changes for strings resembling
6
+ # sensitive information, and blocks the commit if any are detected.
7
+ #
8
+ # How to enable:
9
+ # chmod +x .githooks/pre-commit
10
+ # git config core.hooksPath .githooks
11
+ #
12
+ set -euo pipefail
13
+ shopt -s nocasematch
14
+
15
+ # =============================================================================
16
+ # Collect the diff
17
+ # =============================================================================
18
+
19
+ # Collect the diff in a single call, since calling git diff once per file
20
+ # would be extremely slow when many files are staged.
21
+ # The detection scope below is narrow, so the target files are filtered
22
+ # ahead of time via git's pathspec:
23
+ # - mcp config files (.json / .toml) where intra-mart OAuth client keys are written
24
+ diff_output=$(git diff --cached -U0 --no-color --diff-filter=ACMR -- '*.json' '*.toml' 2>/dev/null | tr -d '\0' || true)
25
+ if [ -z "$diff_output" ]; then
26
+ exit 0
27
+ fi
28
+
29
+ found=0
30
+ findings=()
31
+
32
+ # =============================================================================
33
+ # base64 decoding functions
34
+ # =============================================================================
35
+
36
+ # On environments where fork/exec is expensive (e.g. Git Bash on Windows),
37
+ # spawning a process per candidate token would slow the check down as the
38
+ # number of candidates grows, so base64 decoding is done with bash builtins
39
+ # only, without spawning external processes (base64/tr).
40
+ # To also work on stock /bin/bash 3.2 (still the default shipped on macOS),
41
+ # associative arrays (bash 4.0+) are avoided in favor of plain string search
42
+ # for the character-to-value lookup.
43
+ B64_ALPHABET="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
44
+
45
+ # Sets the 6-bit value of the given base64 character into B64_LAST_VAL.
46
+ # If not found, clears B64_LAST_VAL and returns 1.
47
+ _b64_char_value() {
48
+ case "$1" in
49
+ -) B64_LAST_VAL=62; return 0 ;;
50
+ _) B64_LAST_VAL=63; return 0 ;;
51
+ esac
52
+ local idx="${B64_ALPHABET%%"$1"*}"
53
+ if [ "$idx" = "$B64_ALPHABET" ]; then
54
+ B64_LAST_VAL=""
55
+ return 1
56
+ fi
57
+ B64_LAST_VAL=${#idx}
58
+ return 0
59
+ }
60
+
61
+ # Decodes the token string as base64 (urlsafe alphabet accepted too), and
62
+ # returns true if the decoded result consists only of the alphanumeric
63
+ # characters and symbols used in an intra-mart OAuth client key
64
+ # (a hex string + '@' + tenant ID).
65
+ decode_contains_at() {
66
+ local token="$1"
67
+ local len=${#token}
68
+ # Declare all locals up front instead of re-declaring them on every loop
69
+ # iteration, to avoid the repeated `local` overhead.
70
+ local i=0 has_at=1 c0 c1 c2 c3 v0 v1 v2 v3 nbytes val b1 b2 b3
71
+
72
+ while (( i < len )); do
73
+ # base64 restores "3 bytes (8bit x 3)" from "4 characters (6bit x 4)",
74
+ # so the token is processed 4 characters at a time from the start.
75
+ c0="${token:i:1}"; c1="${token:i+1:1}"; c2="${token:i+2:1}"; c3="${token:i+3:1}"
76
+ [[ -z "$c0" || -z "$c1" ]] && break
77
+
78
+ # Convert each character to its position in the base64 alphabet
79
+ # (a 6-bit value, 0-63).
80
+ _b64_char_value "$c0" || return 1
81
+ v0=$B64_LAST_VAL
82
+ _b64_char_value "$c1" || return 1
83
+ v1=$B64_LAST_VAL
84
+
85
+ # If the 3rd/4th character is padding ("=") or absent, the number of
86
+ # bytes that can be restored from this group is less than 3
87
+ # (only the last group of a base64 string can restore 2 or 1 bytes).
88
+ nbytes=3; v2=0; v3=0
89
+ if [[ -z "$c2" || "$c2" == "=" ]]; then
90
+ nbytes=1
91
+ else
92
+ _b64_char_value "$c2" || return 1
93
+ v2=$B64_LAST_VAL
94
+ if [[ -z "$c3" || "$c3" == "=" ]]; then
95
+ nbytes=2
96
+ else
97
+ _b64_char_value "$c3" || return 1
98
+ v3=$B64_LAST_VAL
99
+ fi
100
+ fi
101
+
102
+ # Combine the four 6-bit values (v0-v3, 24 bits total) into a single
103
+ # integer, then split it back into three 8-bit bytes to restore the
104
+ # original byte sequence.
105
+ # 6bit x 4 = [v0][v1][v2][v3] -> 8bit x 3 = [b1][b2][b3]
106
+ val=$(( (v0 * 262144) + (v1 * 4096) + (v2 * 64) + v3 ))
107
+ b1=$(( (val / 65536) % 256 ))
108
+
109
+ # If a byte value that is never used in an intra-mart OAuth client key
110
+ # is found, skip further evaluation to avoid a false positive.
111
+ (( (b1 >= 48 && b1 <= 57) || (b1 >= 65 && b1 <= 90) || (b1 >= 97 && b1 <= 122) || b1 == 64 || b1 == 95 || b1 == 45 )) || return 1
112
+
113
+ # If the 1st byte is "@" (64 in decimal), this may be an intra-mart
114
+ # OAuth client key, so set has_at to 0.
115
+ (( b1 == 64 )) && has_at=0
116
+
117
+ # Apply the same check to the 2nd/3rd byte as for b1.
118
+ # If only 1 byte can be restored from this group (nbytes=1), b2/b3
119
+ # don't exist, so the check itself is skipped based on nbytes.
120
+ if (( nbytes >= 2 )); then
121
+ b2=$(( (val / 256) % 256 ))
122
+ (( (b2 >= 48 && b2 <= 57) || (b2 >= 65 && b2 <= 90) || (b2 >= 97 && b2 <= 122) || b2 == 64 || b2 == 95 || b2 == 45 )) || return 1
123
+ (( b2 == 64 )) && has_at=0
124
+ fi
125
+ if (( nbytes >= 3 )); then
126
+ b3=$(( val % 256 ))
127
+ (( (b3 >= 48 && b3 <= 57) || (b3 >= 65 && b3 <= 90) || (b3 >= 97 && b3 <= 122) || b3 == 64 || b3 == 95 || b3 == 45 )) || return 1
128
+ (( b3 == 64 )) && has_at=0
129
+ fi
130
+
131
+ # Once a group restoring fewer than 3 bytes appears, that is the end of
132
+ # the token (it was padded), so the loop is exited. Otherwise, advance
133
+ # to the next 4 characters.
134
+ (( nbytes < 3 )) && break
135
+ i=$((i + 4))
136
+ done
137
+
138
+ # Reaching here means the whole token was scanned, so the string consists
139
+ # only of alphanumeric characters and symbols. If "@" was found along the
140
+ # way, has_at=0 (success), and that value is returned as-is.
141
+ return "$has_at"
142
+ }
143
+
144
+ # =============================================================================
145
+ # Function that checks base64-like tokens in added lines
146
+ # =============================================================================
147
+
148
+ # Cache of decode results to avoid re-decoding the same token.
149
+ # Caches the result of passing the candidate string to decode_contains_at(),
150
+ # keyed by the token string itself. Associative arrays (bash 4.0+) are not used.
151
+ TOKENS_MATCHED=$'\x01'
152
+ TOKENS_UNMATCHED=$'\x01'
153
+
154
+ # Extracts every base64-like token of 40+ characters from a single added
155
+ # line using a regex, and passes each token to decode_contains_at() to judge
156
+ # whether it looks like an intra-mart OAuth client key. If so, appends the
157
+ # finding to findings and sets found=1.
158
+ check_base64_tokens() {
159
+ local file="$1" lineno="$2" content="$3"
160
+ # A candidate token cannot exist below 40 characters, so bail out before
161
+ # entering the regex loop.
162
+ (( ${#content} < 40 )) && return
163
+ local remaining="$content" token is_match
164
+
165
+ # Extract candidate tokens using bash's built-in regex matching only
166
+ # (spawning a grep subprocess per line would be extremely slow when many
167
+ # files are changed).
168
+ while [[ "$remaining" =~ ([A-Za-z0-9+/_-]{40,}={0,2}) ]]; do
169
+ token="${BASH_REMATCH[1]}"
170
+ remaining="${remaining#*"$token"}"
171
+
172
+ # The same token can appear across multiple files/lines (e.g. the same
173
+ # config copied to multiple places), so the judgment result is cached
174
+ # and reused, while still recording a finding for every occurrence.
175
+ if [[ "$TOKENS_MATCHED" == *$'\x01'"$token"$'\x01'* ]]; then
176
+ is_match=0
177
+ elif [[ "$TOKENS_UNMATCHED" == *$'\x01'"$token"$'\x01'* ]]; then
178
+ is_match=1
179
+ elif decode_contains_at "$token"; then
180
+ TOKENS_MATCHED+="$token"$'\x01'
181
+ is_match=0
182
+ else
183
+ TOKENS_UNMATCHED+="$token"$'\x01'
184
+ is_match=1
185
+ fi
186
+
187
+ if (( is_match == 0 )); then
188
+ findings+=("[$file:$lineno] Found an intra-mart OAuth client key string: ${token:0:12}...")
189
+ found=1
190
+ fi
191
+ done
192
+ }
193
+
194
+ # =============================================================================
195
+ # Check every line of the diff
196
+ # =============================================================================
197
+
198
+ # The detection scope below is narrow, so only the following extensions are
199
+ # targeted:
200
+ # - mcp config files (.json / .toml) where intra-mart OAuth client keys are written
201
+ INCLUDE_FILE_RE='\.(json|toml)$'
202
+
203
+ # package-lock.json contains many hash-like strings that are easily
204
+ # mistaken for auth keys, so it is excluded from scanning.
205
+ EXCLUDE_FILE_RE='(^|/)package-lock\.json$'
206
+
207
+ current_file=""
208
+ current_line=0
209
+ is_binary=0
210
+ skip_file=0
211
+
212
+ while IFS= read -r line; do
213
+ case "$line" in
214
+ "diff --git "*)
215
+ # e.g. diff --git a/path/to/file b/path/to/file
216
+ current_file="${line#diff --git a/}"
217
+ current_file="${current_file%% b/*}"
218
+ is_binary=0
219
+ if [[ "$current_file" =~ $INCLUDE_FILE_RE ]] && [[ ! "$current_file" =~ $EXCLUDE_FILE_RE ]]; then
220
+ skip_file=0
221
+ else
222
+ skip_file=1
223
+ fi
224
+ ;;
225
+ "Binary files "*|"GIT binary patch"*)
226
+ is_binary=1
227
+ ;;
228
+ "@@ "*)
229
+ # e.g. @@ -12,0 +13,2 @@ ... -> get the starting line number (13) on the new-file side
230
+ if [[ "$line" =~ \+([0-9]+) ]]; then
231
+ current_line="${BASH_REMATCH[1]}"
232
+ fi
233
+ ;;
234
+ "+++ "*|"--- "*)
235
+ : # ignore diff header lines
236
+ ;;
237
+ "+"*)
238
+ if (( is_binary == 1 || skip_file == 1 )); then
239
+ continue
240
+ fi
241
+ content="${line#+}"
242
+ check_base64_tokens "$current_file" "$current_line" "$content"
243
+ current_line=$((current_line + 1))
244
+ ;;
245
+ *)
246
+ : ;;
247
+ esac
248
+ done <<< "$diff_output"
249
+
250
+ # =============================================================================
251
+ # Display the detection results
252
+ # =============================================================================
253
+
254
+ if [ "$found" -eq 1 ]; then
255
+ echo "----------------------------------------------------------------------"
256
+ echo "🚫 Commit blocked: strings resembling sensitive information were detected"
257
+ echo "----------------------------------------------------------------------"
258
+ for msg in "${findings[@]}"; do
259
+ echo " - $msg"
260
+ done
261
+ echo ""
262
+ echo "The locations above may contain strings resembling sensitive information."
263
+ echo "Please review the content before committing, and remove or replace it if needed."
264
+ echo "If this detection is not an issue, bypass it with: git commit --no-verify"
265
+ exit 1
266
+ fi
267
+
268
+ exit 0
@@ -0,0 +1,255 @@
1
+ #!/usr/bin/env bash
2
+ # @accel-cli-managed
3
+ #
4
+ # pre-commit:
5
+ # git にステージされた変更内容に Authentication ヘッダや API キーに類似した文字列が
6
+ # コード上に含まれていないかチェックし、検出時はコミットをブロックする hook スクリプト。
7
+ #
8
+ # 有効化方法:
9
+ # chmod +x .githooks/pre-commit
10
+ # git config core.hooksPath .githooks
11
+ #
12
+ set -euo pipefail
13
+ shopt -s nocasematch
14
+
15
+ # =============================================================================
16
+ # 変更内容の差分を取得
17
+ # =============================================================================
18
+
19
+ # ファイル数分 git diff を呼ぶと大量ファイル変更時に著しく遅くなるため、差分取得は 1回にまとめる。
20
+ # 検出対象は以下に限定するため、git diff の対象ファイルをあらかじめ絞り込む。
21
+ # - intra-mart OAuth クライアントキーが記載される mcp 設定ファイル(.json / .toml)
22
+ diff_output=$(git diff --cached -U0 --no-color --diff-filter=ACMR -- '*.json' '*.toml' 2>/dev/null | tr -d '\0' || true)
23
+ if [ -z "$diff_output" ]; then
24
+ exit 0
25
+ fi
26
+
27
+ found=0
28
+ findings=()
29
+
30
+ # =============================================================================
31
+ # base64 デコード関数
32
+ # =============================================================================
33
+
34
+ # Git Bash (Windows) 等 fork/exec が高コストな環境では、
35
+ # 候補トークン数に比例してプロセス起動が積み重なり、チェック動作が遅くなるため、
36
+ # base64 デコードは外部プロセス(base64/tr)を起動せず bash 組み込み演算のみで行う。
37
+ # macOS 標準の /bin/bash 3.2 でも動作させるため、
38
+ # 連想配列(bash 4.0+)は使わず、文字列検索で文字から値へ変換する。
39
+ B64_ALPHABET="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
40
+
41
+ # 指定した base64 文字の 6bit 値を変数 B64_LAST_VAL にセットする。
42
+ # 見つからない場合は B64_LAST_VAL を空にして 1 を返却する。
43
+ _b64_char_value() {
44
+ case "$1" in
45
+ -) B64_LAST_VAL=62; return 0 ;;
46
+ _) B64_LAST_VAL=63; return 0 ;;
47
+ esac
48
+ local idx="${B64_ALPHABET%%"$1"*}"
49
+ if [ "$idx" = "$B64_ALPHABET" ]; then
50
+ B64_LAST_VAL=""
51
+ return 1
52
+ fi
53
+ B64_LAST_VAL=${#idx}
54
+ return 0
55
+ }
56
+
57
+ # トークン文字列を base64(urlsafe も許容)としてデコードし、
58
+ # intra-mart OAuth クライアントキー(16 進文字列 + '@' + テナントID)で使われる英数字+記号で
59
+ # 構成される場合に true を返却する。
60
+ decode_contains_at() {
61
+ local token="$1"
62
+ local len=${#token}
63
+ # ループ内で毎回 local 宣言をやり直すコストを避けるため、変数は先に一括宣言する
64
+ local i=0 has_at=1 c0 c1 c2 c3 v0 v1 v2 v3 nbytes val b1 b2 b3
65
+
66
+ while (( i < len )); do
67
+ # base64 は「4文字(6bit×4)」から「3バイト(8bit×3)」を復元する仕組みのため、
68
+ # 先頭から4文字ずつ切り出して処理する。
69
+ c0="${token:i:1}"; c1="${token:i+1:1}"; c2="${token:i+2:1}"; c3="${token:i+3:1}"
70
+ [[ -z "$c0" || -z "$c1" ]] && break
71
+
72
+ # 各文字を base64 アルファベット上の位置(6bit の値, 0〜63)に変換する
73
+ _b64_char_value "$c0" || return 1
74
+ v0=$B64_LAST_VAL
75
+ _b64_char_value "$c1" || return 1
76
+ v1=$B64_LAST_VAL
77
+
78
+ # 3, 4文字目がパディング("=")または存在しない場合、
79
+ # このグループから復元できるバイト数は 3 未満になる。
80
+ # (base64 は末尾グループのみ 2 バイト・1 バイト復元になる可能性がある)
81
+ nbytes=3; v2=0; v3=0
82
+ if [[ -z "$c2" || "$c2" == "=" ]]; then
83
+ nbytes=1
84
+ else
85
+ _b64_char_value "$c2" || return 1
86
+ v2=$B64_LAST_VAL
87
+ if [[ -z "$c3" || "$c3" == "=" ]]; then
88
+ nbytes=2
89
+ else
90
+ _b64_char_value "$c3" || return 1
91
+ v3=$B64_LAST_VAL
92
+ fi
93
+ fi
94
+
95
+ # 4つの 6bit 値(v0〜v3, 計 24bit)を1つの整数に結合し、
96
+ # 8bit ずつ 3 つに割り直すことで元のバイト列を復元する。
97
+ # 6bit×4 = [v0][v1][v2][v3] → 8bit×3 = [b1][b2][b3]
98
+ val=$(( (v0 * 262144) + (v1 * 4096) + (v2 * 64) + v3 ))
99
+ b1=$(( (val / 65536) % 256 ))
100
+
101
+ # intra-mart OAuth クライアントキーで使われないバイト値が含まれている場合は、
102
+ # 誤検知を防止するために、判定をスキップする。
103
+ (( (b1 >= 48 && b1 <= 57) || (b1 >= 65 && b1 <= 90) || (b1 >= 97 && b1 <= 122) || b1 == 64 || b1 == 95 || b1 == 45 )) || return 1
104
+
105
+ # 1バイト目が "@"(10 進数で 64)であれば、
106
+ # intra-mart OAuth クライアントキーである可能性があるため、
107
+ # has_at を 0 にする。
108
+ (( b1 == 64 )) && has_at=0
109
+
110
+ # 2バイト目・3バイト目についても b1 と同様の判定を行う。
111
+ # ただし、このグループから復元できるのが 1 バイトのみ(nbytes=1)の場合は、
112
+ # b2・b3 は存在しないため、nbytes に応じて判定自体をスキップする。
113
+ if (( nbytes >= 2 )); then
114
+ b2=$(( (val / 256) % 256 ))
115
+ (( (b2 >= 48 && b2 <= 57) || (b2 >= 65 && b2 <= 90) || (b2 >= 97 && b2 <= 122) || b2 == 64 || b2 == 95 || b2 == 45 )) || return 1
116
+ (( b2 == 64 )) && has_at=0
117
+ fi
118
+ if (( nbytes >= 3 )); then
119
+ b3=$(( val % 256 ))
120
+ (( (b3 >= 48 && b3 <= 57) || (b3 >= 65 && b3 <= 90) || (b3 >= 97 && b3 <= 122) || b3 == 64 || b3 == 95 || b3 == 45 )) || return 1
121
+ (( b3 == 64 )) && has_at=0
122
+ fi
123
+
124
+ # 3バイトに満たないグループが出た時点で、それがトークンの末尾になる(パディング済み)。
125
+ # そのため、ループを抜ける。それ以外の場合は、次の4文字へ進む。
126
+ (( nbytes < 3 )) && break
127
+ i=$((i + 4))
128
+ done
129
+
130
+ # トークン全体を最後まで走査できた場合は、文字列が英数字+記号で構成される。
131
+ # その中で、"@" が含まれていた場合は、has_at=0(成功)となり、その値を戻り値として返却する。
132
+ return "$has_at"
133
+ }
134
+
135
+ # =============================================================================
136
+ # 追加行の base64 風トークンをチェックする関数
137
+ # =============================================================================
138
+
139
+ # 同一トークンの再デコードを避けるための判定結果キャッシュ。
140
+ # 検出対象の文字列を decode_contains_at() に渡した結果を、トークン文字列ごとにキャッシュする。
141
+ # 連想配列(bash 4.0+)は使用しない。
142
+ TOKENS_MATCHED=$'\x01'
143
+ TOKENS_UNMATCHED=$'\x01'
144
+
145
+ # 追加行 1行から 40文字以上の base64 風トークンを正規表現ですべて抜き出し、
146
+ # 各トークンを decode_contains_at() に渡して intra-mart OAuth クライアントキー形式かどうかを判定する。
147
+ # 該当すれば findings に検出内容を追記し found=1 をセットする。
148
+ check_base64_tokens() {
149
+ local file="$1" lineno="$2" content="$3"
150
+ # 40 文字未満なら候補トークンは存在しないため、処理を終了する。
151
+ (( ${#content} < 40 )) && return
152
+ local remaining="$content" token is_match
153
+
154
+ # 行ごとに grep サブプロセスを起動すると、大量ファイル変更時に著しく遅くなるため、
155
+ # bash 組み込みの正規表現マッチのみで候補トークンを抽出する。
156
+ while [[ "$remaining" =~ ([A-Za-z0-9+/_-]{40,}={0,2}) ]]; do
157
+ token="${BASH_REMATCH[1]}"
158
+ remaining="${remaining#*"$token"}"
159
+
160
+ # 同じトークンが複数ファイル・複数行に出現するケース(同じ設定を複数箇所に
161
+ # コピーした場合等)があるため、判定結果はキャッシュを使い回しつつ、
162
+ # 出現箇所ごとに findings へ記録する。
163
+ if [[ "$TOKENS_MATCHED" == *$'\x01'"$token"$'\x01'* ]]; then
164
+ is_match=0
165
+ elif [[ "$TOKENS_UNMATCHED" == *$'\x01'"$token"$'\x01'* ]]; then
166
+ is_match=1
167
+ elif decode_contains_at "$token"; then
168
+ TOKENS_MATCHED+="$token"$'\x01'
169
+ is_match=0
170
+ else
171
+ TOKENS_UNMATCHED+="$token"$'\x01'
172
+ is_match=1
173
+ fi
174
+
175
+ if (( is_match == 0 )); then
176
+ findings+=("[$file:$lineno] intra-mart OAuth クライアントキー文字列を検出しました: ${token:0:12}...")
177
+ found=1
178
+ fi
179
+ done
180
+ }
181
+
182
+ # =============================================================================
183
+ # 差分の各行をチェック
184
+ # =============================================================================
185
+
186
+ # 検出対象は以下に限定するため、一部の拡張子のみを対象とする。
187
+ # - intra-mart OAuth クライアントキーが記載される mcp 設定ファイル(.json / .toml)
188
+ INCLUDE_FILE_RE='\.(json|toml)$'
189
+
190
+ # package-lock.json は大量のハッシュ文字列が認証キーと誤認されやすいため、
191
+ # スキャン対象から除外する。
192
+ EXCLUDE_FILE_RE='(^|/)package-lock\.json$'
193
+
194
+ current_file=""
195
+ current_line=0
196
+ is_binary=0
197
+ skip_file=0
198
+
199
+ while IFS= read -r line; do
200
+ case "$line" in
201
+ "diff --git "*)
202
+ # 例: diff --git a/path/to/file b/path/to/file
203
+ current_file="${line#diff --git a/}"
204
+ current_file="${current_file%% b/*}"
205
+ is_binary=0
206
+ if [[ "$current_file" =~ $INCLUDE_FILE_RE ]] && [[ ! "$current_file" =~ $EXCLUDE_FILE_RE ]]; then
207
+ skip_file=0
208
+ else
209
+ skip_file=1
210
+ fi
211
+ ;;
212
+ "Binary files "*|"GIT binary patch"*)
213
+ is_binary=1
214
+ ;;
215
+ "@@ "*)
216
+ # 例: @@ -12,0 +13,2 @@ ... → 新ファイル側の開始行番号 (13) を取得する
217
+ if [[ "$line" =~ \+([0-9]+) ]]; then
218
+ current_line="${BASH_REMATCH[1]}"
219
+ fi
220
+ ;;
221
+ "+++ "*|"--- "*)
222
+ : # diff ヘッダ行は無視
223
+ ;;
224
+ "+"*)
225
+ if (( is_binary == 1 || skip_file == 1 )); then
226
+ continue
227
+ fi
228
+ content="${line#+}"
229
+ check_base64_tokens "$current_file" "$current_line" "$content"
230
+ current_line=$((current_line + 1))
231
+ ;;
232
+ *)
233
+ : ;;
234
+ esac
235
+ done <<< "$diff_output"
236
+
237
+ # =============================================================================
238
+ # 検出結果の表示
239
+ # =============================================================================
240
+
241
+ if [ "$found" -eq 1 ]; then
242
+ echo "----------------------------------------------------------------------"
243
+ echo "🚫 コミットを中止しました: 機密情報に類似する文字列が検出されました"
244
+ echo "----------------------------------------------------------------------"
245
+ for msg in "${findings[@]}"; do
246
+ echo " - $msg"
247
+ done
248
+ echo ""
249
+ echo "上記の箇所に、機密情報に類似する文字列が含まれている可能性があります。"
250
+ echo "コミット前に必ず内容を確認し、必要に応じて削除するか、他の文字列に置き換えてください。"
251
+ echo "検出内容に問題がない場合は、git commit --no-verify で回避してください。"
252
+ exit 1
253
+ fi
254
+
255
+ exit 0
@@ -0,0 +1,255 @@
1
+ #!/usr/bin/env bash
2
+ # @accel-cli-managed
3
+ #
4
+ # pre-commit:
5
+ # 扫描已暂存到 git 的变更内容中是否包含疑似敏感信息的字符串,
6
+ # 若检测到则阻止本次提交的 hook 脚本。
7
+ #
8
+ # 启用方法:
9
+ # chmod +x .githooks/pre-commit
10
+ # git config core.hooksPath .githooks
11
+ #
12
+ set -euo pipefail
13
+ shopt -s nocasematch
14
+
15
+ # =============================================================================
16
+ # 获取变更差异
17
+ # =============================================================================
18
+
19
+ # 如果按文件数逐个调用 git diff,在变更文件较多时会显著变慢,
20
+ # 因此差异获取统一合并为 1 次。
21
+ # 由于检测范围仅限于以下内容,因此通过 git 的路径规格预先筛选目标文件:
22
+ # - 记载 intra-mart OAuth 客户端密钥的 mcp 配置文件(.json / .toml)
23
+ diff_output=$(git diff --cached -U0 --no-color --diff-filter=ACMR -- '*.json' '*.toml' 2>/dev/null | tr -d '\0' || true)
24
+ if [ -z "$diff_output" ]; then
25
+ exit 0
26
+ fi
27
+
28
+ found=0
29
+ findings=()
30
+
31
+ # =============================================================================
32
+ # base64 解码函数
33
+ # =============================================================================
34
+
35
+ # 在 Git Bash (Windows) 等 fork/exec 成本较高的环境中,若按候选 token
36
+ # 数量逐一启动进程,检查动作将随候选数量增多而变慢,
37
+ # 因此 base64 解码不启动外部进程(base64/tr),仅使用 bash 内置运算完成。
38
+ # 为了在 macOS 系统自带的 /bin/bash 3.2 上也能运行,
39
+ # 不使用关联数组(bash 4.0+),改用字符串检索完成字符到数值的转换。
40
+ B64_ALPHABET="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
41
+
42
+ # 将指定 base64 字符对应的 6bit 数值写入变量 B64_LAST_VAL。
43
+ # 若找不到,则将 B64_LAST_VAL 置空并返回 1。
44
+ _b64_char_value() {
45
+ case "$1" in
46
+ -) B64_LAST_VAL=62; return 0 ;;
47
+ _) B64_LAST_VAL=63; return 0 ;;
48
+ esac
49
+ local idx="${B64_ALPHABET%%"$1"*}"
50
+ if [ "$idx" = "$B64_ALPHABET" ]; then
51
+ B64_LAST_VAL=""
52
+ return 1
53
+ fi
54
+ B64_LAST_VAL=${#idx}
55
+ return 0
56
+ }
57
+
58
+ # 将 token 字符串以 base64(同时兼容 urlsafe 字符集)解码,若解码结果
59
+ # 仅由 intra-mart OAuth 客户端密钥(16进制字符串 + '@' + 租户ID)所使用的
60
+ # 英数字与符号构成,则返回 true。
61
+ decode_contains_at() {
62
+ local token="$1"
63
+ local len=${#token}
64
+ # 为避免循环体内每次都重新执行 local 声明带来的开销,变量统一在循环外一次性声明
65
+ local i=0 has_at=1 c0 c1 c2 c3 v0 v1 v2 v3 nbytes val b1 b2 b3
66
+
67
+ while (( i < len )); do
68
+ # base64 是从「4个字符(6bit×4)」还原「3个字节(8bit×3)」的机制,
69
+ # 因此从头开始每次截取 4 个字符进行处理。
70
+ c0="${token:i:1}"; c1="${token:i+1:1}"; c2="${token:i+2:1}"; c3="${token:i+3:1}"
71
+ [[ -z "$c0" || -z "$c1" ]] && break
72
+
73
+ # 将每个字符转换为其在 base64 字母表中的位置(6bit 数值,0〜63)
74
+ _b64_char_value "$c0" || return 1
75
+ v0=$B64_LAST_VAL
76
+ _b64_char_value "$c1" || return 1
77
+ v1=$B64_LAST_VAL
78
+
79
+ # 若第 3、4 个字符是填充符("=")或不存在,
80
+ # 则该分组能还原的字节数会少于 3。
81
+ # (base64 仅末尾分组可能还原为 2 字节或 1 字节)
82
+ nbytes=3; v2=0; v3=0
83
+ if [[ -z "$c2" || "$c2" == "=" ]]; then
84
+ nbytes=1
85
+ else
86
+ _b64_char_value "$c2" || return 1
87
+ v2=$B64_LAST_VAL
88
+ if [[ -z "$c3" || "$c3" == "=" ]]; then
89
+ nbytes=2
90
+ else
91
+ _b64_char_value "$c3" || return 1
92
+ v3=$B64_LAST_VAL
93
+ fi
94
+ fi
95
+
96
+ # 将 4 个 6bit 数值(v0〜v3,共 24bit)合并为一个整数,
97
+ # 再按 8bit 拆分为 3 个字节,从而还原出原始字节序列。
98
+ # 6bit×4 = [v0][v1][v2][v3] → 8bit×3 = [b1][b2][b3]
99
+ val=$(( (v0 * 262144) + (v1 * 4096) + (v2 * 64) + v3 ))
100
+ b1=$(( (val / 65536) % 256 ))
101
+
102
+ # 若出现 intra-mart OAuth 客户端密钥中不会使用的字节值,
103
+ # 为避免误判,跳过后续判定。
104
+ (( (b1 >= 48 && b1 <= 57) || (b1 >= 65 && b1 <= 90) || (b1 >= 97 && b1 <= 122) || b1 == 64 || b1 == 95 || b1 == 45 )) || return 1
105
+
106
+ # 若第 1 个字节为 "@"(十进制 64),
107
+ # 则可能是 intra-mart OAuth 客户端密钥,
108
+ # 将 has_at 置为 0。
109
+ (( b1 == 64 )) && has_at=0
110
+
111
+ # 第 2、3 个字节也进行与 b1 相同的判定。
112
+ # 但若该分组只能还原 1 个字节(nbytes=1),
113
+ # 则 b2、b3 不存在,因此根据 nbytes 跳过判定本身。
114
+ if (( nbytes >= 2 )); then
115
+ b2=$(( (val / 256) % 256 ))
116
+ (( (b2 >= 48 && b2 <= 57) || (b2 >= 65 && b2 <= 90) || (b2 >= 97 && b2 <= 122) || b2 == 64 || b2 == 95 || b2 == 45 )) || return 1
117
+ (( b2 == 64 )) && has_at=0
118
+ fi
119
+ if (( nbytes >= 3 )); then
120
+ b3=$(( val % 256 ))
121
+ (( (b3 >= 48 && b3 <= 57) || (b3 >= 65 && b3 <= 90) || (b3 >= 97 && b3 <= 122) || b3 == 64 || b3 == 95 || b3 == 45 )) || return 1
122
+ (( b3 == 64 )) && has_at=0
123
+ fi
124
+
125
+ # 一旦出现还原字节数不足 3 的分组,说明该分组即为 token 的末尾(已填充)。
126
+ # 因此退出循环;否则继续处理下 4 个字符。
127
+ (( nbytes < 3 )) && break
128
+ i=$((i + 4))
129
+ done
130
+
131
+ # 能扫描到 token 末尾,说明该字符串仅由英数字与符号构成。
132
+ # 期间若发现 "@",则 has_at=0(成功),并将该值作为返回值返回。
133
+ return "$has_at"
134
+ }
135
+
136
+ # =============================================================================
137
+ # 检查添加行中 base64 风格 token 的函数
138
+ # =============================================================================
139
+
140
+ # 用于避免重复解码同一 token 的判定结果缓存。
141
+ # 以 token 字符串本身为键,缓存传给 decode_contains_at() 后得到的判定结果。
142
+ # 不使用关联数组(bash 4.0+)。
143
+ TOKENS_MATCHED=$'\x01'
144
+ TOKENS_UNMATCHED=$'\x01'
145
+
146
+ # 从每一行添加行中,用正则表达式提取所有 40 个字符以上的 base64 风格 token,
147
+ # 并将每个 token 传给 decode_contains_at() 判定是否为 intra-mart OAuth 客户端密钥格式。
148
+ # 命中则将检测内容追加到 findings 并设置 found=1。
149
+ check_base64_tokens() {
150
+ local file="$1" lineno="$2" content="$3"
151
+ # 不足 40 个字符则不可能存在候选 token,在进入正则循环前直接返回。
152
+ (( ${#content} < 40 )) && return
153
+ local remaining="$content" token is_match
154
+
155
+ # 若按行启动 grep 子进程,在变更文件较多时会显著变慢,
156
+ # 因此仅使用 bash 内置正则匹配提取候选 token。
157
+ while [[ "$remaining" =~ ([A-Za-z0-9+/_-]{40,}={0,2}) ]]; do
158
+ token="${BASH_REMATCH[1]}"
159
+ remaining="${remaining#*"$token"}"
160
+
161
+ # 同一 token 可能出现在多个文件或多行中(例如将同一配置复制到多处),
162
+ # 因此判定结果会复用缓存,但每次出现都会记录到 findings 中。
163
+ if [[ "$TOKENS_MATCHED" == *$'\x01'"$token"$'\x01'* ]]; then
164
+ is_match=0
165
+ elif [[ "$TOKENS_UNMATCHED" == *$'\x01'"$token"$'\x01'* ]]; then
166
+ is_match=1
167
+ elif decode_contains_at "$token"; then
168
+ TOKENS_MATCHED+="$token"$'\x01'
169
+ is_match=0
170
+ else
171
+ TOKENS_UNMATCHED+="$token"$'\x01'
172
+ is_match=1
173
+ fi
174
+
175
+ if (( is_match == 0 )); then
176
+ findings+=("[$file:$lineno] 检测到 intra-mart OAuth 客户端密钥字符串: ${token:0:12}...")
177
+ found=1
178
+ fi
179
+ done
180
+ }
181
+
182
+ # =============================================================================
183
+ # 检查差异中的每一行
184
+ # =============================================================================
185
+
186
+ # 由于检测范围仅限于以下内容,因此仅将下述扩展名作为检测对象。
187
+ # - 记载 intra-mart OAuth 客户端密钥的 mcp 配置文件(.json / .toml)
188
+ INCLUDE_FILE_RE='\.(json|toml)$'
189
+
190
+ # package-lock.json 中包含大量容易被误判为认证密钥的哈希类字符串,
191
+ # 因此从扫描对象中排除。
192
+ EXCLUDE_FILE_RE='(^|/)package-lock\.json$'
193
+
194
+ current_file=""
195
+ current_line=0
196
+ is_binary=0
197
+ skip_file=0
198
+
199
+ while IFS= read -r line; do
200
+ case "$line" in
201
+ "diff --git "*)
202
+ # 例如: diff --git a/path/to/file b/path/to/file
203
+ current_file="${line#diff --git a/}"
204
+ current_file="${current_file%% b/*}"
205
+ is_binary=0
206
+ if [[ "$current_file" =~ $INCLUDE_FILE_RE ]] && [[ ! "$current_file" =~ $EXCLUDE_FILE_RE ]]; then
207
+ skip_file=0
208
+ else
209
+ skip_file=1
210
+ fi
211
+ ;;
212
+ "Binary files "*|"GIT binary patch"*)
213
+ is_binary=1
214
+ ;;
215
+ "@@ "*)
216
+ # 例如: @@ -12,0 +13,2 @@ ... → 获取新文件一侧的起始行号(13)
217
+ if [[ "$line" =~ \+([0-9]+) ]]; then
218
+ current_line="${BASH_REMATCH[1]}"
219
+ fi
220
+ ;;
221
+ "+++ "*|"--- "*)
222
+ : # 忽略 diff 头部行
223
+ ;;
224
+ "+"*)
225
+ if (( is_binary == 1 || skip_file == 1 )); then
226
+ continue
227
+ fi
228
+ content="${line#+}"
229
+ check_base64_tokens "$current_file" "$current_line" "$content"
230
+ current_line=$((current_line + 1))
231
+ ;;
232
+ *)
233
+ : ;;
234
+ esac
235
+ done <<< "$diff_output"
236
+
237
+ # =============================================================================
238
+ # 显示检测结果
239
+ # =============================================================================
240
+
241
+ if [ "$found" -eq 1 ]; then
242
+ echo "----------------------------------------------------------------------"
243
+ echo "🚫 已阻止提交:检测到疑似敏感信息的字符串"
244
+ echo "----------------------------------------------------------------------"
245
+ for msg in "${findings[@]}"; do
246
+ echo " - $msg"
247
+ done
248
+ echo ""
249
+ echo "以上位置可能包含疑似敏感信息的字符串。"
250
+ echo "请在提交前务必确认内容,并按需删除或替换为其他字符串。"
251
+ echo "如确认检测内容没有问题,可使用 git commit --no-verify 跳过本次检查。"
252
+ exit 1
253
+ fi
254
+
255
+ exit 0
@@ -16,10 +16,6 @@ const fileExists = async (path) => {
16
16
  return false;
17
17
  }
18
18
  };
19
- const dirnamePosix = (p) => {
20
- const idx = p.lastIndexOf("/");
21
- return idx === -1 ? "" : p.slice(0, idx);
22
- };
23
19
  const isWithinDir = (parentDir, candidate) => {
24
20
  const parent = resolve(parentDir);
25
21
  const target = resolve(candidate);
@@ -68,7 +64,7 @@ export const deployAssets = async (options) => {
68
64
  });
69
65
  progress?.onDownloadStart?.();
70
66
  await provider.materialize([
71
- ...new Set(entries.map((e) => dirnamePosix(e.sourceRelPath))),
67
+ ...new Set(entries.map((e) => e.sourceRelPath)),
72
68
  ]);
73
69
  const deployedFiles = [];
74
70
  const hashEntries = [];
@@ -2,7 +2,7 @@ import type { AssetProvider } from "../core/types.js";
2
2
  export type CommitTree = {
3
3
  listFiles: () => Promise<string[]>;
4
4
  readFile: (relPath: string) => Promise<string>;
5
- materialize: (dirs: string[]) => Promise<void>;
5
+ materialize: (files: string[]) => Promise<void>;
6
6
  };
7
7
  export type GitAssetProvider = AssetProvider & {
8
8
  asTree: () => CommitTree;
@@ -18,7 +18,6 @@ export const createGitAssetProvider = (repoUrl, ref, options = {}) => {
18
18
  let store = null;
19
19
  let commit = null;
20
20
  let packSeq = 0;
21
- const prefetchedMetaDirs = new Map();
22
21
  const withHint = (message, cause) => {
23
22
  if (isGitAuthError(cause)) {
24
23
  return `${message}\n${getMessage("error.gitAuthHint", locale)}`;
@@ -50,29 +49,6 @@ export const createGitAssetProvider = (repoUrl, ref, options = {}) => {
50
49
  await store.writePack(pack, `blobs-${packSeq++}`);
51
50
  }
52
51
  };
53
- const topDirOf = (relPath) => {
54
- const slash = relPath.indexOf("/");
55
- return slash === -1 ? "" : relPath.slice(0, slash);
56
- };
57
- const ensureMetasPrefetched = async (oid, topDir) => {
58
- let dirs = prefetchedMetaDirs.get(oid);
59
- if (!dirs) {
60
- dirs = new Set();
61
- prefetchedMetaDirs.set(oid, dirs);
62
- }
63
- if (dirs.has(topDir))
64
- return;
65
- const { store } = requireRepo();
66
- const prefix = topDir === "" ? "" : `${topDir}/`;
67
- const entries = await store.listBlobEntries(oid);
68
- const metaOids = entries
69
- .filter((e) => e.path.startsWith(prefix) &&
70
- (e.path === `${prefix}${META_FILENAME}` ||
71
- e.path.endsWith(`/${META_FILENAME}`)))
72
- .map((e) => e.oid);
73
- await fetchMissingBlobs(metaOids);
74
- dirs.add(topDir);
75
- };
76
52
  const readFileAt = async (oid, relPath) => {
77
53
  const { store } = requireRepo();
78
54
  try {
@@ -81,24 +57,18 @@ export const createGitAssetProvider = (repoUrl, ref, options = {}) => {
81
57
  catch (err) {
82
58
  if (!isGitObjectMissingError(err))
83
59
  throw err;
84
- if (relPath === META_FILENAME || relPath.endsWith(`/${META_FILENAME}`)) {
85
- await ensureMetasPrefetched(oid, topDirOf(relPath));
86
- return store.readBlobAtPath(oid, relPath);
87
- }
88
60
  throw new Error(`File content is not materialized (materialize() must be called first): ${relPath}`);
89
61
  }
90
62
  };
91
- const materializeAt = async (oid, dirs) => {
92
- if (dirs.length === 0)
63
+ const materializeAt = async (oid, files) => {
64
+ if (files.length === 0)
93
65
  return;
94
66
  const { store } = requireRepo();
95
- const prefixes = [
96
- ...new Set(dirs.map((d) => (d === "" || d === "." ? "" : `${d}/`))),
97
- ];
98
67
  const entries = await store.listBlobEntries(oid);
99
- const targets = entries
100
- .filter((e) => prefixes.some((p) => e.path.startsWith(p)))
101
- .map((e) => e.oid);
68
+ const oidByPath = new Map(entries.map((e) => [e.path, e.oid]));
69
+ const targets = files
70
+ .map((f) => oidByPath.get(f))
71
+ .filter((o) => o !== undefined);
102
72
  await fetchMissingBlobs(targets);
103
73
  };
104
74
  const listFilesAt = async (oid) => {
@@ -113,19 +83,15 @@ export const createGitAssetProvider = (repoUrl, ref, options = {}) => {
113
83
  });
114
84
  await store.writePack(pack, label);
115
85
  const entries = await store.listBlobEntries(oid);
116
- const rootMetaOids = entries
117
- .filter((e) => {
118
- const parts = e.path.split("/");
119
- return ((parts.length === 1 && parts[0] === META_FILENAME) ||
120
- (parts.length === 2 && parts[1] === META_FILENAME));
121
- })
86
+ const metaOids = entries
87
+ .filter((e) => e.path === META_FILENAME || e.path.endsWith(`/${META_FILENAME}`))
122
88
  .map((e) => e.oid);
123
- await fetchMissingBlobs(rootMetaOids);
89
+ await fetchMissingBlobs(metaOids);
124
90
  };
125
91
  const commitTreeOf = (oid) => ({
126
92
  listFiles: () => listFilesAt(oid),
127
93
  readFile: (relPath) => readFileAt(oid, relPath),
128
- materialize: (dirs) => materializeAt(oid, dirs),
94
+ materialize: (files) => materializeAt(oid, files),
129
95
  });
130
96
  const provider = {
131
97
  fetch: async () => {
@@ -157,16 +123,15 @@ export const createGitAssetProvider = (repoUrl, ref, options = {}) => {
157
123
  const { commit: oid } = requireRepo();
158
124
  return readFileAt(oid, relPath);
159
125
  },
160
- materialize: (dirs) => {
126
+ materialize: (files) => {
161
127
  const { commit: oid } = requireRepo();
162
- return materializeAt(oid, dirs);
128
+ return materializeAt(oid, files);
163
129
  },
164
130
  cleanup: async () => {
165
131
  if (store) {
166
132
  await store.cleanup();
167
133
  store = null;
168
134
  commit = null;
169
- prefetchedMetaDirs.clear();
170
135
  }
171
136
  },
172
137
  sourceInfo: () => ({
@@ -8,7 +8,7 @@ export type RenderedAsset = {
8
8
  sha1: string;
9
9
  };
10
10
  export type RenderedPlan = Map<string, RenderedAsset>;
11
- export declare const buildRenderedPlan: (tree: AssetTree, settings: AccelSettings, materialize?: (dirs: string[]) => Promise<void>) => Promise<RenderedPlan>;
11
+ export declare const buildRenderedPlan: (tree: AssetTree, settings: AccelSettings, materialize?: (files: string[]) => Promise<void>) => Promise<RenderedPlan>;
12
12
  export type FileState = {
13
13
  relativePath: string;
14
14
  base: RenderedAsset | null;
@@ -4,10 +4,6 @@ import { buildEvalContext } from "../core/eval-context.js";
4
4
  import { walkAssetRepo } from "./walker.js";
5
5
  import { renderAssetContent } from "./renderer.js";
6
6
  import { computeSha1 } from "../utils/hash.js";
7
- const dirnamePosix = (p) => {
8
- const idx = p.lastIndexOf("/");
9
- return idx === -1 ? "" : p.slice(0, idx);
10
- };
11
7
  const isSafeRelPath = (p) => !p.startsWith("/") && !p.split("/").includes("..");
12
8
  export const buildRenderedPlan = async (tree, settings, materialize) => {
13
9
  const context = buildEvalContext(settings);
@@ -21,7 +17,7 @@ export const buildRenderedPlan = async (tree, settings, materialize) => {
21
17
  });
22
18
  if (materialize) {
23
19
  await materialize([
24
- ...new Set(safeEntries.map((e) => dirnamePosix(e.sourceRelPath))),
20
+ ...new Set(safeEntries.map((e) => e.sourceRelPath)),
25
21
  ]);
26
22
  }
27
23
  const plan = new Map();
@@ -5,4 +5,5 @@ export type AssetEntry = {
5
5
  relativePath: string;
6
6
  meta: MetaJson | null;
7
7
  };
8
+ export declare const walkAssetDir: (tree: AssetTree, context: EvalContext) => Promise<AssetEntry[]>;
8
9
  export declare const walkAssetRepo: (tree: AssetTree, targetSemver: string, context: EvalContext) => Promise<AssetEntry[]>;
@@ -89,7 +89,7 @@ const walkDirectory = async (tree, vtree, dir, baseDir, parentMeta, context) =>
89
89
  return [];
90
90
  }
91
91
  }
92
- const relativeOf = (p) => p === baseDir ? "" : p.slice(baseDir.length + 1);
92
+ const relativeOf = (p) => p === baseDir ? "" : baseDir === "" ? p : p.slice(baseDir.length + 1);
93
93
  if (ownMeta?.type === "file") {
94
94
  const parentRelative = relativeOf(dirnamePosix(dir));
95
95
  if (ownMeta.rename && ownMeta.rename.length > 0) {
@@ -151,6 +151,13 @@ const deduplicateByPath = (entries) => {
151
151
  }
152
152
  return [...byPath.values()];
153
153
  };
154
+ export const walkAssetDir = async (tree, context) => {
155
+ const files = await tree.listFiles();
156
+ const vtree = buildVirtualTree(files);
157
+ const meta = await readMetaJson(tree, vtree, "");
158
+ const entries = await walkDirectory(tree, vtree, "", "", meta, context);
159
+ return deduplicateByPath(entries);
160
+ };
154
161
  export const walkAssetRepo = async (tree, targetSemver, context) => {
155
162
  const files = await tree.listFiles();
156
163
  const vtree = buildVirtualTree(files);
@@ -10,7 +10,7 @@ import { withHint } from "../interactive/format.js";
10
10
  import { createGitAssetProvider } from "../asset/git-provider.js";
11
11
  import { buildRenderedPlan, collectFileStates, classifyAll, applyUpdateActions, buildUpdatedRecords, } from "../asset/updater.js";
12
12
  import { mergeFile } from "../utils/merge-file.js";
13
- import { runInstallBuild } from "../asset/installer.js";
13
+ import { getInstallCmds, runInstallBuild } from "../asset/installer.js";
14
14
  import { readSettingsSafe, readHashsum, writeSettings, writeHashsum, } from "../utils/settings-io.js";
15
15
  import { getMessage } from "../i18n/index.js";
16
16
  import { detectLocale } from "../utils/locale-detect.js";
@@ -101,7 +101,7 @@ const resolveInteractiveSettings = async (promptOpts, cliOnlyOpts, releaseIdFall
101
101
  })
102
102
  : runPrompts({ ...promptOpts, skipIntro: true });
103
103
  };
104
- const printResult = (summary, locale) => {
104
+ const printResult = (summary, locale, installGuide) => {
105
105
  const lines = [
106
106
  [summary.updated, "update.result.updated"],
107
107
  [summary.merged, "update.result.merged"],
@@ -147,6 +147,9 @@ const printResult = (summary, locale) => {
147
147
  p.log.warning(`${getMessage("update.conflictSummary", locale, {
148
148
  count: String(summary.conflicts.length),
149
149
  })}\n${list}`);
150
+ if (installGuide) {
151
+ p.log.warning(getMessage("update.installSkippedConflict", locale, installGuide));
152
+ }
150
153
  }
151
154
  if (summary.skippedEdited.length > 0) {
152
155
  const list = summary.skippedEdited.map((c) => ` - ${c}`).join("\n");
@@ -422,10 +425,17 @@ export const updateCommand = defineCommand({
422
425
  };
423
426
  await writeSettings(projectDir, updatedSettings);
424
427
  await writeHashsum(projectDir, hashEntries);
425
- if (summary.changedFileCount > 0 && !args["skip-install"]) {
428
+ const skipInstall = args["skip-install"];
429
+ const hasConflicts = summary.conflicts.length > 0;
430
+ if (summary.changedFileCount > 0 && !hasConflicts && !skipInstall) {
426
431
  runInstallBuild(projectDir, newSettings.packageManager, buildProgressCallbacks(locale));
427
432
  }
428
- printResult(summary, locale);
433
+ let installGuide;
434
+ if (hasConflicts && !skipInstall) {
435
+ const [installCommand, buildCommand] = getInstallCmds(newSettings.packageManager);
436
+ installGuide = { installCommand, buildCommand };
437
+ }
438
+ printResult(summary, locale, installGuide);
429
439
  }
430
440
  catch (err) {
431
441
  p.log.error(err instanceof Error ? err.message : String(err));
@@ -56,7 +56,7 @@ export type ForeachReplacement = {
56
56
  };
57
57
  export type Replacement = TextReplacement | SectionReplacement | RegexReplacement | ForeachReplacement;
58
58
  export type RenameRule = {
59
- condition: Condition;
59
+ condition?: Condition;
60
60
  from: string;
61
61
  to: string;
62
62
  };
@@ -100,6 +100,7 @@ export type AccelSettings = {
100
100
  javascript: boolean;
101
101
  locale: string;
102
102
  packageManager: string;
103
+ gitHooks?: boolean;
103
104
  jugglingProject: string | null;
104
105
  assetSource?: AssetSourceInfo;
105
106
  deployedAssets: Record<string, string>;
@@ -118,7 +119,7 @@ export type AssetSourceInfo = {
118
119
  export type AssetProvider = {
119
120
  fetch: () => Promise<string>;
120
121
  listFiles: () => Promise<string[]>;
121
- materialize: (dirs: string[]) => Promise<void>;
122
+ materialize: (files: string[]) => Promise<void>;
122
123
  readFile: (relPath: string) => Promise<string>;
123
124
  cleanup: () => Promise<void>;
124
125
  sourceInfo: () => AssetSourceInfo;
package/dist/i18n/en.js CHANGED
@@ -36,6 +36,9 @@ export const messages = {
36
36
  "warning.moduleMismatch": "Specified modules differ from juggling.im. Using specified values.",
37
37
  "warning.gitNotFound": "git command not found. Skipping Git initialization.",
38
38
  "warning.fileExists": "File already exists, skipping: {path}",
39
+ "warning.gitHooksUserFile": "Skipped placing the pre-commit hook because {path} is not managed by the CLI. To keep the token-leak check, integrate it into your existing hook manually.",
40
+ "warning.gitHooksPathConflict": "Skipped enabling the pre-commit hook because git core.hooksPath is set to {current}. Integrate the token-leak check (.githooks/pre-commit) into your existing hook setup manually.",
41
+ "warning.gitHooksForeignFiles": "Skipped setting core.hooksPath because .githooks contains files not managed by the CLI ({files}). After confirming they are safe, run git config core.hooksPath .githooks manually.",
39
42
  "attach.skipSummary": "{count} file(s) were skipped because they already exist.",
40
43
  "attach.overwritePrompt": "{path} already exists. Overwrite?",
41
44
  "attach.overwritePrompt.yes": "Yes (overwrite this file)",
@@ -73,6 +76,7 @@ export const messages = {
73
76
  "update.upToDate": "Everything is up to date. Nothing to update.",
74
77
  "update.complete": "Update complete. Updated {updated}, kept {kept}, deleted {deleted} file(s).",
75
78
  "update.conflictSummary": "{count} conflict(s) found. Review the markers (<<<<<<<) and resolve them manually:",
79
+ "update.installSkippedConflict": "install / build were skipped. After resolving the conflicts, run:\n {installCommand} && {buildCommand}",
76
80
  "update.error.keepEditedWithoutAllow": "--keep-edited can only be used together with --allow-missing-base.",
77
81
  "update.error.baseFetchHint": "To continue in fallback mode, pass --allow-missing-base (add --keep-edited to keep edited files and skip them). If the asset repository moved, point to the new location with --asset-server-url / --asset-ref. As a last resort, run accel detach and re-run init.",
78
82
  "update.fallback.editedCount": "Without the base commit, upstream changes to edited files cannot be detected. Edited files that differ from upstream: {count}",
package/dist/i18n/ja.js CHANGED
@@ -36,6 +36,9 @@ export const messages = {
36
36
  "warning.moduleMismatch": "指定されたモジュールとjuggling.imのモジュールが異なります。指定値を優先します。",
37
37
  "warning.gitNotFound": "gitコマンドが見つかりません。Git初期化をスキップします。",
38
38
  "warning.fileExists": "既存ファイルのためスキップ: {path}",
39
+ "warning.gitHooksUserFile": "{path} はCLI管理外のファイルのため、pre-commitフックの配置をスキップしました。トークン漏洩防止のチェックが必要な場合は、既存のフックへ手動で組み込んでください。",
40
+ "warning.gitHooksPathConflict": "gitのcore.hooksPathが {current} に設定されているため、pre-commitフックの有効化をスキップしました。トークン漏洩防止のチェック (.githooks/pre-commit) を既存のフック機構へ手動で組み込んでください。",
41
+ "warning.gitHooksForeignFiles": ".githooks 配下にCLI管理外のファイル ({files}) が存在するため、core.hooksPathの自動設定をスキップしました。内容に問題がないことを確認した上で、git config core.hooksPath .githooks を手動で実行してください。",
39
42
  "attach.skipSummary": "{count}件のファイルは既に存在したためスキップしました。",
40
43
  "attach.overwritePrompt": "{path} は既に存在します。上書きしますか?",
41
44
  "attach.overwritePrompt.yes": "Yes (このファイルを上書き)",
@@ -73,6 +76,7 @@ export const messages = {
73
76
  "update.upToDate": "すべて最新の状態です。更新はありません。",
74
77
  "update.complete": "updateが完了しました。{updated}件を更新、{kept}件を保持、{deleted}件を削除しました。",
75
78
  "update.conflictSummary": "{count}件のコンフリクトがあります。マーカー(<<<<<<<)を確認して手動で解決してください:",
79
+ "update.installSkippedConflict": "install / build はスキップされました。コンフリクト解決後に以下を実行してください:\n {installCommand} && {buildCommand}",
76
80
  "update.error.keepEditedWithoutAllow": "--keep-edited は --allow-missing-base と併用する場合のみ指定できます。",
77
81
  "update.error.baseFetchHint": "フォールバックモードで続行するには --allow-missing-base を指定してください(--keep-edited 併用で編集済みファイルを保持してスキップ)。資材リポジトリが移転した場合は --asset-server-url / --asset-ref で取得元を変更できます。最終手段として accel detach 後に再度 init する方法もあります。",
78
82
  "update.fallback.editedCount": "基準コミット(base)なしで続行する場合、編集済みファイルの上流変更は判定できません。上流と差分のある編集済みファイル: {count}件",
@@ -36,6 +36,9 @@ export const messages = {
36
36
  "warning.moduleMismatch": "指定的模块与juggling.im不同。将使用指定值。",
37
37
  "warning.gitNotFound": "未找到git命令。跳过Git初始化。",
38
38
  "warning.fileExists": "文件已存在,跳过: {path}",
39
+ "warning.gitHooksUserFile": "由于 {path} 不是由 CLI 管理的文件,已跳过 pre-commit 钩子的部署。如需保留防止令牌泄露的检查,请手动将其集成到现有钩子中。",
40
+ "warning.gitHooksPathConflict": "由于 git 的 core.hooksPath 已设置为 {current},已跳过 pre-commit 钩子的启用。请手动将防止令牌泄露的检查(.githooks/pre-commit)集成到现有的钩子机制中。",
41
+ "warning.gitHooksForeignFiles": "由于 .githooks 下存在不由 CLI 管理的文件({files}),已跳过 core.hooksPath 的自动设置。请确认其内容没有问题后,手动执行 git config core.hooksPath .githooks。",
39
42
  "attach.skipSummary": "{count}个文件已存在,已跳过。",
40
43
  "attach.overwritePrompt": "{path} 已存在。要覆盖吗?",
41
44
  "attach.overwritePrompt.yes": "Yes (覆盖此文件)",
@@ -73,6 +76,7 @@ export const messages = {
73
76
  "update.upToDate": "已是最新状态,无需更新。",
74
77
  "update.complete": "update完成。更新{updated}个、保留{kept}个、删除{deleted}个文件。",
75
78
  "update.conflictSummary": "发现{count}个冲突。请检查标记(<<<<<<<)并手动解决:",
79
+ "update.installSkippedConflict": "已跳过 install / build。解决冲突后请执行以下命令:\n {installCommand} && {buildCommand}",
76
80
  "update.error.keepEditedWithoutAllow": "--keep-edited 仅可与 --allow-missing-base 一起使用。",
77
81
  "update.error.baseFetchHint": "要以回退模式继续,请指定 --allow-missing-base(同时指定 --keep-edited 可保留并跳过已编辑的文件)。如果资源仓库已迁移,可通过 --asset-server-url / --asset-ref 更改获取源。作为最后手段,可执行 accel detach 后重新 init。",
78
82
  "update.fallback.editedCount": "在没有基准提交(base)的情况下继续时,无法判定已编辑文件的上游变更。与上游存在差异的已编辑文件: {count}个",
@@ -0,0 +1 @@
1
+ export declare const syncGitHooks: (projectDir: string) => Promise<void>;
@@ -0,0 +1,91 @@
1
+ import fs from "node:fs";
2
+ import { access, chmod, mkdir, readdir, readFile, writeFile, } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import git from "isomorphic-git";
6
+ import * as p from "@clack/prompts";
7
+ import { createFsAssetTree } from "../asset/asset-tree.js";
8
+ import { walkAssetDir } from "../asset/walker.js";
9
+ import { emptyEvalContext } from "../core/eval-context.js";
10
+ import { getMessage } from "../i18n/index.js";
11
+ import { detectLocale } from "./locale-detect.js";
12
+ import { readSettingsSafe } from "./settings-io.js";
13
+ const MANAGED_MARKER = "@accel-cli-managed";
14
+ const HOOKS_PATH = ".githooks";
15
+ const HOOK_FILE_REL = ".githooks/pre-commit";
16
+ const ASSETS_GITHOOKS_ROOT = fileURLToPath(new URL("../../assets/githooks", import.meta.url));
17
+ const readFileSafe = async (filePath) => {
18
+ try {
19
+ return await readFile(filePath, "utf-8");
20
+ }
21
+ catch {
22
+ return null;
23
+ }
24
+ };
25
+ const listForeignFiles = async (hooksDir) => {
26
+ const foreign = [];
27
+ for (const entry of await readdir(hooksDir, { withFileTypes: true })) {
28
+ if (!entry.isFile()) {
29
+ foreign.push(entry.name);
30
+ continue;
31
+ }
32
+ const content = await readFileSafe(join(hooksDir, entry.name));
33
+ if (content === null || !content.includes(MANAGED_MARKER)) {
34
+ foreign.push(entry.name);
35
+ }
36
+ }
37
+ return foreign;
38
+ };
39
+ export const syncGitHooks = async (projectDir) => {
40
+ const settings = await readSettingsSafe(projectDir);
41
+ if (settings?.gitHooks === false)
42
+ return;
43
+ try {
44
+ await access(join(projectDir, ".git"));
45
+ }
46
+ catch {
47
+ return;
48
+ }
49
+ const locale = settings?.locale ?? detectLocale();
50
+ const tree = createFsAssetTree(ASSETS_GITHOOKS_ROOT);
51
+ const entries = await walkAssetDir(tree, emptyEvalContext({ locale }));
52
+ for (const entry of entries) {
53
+ const destPath = join(projectDir, entry.relativePath);
54
+ const existing = await readFileSafe(destPath);
55
+ if (existing !== null && !existing.includes(MANAGED_MARKER)) {
56
+ p.log.warning(getMessage("warning.gitHooksUserFile", locale, {
57
+ path: entry.relativePath,
58
+ }));
59
+ continue;
60
+ }
61
+ const content = (await tree.readFile(entry.sourceRelPath)).replace(/\r\n/g, "\n");
62
+ await mkdir(dirname(destPath), { recursive: true });
63
+ await writeFile(destPath, content, "utf-8");
64
+ if (entry.relativePath === HOOK_FILE_REL) {
65
+ await chmod(destPath, 0o755);
66
+ }
67
+ }
68
+ const current = (await git.getConfig({
69
+ fs,
70
+ dir: projectDir,
71
+ path: "core.hooksPath",
72
+ }));
73
+ if (current === undefined) {
74
+ const foreign = await listForeignFiles(join(projectDir, HOOKS_PATH));
75
+ if (foreign.length > 0) {
76
+ p.log.warning(getMessage("warning.gitHooksForeignFiles", locale, {
77
+ files: foreign.join(", "),
78
+ }));
79
+ return;
80
+ }
81
+ await git.setConfig({
82
+ fs,
83
+ dir: projectDir,
84
+ path: "core.hooksPath",
85
+ value: HOOKS_PATH,
86
+ });
87
+ }
88
+ else if (current !== HOOKS_PATH) {
89
+ p.log.warning(getMessage("warning.gitHooksPathConflict", locale, { current }));
90
+ }
91
+ };
@@ -2,6 +2,7 @@ import { readFile, writeFile } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
4
4
  import { persistCredentials } from "./credentials.js";
5
+ import { syncGitHooks } from "./githooks-sync.js";
5
6
  import { readSettingsSafe } from "./settings-io.js";
6
7
  const AUTHORIZATION_HEADER = "Authorization";
7
8
  export const matchesEndpoint = (url, endpoint) => {
@@ -94,4 +95,9 @@ export const persistCredentialsAndSyncMcp = async (projectDir, creds) => {
94
95
  }
95
96
  catch {
96
97
  }
98
+ try {
99
+ await syncGitHooks(projectDir);
100
+ }
101
+ catch {
102
+ }
97
103
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intra-mart/accel",
3
- "version": "0.4.0-dev.202607140628",
3
+ "version": "0.4.0-dev.202607170346",
4
4
  "type": "module",
5
5
  "description": "CLI tool for intra-mart Accel Platform development",
6
6
  "author": "NTT DATA INTRAMART",
@@ -19,7 +19,8 @@
19
19
  "accel": "./dist/index.js"
20
20
  },
21
21
  "files": [
22
- "dist"
22
+ "dist",
23
+ "assets"
23
24
  ],
24
25
  "engines": {
25
26
  "node": ">=24.0.0"