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

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