@tyhld/conductor 0.12.170 → 0.12.172

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tyhld/conductor",
3
- "version": "0.12.170",
3
+ "version": "0.12.172",
4
4
  "description": "采配くん管制の見守りアプリ(conductor-agent)。各PCで常駐し、中央(devlog-tracker)へ定期的に生存報告(heartbeat)を送る常駐CLI。",
5
5
  "type": "module",
6
6
  "bin": {
@@ -100,7 +100,6 @@
100
100
  "Edit(**/.ssh/**)",
101
101
  "Edit(**/*.pem)",
102
102
  "Edit(**/*.key)",
103
- "Edit(**/.npmrc)",
104
103
  "Read(**/.env)",
105
104
  "Read(**/.env.local)",
106
105
  "Read(**/.env.development)",
@@ -862,6 +862,28 @@ TYHLD-platform の2便が、**読むだけの検索**で同じ `danger` に止
862
862
  - **`-f` / `--file` と `-e` が混ざった形では、1つも外しません**(安全側に倒したまま)。
863
863
  - **番人が古い機体では効きません。** 各PCで人が1回配布を流すまで、その機では今までどおりです。
864
864
 
865
+ ## 1-13. ★値の入っていない `.npmrc` は、作る・直す・記録に入れるのを通す(便 5751e7ae・えふさん決定 2026-11-03)
866
+
867
+ 共通部品(`@tyhld/*`)を取ってくる `.npmrc` は、中身が取り寄せ先の行と鍵の置き場の名前(`${NPM_TOKEN}`)だけで、
868
+ 鍵の値はありません。それでも名前だけで秘密と判定していたので、職人の Write(便 9ca0acd2・禁止の一覧の `Edit(**/.npmrc)`)も
869
+ `git add`(便 6a4e2122・`danger: secret file (.npmrc) sent by git add`)も止まり、そのたびにえふさんの手番になっていました。
870
+
871
+ | 形 | 前 | 後 |
872
+ |---|---|---|
873
+ | Write/Edit/MultiEdit で、許す形の行だけの `.npmrc` を作る・直す(元も許す形だけか、まだ無い) | 止まる | **通る** |
874
+ | 名指しの `git add`・`git stage`・`git commit <名指し>` で、許す形の行だけの `.npmrc` を記録に入れる | `danger` | **通る** |
875
+ | `_authToken` の右が実物/`_auth`・`_password`・`always-auth`・`username`・未知の行/URL に名前や合言葉 | `danger` | `danger`(変えない) |
876
+ | 元の `.npmrc` に実物の値が在る(値なしで上書き・直し=本物の鍵を消す形) | `danger` | `danger`(変えない) |
877
+ | `~/.npmrc`・ホームの隠しフォルダの下・秘密の置き場の下・近道・作業場所が変数の `git -C "$DIR"` | `danger` | `danger`(変えない) |
878
+ | 読む(Read・`cat`)・Bash で書く(`cp`・`tee`・`>`)・`git hash-object -w` | `danger` | `danger`(変えない) |
879
+
880
+ - 許す形の行=空行・注釈(`#`・`;`)・`registry=<URL>`・`@<scope>:registry=<URL>`・`//<ホスト>/:_authToken=${<名前>}` だけ。
881
+ 番人は中身を読みますが、判定の「はい/いいえ」にしか使わず、中身は1文字も外に出しません(`npmrc_text_is_ref_only`)。
882
+ - **禁止の一覧の `Edit(**/.npmrc)` は退役しました**(`update-guard.sh` の `RETIRED_DENY`・各現場からも外す)。この行は中身を見られないので、
883
+ 値なしの Write まで止めていました。値の入った書き込みは番人の中身の判定が止めます(`test_npmrc_ref_only.py` で確かめた)。
884
+ ★2枚目の守りは残します:現場の `.npmrc` に実物の値が入っていれば、配り直しが `Read(/.npmrc)` と `Edit(/.npmrc)` を狙い撃ちで戻します。
885
+ - 試験:`scripts/hooks/test_npmrc_ref_only.py`・`test/site-npmrc-edit-retire.test.ts`・`test/write-deny-retired.test.ts`。
886
+
865
887
  ## 2. ファイルの役割
866
888
 
867
889
  | ファイル | 役割 |
@@ -451,6 +451,137 @@ def secret_reason(path: str, cwd=None):
451
451
  return None
452
452
 
453
453
 
454
+ # ─────────────────────────────────────────────────────────────────────────────
455
+ # 値の入っていない .npmrc は、作る・直す・記録に入れるのを通す(えふさん決定 2026-11-03・便 5751e7ae)
456
+ #
457
+ # 【何が起きていたか】共通部品(@tyhld/*)を取ってくる .npmrc は、中身が「取り寄せ先の行」と
458
+ # 「鍵の置き場の名前(${NPM_TOKEN})」だけで、鍵の値は無い。それでも名前だけで秘密と判定していた
459
+ # ので、職人の Write(便 9ca0acd2)も git add(便 6a4e2122・danger: secret file (.npmrc) sent by git add)
460
+ # も止まり、そのたびにえふさんの手番になっていた。
461
+ # 【どう直したか】番人が中身を読んで(★外には1文字も出さない)、許す形の行【だけ】のときに限って通す。
462
+ # 許す形=空行・注釈・`registry=<URL>`・`@<scope>:registry=<URL>`・`//<ホスト>/:_authToken=${<名前>}`。
463
+ # ★それ以外の行(鍵の実物・_auth・_password・always-auth・username・email・未知の行)が1行でも在れば、
464
+ # 今までどおり秘密として止める。URL に名前や合言葉を書く形(https://u:p@host)も止める。
465
+ # 【通すのは次の4つがそろうときだけ】
466
+ # ① 字面も実体も名前が .npmrc で、ほかの秘密の理由(秘密の置き場の下 等)が無い
467
+ # ② 近道(symlink)ではない・ホームの直下(~/.npmrc=人の本物の鍵の置き場)ではない
468
+ # ③ 中身(書いた後・記録に入る物)が許す形だけ
469
+ # ④ 上書き・直しなら、元の中身も許す形だけ(実物の鍵が入った .npmrc は消させない・書き換えさせない)
470
+ # ★読む(Read・cat)は今までどおり止める(職人が中身を読む必要は無い。判定は番人がする)。
471
+ # ★Bash で書く(cp・tee・>)は今までどおり止める(ここで通すのは Write/Edit と git add・git commit だけ)。
472
+ # ─────────────────────────────────────────────────────────────────────────────
473
+
474
+ #: 番人が読んで確かめる .npmrc の大きさの上限(これより大きければ確かめない=止める)。
475
+ _NPMRC_MAX_BYTES = 8 * 1024
476
+
477
+ #: 取り寄せ先の URL(名前・合言葉・問い合わせ・${} を含む形は当たらない)。
478
+ _NPMRC_URL = r'https?://[A-Za-z0-9.-]+(:[0-9]{1,5})?(/[A-Za-z0-9._~%/-]*)?'
479
+ _NPMRC_REGISTRY_RE = re.compile(
480
+ r'^(@[a-z0-9][a-z0-9._-]*:)?registry\s*=\s*' + _NPMRC_URL + r'$')
481
+ #: 鍵の行は「鍵の置き場の名前の参照」だけ。★右が ${名前} ちょうどでなければ当たらない。
482
+ _NPMRC_TOKEN_REF_RE = re.compile(
483
+ r'^//[A-Za-z0-9.-]+(:[0-9]{1,5})?(/[A-Za-z0-9._~%-]+)*/:_authToken\s*=\s*'
484
+ r'\$\{[A-Za-z_][A-Za-z0-9_]*\}$')
485
+ _NPMRC_SECRET_REASON = 'secret file (.npmrc)'
486
+
487
+
488
+ def npmrc_text_is_ref_only(text) -> bool:
489
+ """.npmrc の中身が許す形の行だけか。★中身は返さない・どこにも出さない(はい/いいえだけ)。"""
490
+ if not isinstance(text, str) or len(text.encode('utf-8', 'replace')) > _NPMRC_MAX_BYTES:
491
+ return False
492
+ if '\x00' in text:
493
+ return False
494
+ for raw in text.splitlines():
495
+ line = raw.strip()
496
+ if not line or line.startswith('#') or line.startswith(';'):
497
+ continue
498
+ if _NPMRC_REGISTRY_RE.match(line) or _NPMRC_TOKEN_REF_RE.match(line):
499
+ continue
500
+ return False
501
+ return True
502
+
503
+
504
+ def _npmrc_read_text(path):
505
+ """番人が .npmrc の中身を読む(★中身は判定にだけ使う)。無ければ ''、読めなければ None。"""
506
+ try:
507
+ if not os.path.lexists(path):
508
+ return ''
509
+ if os.path.islink(path) or not os.path.isfile(path):
510
+ return None
511
+ if os.path.getsize(path) > _NPMRC_MAX_BYTES:
512
+ return None
513
+ with open(path, 'rb') as f:
514
+ data = f.read(_NPMRC_MAX_BYTES + 1)
515
+ return data.decode('utf-8')
516
+ except Exception: # noqa: BLE001
517
+ return None
518
+
519
+
520
+ def _npmrc_place_ok(path: str) -> bool:
521
+ """①② 名前が .npmrc で、ほかの秘密の理由が無く、近道でもホームの直下でもない。"""
522
+ if not path or not os.path.isabs(path):
523
+ return False
524
+ if os.path.basename(path) != '.npmrc' or secret_reason(path) != _NPMRC_SECRET_REASON:
525
+ return False
526
+ try:
527
+ if os.path.islink(path):
528
+ return False
529
+ real = os.path.realpath(path)
530
+ except Exception: # noqa: BLE001
531
+ return False
532
+ if os.path.basename(real) != '.npmrc' or secret_reason(real) != _NPMRC_SECRET_REASON:
533
+ return False
534
+ # ★名前の判定が先に当たるので、置き場(.ssh などの下)は親のフォルダで測り直す。
535
+ if secret_reason(os.path.dirname(path)) or secret_reason(os.path.dirname(real)):
536
+ return False
537
+ home = _home_dir()
538
+ if home and (os.path.dirname(real) == home or _under_home_dot_dir(real)):
539
+ return False
540
+ return True
541
+
542
+
543
+ def npmrc_file_is_ref_only(path: str) -> bool:
544
+ """在る .npmrc(記録に入れる物)が、許す場所の、許す形の中身だけか。"""
545
+ if not _npmrc_place_ok(path):
546
+ return False
547
+ text = _npmrc_read_text(path)
548
+ return bool(text) and npmrc_text_is_ref_only(text)
549
+
550
+
551
+ def _npmrc_apply_edits(text, edits):
552
+ """Edit/MultiEdit の置き換えを順に当てた後の中身。当てられなければ None(=止める)。"""
553
+ for e in edits:
554
+ if not isinstance(e, dict):
555
+ return None
556
+ old, new = e.get('old_string'), e.get('new_string')
557
+ if not isinstance(old, str) or not isinstance(new, str) or not old:
558
+ return None
559
+ n = text.count(old)
560
+ if n == 0 or (n > 1 and not e.get('replace_all')):
561
+ return None
562
+ text = text.replace(old, new) if e.get('replace_all') else text.replace(old, new, 1)
563
+ return text
564
+
565
+
566
+ def npmrc_write_is_ref_only(path: str, tool, tool_input) -> bool:
567
+ """Write/Edit/MultiEdit の後の中身と、元の中身の両方が許す形だけか(③④)。"""
568
+ if not _npmrc_place_ok(path) or not isinstance(tool_input, dict):
569
+ return False
570
+ before = _npmrc_read_text(path)
571
+ if before is None or (before and not npmrc_text_is_ref_only(before)):
572
+ return False
573
+ if tool == 'Write':
574
+ after = tool_input.get('content')
575
+ elif tool == 'Edit':
576
+ after = _npmrc_apply_edits(before, [tool_input]) if before else None
577
+ elif tool == 'MultiEdit':
578
+ edits = tool_input.get('edits')
579
+ after = _npmrc_apply_edits(before, edits) if before and isinstance(edits, list) else None
580
+ else:
581
+ return False
582
+ return isinstance(after, str) and bool(after.strip()) and npmrc_text_is_ref_only(after)
583
+
584
+
454
585
  # システム領域だが書いても無害な特殊ファイル(捨て先・標準出力など)。
455
586
  # ★ここを除外しないと `... > /dev/null` という日常操作が止まる(実際に止まった)。
456
587
  _HARMLESS_DEVICES = frozenset({
@@ -4327,6 +4458,9 @@ def _vcs_file_danger(tokens, cwd=None):
4327
4458
  verb = _exe_base(tokens[vi])
4328
4459
  args = tokens[vi + 1:]
4329
4460
  where = cwd
4461
+ # 記録に入れる名指しのうち、値の入っていない .npmrc なら通してよい物(便 5751e7ae)。
4462
+ # ★作業場所を確かめられない形(git -C "$DIR")は、番人が読む物と記録に入る物が違い得るので数えない。
4463
+ ref_ok_paths = set()
4330
4464
  if verb == 'git':
4331
4465
  sub, rest = _git_subcommand(args)
4332
4466
  got = _git_cwd(args, cwd)
@@ -4341,9 +4475,14 @@ def _vcs_file_danger(tokens, cwd=None):
4341
4475
  vals = _flag_values(rest, *spec)
4342
4476
  if sub == 'commit':
4343
4477
  # git commit の名指し(便 16b2f958)。pathspec の頭(`:(top)`)は外し、除く指定は見ない。
4344
- vals = vals + [b for b in map(_pathspec_body, _git_commit_paths(rest)) if b]
4478
+ named = [b for b in map(_pathspec_body, _git_commit_paths(rest)) if b]
4479
+ vals = vals + named
4480
+ if got is not _UNKNOWN_DIR:
4481
+ ref_ok_paths = set(named)
4345
4482
  elif staged is not None:
4346
4483
  vals = staged # 記録に入れる名指し(便 9faa1627)
4484
+ if sub in ('add', 'stage') and got is not _UNKNOWN_DIR:
4485
+ ref_ok_paths = set(staged)
4347
4486
  else:
4348
4487
  return None
4349
4488
  label = f'git {sub}'
@@ -4365,6 +4504,9 @@ def _vcs_file_danger(tokens, cwd=None):
4365
4504
  if not v or v == '-':
4366
4505
  continue
4367
4506
  sr = secret_reason(v, where)
4507
+ if sr == _NPMRC_SECRET_REASON and v in ref_ok_paths and npmrc_file_is_ref_only(
4508
+ norm_path(v, where if (where and os.path.isabs(where)) else None)):
4509
+ continue
4368
4510
  if sr:
4369
4511
  return f'{sr} sent by {label}'
4370
4512
  return None
@@ -7145,7 +7287,7 @@ def norm_path(file_path: str, cwd=None) -> str:
7145
7287
  return os.path.normpath(p)
7146
7288
 
7147
7289
 
7148
- def decide_write(file_path: str, cwd=None):
7290
+ def decide_write(file_path: str, cwd=None, tool=None, tool_input=None):
7149
7291
  if not file_path or not isinstance(file_path, str) or not file_path.strip():
7150
7292
  return _r(ALLOW, 'empty file_path')
7151
7293
  try:
@@ -7154,6 +7296,11 @@ def decide_write(file_path: str, cwd=None):
7154
7296
  return _r(DENY, 'danger: unnormalizable path')
7155
7297
 
7156
7298
  sr = secret_reason(path)
7299
+ # ★値の入っていない .npmrc だけは、書いた後と元の中身を番人が確かめて通す(便 5751e7ae)。
7300
+ # 通した後も、下のシステム領域・番人の設定・.tyhld の判定はそのまま掛かる。
7301
+ npmrc_ok = sr == _NPMRC_SECRET_REASON and npmrc_write_is_ref_only(path, tool, tool_input)
7302
+ if npmrc_ok:
7303
+ sr = None
7157
7304
  if sr:
7158
7305
  return _r(DENY, f'danger: write to {sr}')
7159
7306
  syr = system_write_reason(path)
@@ -7176,7 +7323,7 @@ def decide_write(file_path: str, cwd=None):
7176
7323
  return _r(DENY, 'danger: write to guard directory (.tyhld)')
7177
7324
  # ★.env 類(雛形を含む)への書き込みは、Bash と同じく止める(便 3d11f913・番人でも結果を一致)。
7178
7325
  # 読み込みは変えない(secret_reason は雛形を通す)。
7179
- if _is_write_protected_name(_env_base(path)):
7326
+ if _is_write_protected_name(_env_base(path)) and not npmrc_ok:
7180
7327
  return _r(DENY, f'danger: secret file write ({_env_base(path)})')
7181
7328
  return _r(ALLOW, 'no gate, no danger')
7182
7329
 
@@ -7369,7 +7516,7 @@ def decide_event(data):
7369
7516
  fp = tin.get('file_path', '')
7370
7517
  if not fp:
7371
7518
  return _r(ALLOW, 'no file_path')
7372
- return decide_write(fp, data.get('cwd'))
7519
+ return decide_write(fp, data.get('cwd'), tool, tin)
7373
7520
  if tool in READ_TOOLS:
7374
7521
  fp = tin.get('file_path') or tin.get('notebook_path') or ''
7375
7522
  if not fp:
@@ -0,0 +1,218 @@
1
+ #!/usr/bin/env python3
2
+ """便 5751e7ae: 値の入っていない .npmrc は、職人が作る・直す・記録に入れるのを通す試験。
3
+
4
+ 実行: python3 scripts/hooks/test_npmrc_ref_only.py
5
+ 1件でも期待と違えば exit 1。
6
+
7
+ 【背景】共通部品(@tyhld/*)を取ってくる .npmrc は「取り寄せ先の行」と「鍵の置き場の名前(${NPM_TOKEN})」
8
+ だけで、鍵の値は無い。それでも名前だけで秘密と判定していたので、職人の Write(便 9ca0acd2)も
9
+ git add(便 6a4e2122・danger: secret file (.npmrc) sent by git add)も止まり、えふさんの手番になっていた。
10
+
11
+ 【固定すること】
12
+ ① 値なしの .npmrc は Write・Edit・MultiEdit・git add・git commit が通る。
13
+ ② _authToken の右が実物の文字列/未知の行/_auth・_password・always-auth・username の行/
14
+ URL に名前・合言葉を書いた形 が1つでも混じれば、今までどおり止まる。
15
+ ③ 元の中身に実物が在る .npmrc は、値なしの中身でも上書き・直しで消させない。
16
+ ④ 近道(symlink)・ホームの直下(~/.npmrc)・秘密の置き場の下・作業場所を確かめられない git -C "$DIR" は止まる。
17
+ ⑤ 読む(Read・cat)・Bash で書く(cp・tee・>)は今までどおり止まる。
18
+ ⑥ .env など他の秘密のファイルの Write・git add は今までどおり止まる。
19
+ ⑦ 禁止の一覧(sales-template/settings.json)から Edit(**/.npmrc) を外し、退役の一覧に入れた。
20
+
21
+ ★鍵はすべて作り物。本物の .npmrc・~/.npmrc は1バイトも読まない・書かない(場所は /tmp の下の使い捨て)。
22
+ """
23
+ import json
24
+ import os
25
+ import shutil
26
+ import subprocess
27
+ import sys
28
+ import tempfile
29
+
30
+ HERE = os.path.dirname(os.path.abspath(__file__))
31
+ sys.path.insert(0, HERE)
32
+
33
+ import policy # noqa: E402
34
+
35
+ failures = []
36
+
37
+
38
+ def check(label, got, want):
39
+ ok = got == want
40
+ if not ok:
41
+ failures.append(f'{label}: got={got!r} want={want!r}')
42
+ print(f'{"OK " if ok else "NG "} {label:72} {str(got)[:24]}')
43
+
44
+
45
+ NAME = '.npm' + 'rc'
46
+ ENV = '.e' + 'nv'
47
+ FAKE = 'FAKE_npm_' + 'x' * 20 # 作り物の鍵(実物の形に似せない)
48
+ REG = '@tyhld:registry=https://npm.pkg.github.com\n'
49
+ REF = '//npm.pkg.github.com/:_authToken=${NPM_TOKEN}\n'
50
+ SAFE = REG + REF
51
+
52
+ BASE = tempfile.mkdtemp(prefix='npmrc-ref-only-', dir='/tmp')
53
+ REPO = os.path.join(BASE, 'site')
54
+ os.makedirs(REPO)
55
+ subprocess.run(['git', 'init', '-q', REPO], check=True)
56
+ P = os.path.join(REPO, NAME)
57
+
58
+
59
+ def put(text, path=P):
60
+ with open(path, 'w', encoding='utf-8') as f:
61
+ f.write(text)
62
+
63
+
64
+ def gone(path=P):
65
+ if os.path.lexists(path):
66
+ os.remove(path)
67
+
68
+
69
+ def ev(tool, tin, cwd=REPO):
70
+ return policy.decide_event({'tool_name': tool, 'cwd': cwd, 'tool_input': tin})['decision']
71
+
72
+
73
+ def bash(cmd, cwd=REPO):
74
+ return policy.decide_bash(cmd, cwd)['decision']
75
+
76
+
77
+ A, D = policy.ALLOW, policy.DENY
78
+
79
+ try:
80
+ print('── 中身の判定(はい/いいえだけ・中身は返さない) ' + '─' * 20)
81
+ for label, text, want in [
82
+ ('取り寄せ先+鍵の置き場の名前', SAFE, True),
83
+ ('取り寄せ先だけ', REG, True),
84
+ ('既定の取り寄せ先', 'registry=https://registry.npmjs.org/\n', True),
85
+ ('空行・注釈(# と ;)', '# 注釈\n\n; 注釈\n' + SAFE, True),
86
+ ('= の前後に空白', '@tyhld:registry = https://npm.pkg.github.com\n'
87
+ '//npm.pkg.github.com/:_authToken = ${NPM_TOKEN}\n', True),
88
+ ('CRLF の行末', SAFE.replace('\n', '\r\n'), True),
89
+ ('鍵の実物', REG + f'//npm.pkg.github.com/:_authToken={FAKE}\n', False),
90
+ ('参照の前後に実物', REG + '//npm.pkg.github.com/:_authToken=x${NPM_TOKEN}\n', False),
91
+ ('参照が2つ', REG + '//npm.pkg.github.com/:_authToken=${A}${B}\n', False),
92
+ ('$NAME の形(括弧なし)', REG + '//npm.pkg.github.com/:_authToken=$NPM_TOKEN\n', False),
93
+ ('_auth の行', REG + '//npm.pkg.github.com/:_auth=${NPM_AUTH}\n', False),
94
+ ('_password の行', REG + '//npm.pkg.github.com/:_password=${P}\n', False),
95
+ ('always-auth の行', SAFE + 'always-auth=true\n', False),
96
+ ('username の行', SAFE + '//npm.pkg.github.com/:username=u\n', False),
97
+ ('未知の行', SAFE + 'foo=bar\n', False),
98
+ ('URL に名前と合言葉', '@tyhld:registry=https://u:p@npm.pkg.github.com\n', False),
99
+ ('URL に問い合わせ', '@tyhld:registry=https://npm.pkg.github.com/?token=x\n', False),
100
+ ('取り寄せ先に参照', '@tyhld:registry=${REG_URL}\n', False),
101
+ ('鍵の行の先がホームでない', REG + 'npm.pkg.github.com/:_authToken=${NPM_TOKEN}\n', False),
102
+ ('大きすぎる', '#' + 'x' * 9000 + '\n', False),
103
+ ]:
104
+ check(f'中身: {label}', policy.npmrc_text_is_ref_only(text), want)
105
+
106
+ print('── ① 値なしの .npmrc は Write・Edit・MultiEdit が通る ' + '─' * 16)
107
+ gone()
108
+ check('Write: 新しく作る(値なし)', ev('Write', {'file_path': P, 'content': SAFE}), A)
109
+ check('Write: 相対の名前で作る(値なし)', ev('Write', {'file_path': NAME, 'content': SAFE}), A)
110
+ put(REG)
111
+ check('Write: 値なしの上に値なしを書く', ev('Write', {'file_path': P, 'content': SAFE}), A)
112
+ check('Edit: 値なしへ鍵の置き場の名前の行を足す',
113
+ ev('Edit', {'file_path': P, 'old_string': REG, 'new_string': SAFE}), A)
114
+ check('MultiEdit: 値なしのまま2か所を直す',
115
+ ev('MultiEdit', {'file_path': P, 'edits': [
116
+ {'old_string': '@tyhld', 'new_string': '@tyhld'},
117
+ {'old_string': 'npm.pkg', 'new_string': 'npm.pkg'}]}), A)
118
+
119
+ print('── ② 書いた後に値・未知の行が入る形は止まる ' + '─' * 24)
120
+ gone()
121
+ check('Write: 鍵の実物', ev('Write', {'file_path': P, 'content':
122
+ REG + f'//npm.pkg.github.com/:_authToken={FAKE}\n'}), D)
123
+ check('Write: 未知の行が混じる', ev('Write', {'file_path': P, 'content': SAFE + 'foo=bar\n'}), D)
124
+ check('Write: always-auth が混じる', ev('Write', {'file_path': P, 'content': SAFE + 'always-auth=true\n'}), D)
125
+ check('Write: 中身が空', ev('Write', {'file_path': P, 'content': ''}), D)
126
+ check('Write: 中身が無い', ev('Write', {'file_path': P}), D)
127
+ put(SAFE)
128
+ check('Edit: 参照を実物に替える',
129
+ ev('Edit', {'file_path': P, 'old_string': '${NPM_TOKEN}', 'new_string': FAKE}), D)
130
+ check('Edit: 当てる文字が無い', ev('Edit', {'file_path': P, 'old_string': 'zzz', 'new_string': 'y'}), D)
131
+ check('MultiEdit: 2つ目で実物が入る', ev('MultiEdit', {'file_path': P, 'edits': [
132
+ {'old_string': '@tyhld', 'new_string': '@tyhld'},
133
+ {'old_string': '${NPM_TOKEN}', 'new_string': FAKE}]}), D)
134
+ check('NotebookEdit は今までどおり止まる', ev('NotebookEdit', {'file_path': P, 'new_source': SAFE}), D)
135
+ gone()
136
+ check('Edit: まだ無いファイル', ev('Edit', {'file_path': P, 'old_string': 'a', 'new_string': 'b'}), D)
137
+
138
+ print('── ③ 元に実物が在る .npmrc は消させない・書き換えさせない ' + '─' * 10)
139
+ put(REG + f'//npm.pkg.github.com/:_authToken={FAKE}\n')
140
+ check('Write: 実物の上に値なしを書く', ev('Write', {'file_path': P, 'content': SAFE}), D)
141
+ check('Edit: 実物を参照へ替える',
142
+ ev('Edit', {'file_path': P, 'old_string': FAKE, 'new_string': '${NPM_TOKEN}'}), D)
143
+
144
+ print('── ① 値なしの .npmrc は git add・git commit が通る ' + '─' * 18)
145
+ put(SAFE)
146
+ check('git add .npmrc', bash(f'git add {NAME}'), A)
147
+ check('git add ほかと並べて名指し', bash(f'git add package.json src/App.tsx {NAME}'), A)
148
+ check('git add -- .npmrc', bash(f'git add -- {NAME}'), A)
149
+ check('git -C <実際の場所> add .npmrc', bash(f'git -C {REPO} add {NAME}', BASE), A)
150
+ check('git add <絶対パス>', bash(f'git add {P}'), A)
151
+ check('git stage .npmrc', bash(f'git stage {NAME}'), A)
152
+ check('git commit -m x .npmrc', bash(f'git commit -m x {NAME}'), A)
153
+ check('git commit -m x -- .npmrc', bash(f'git commit -m x -- {NAME}'), A)
154
+
155
+ print('── ② 中身が許す形でない .npmrc の git add・git commit は止まる ' + '─' * 6)
156
+ for label, text in [('鍵の実物', REG + f'//npm.pkg.github.com/:_authToken={FAKE}\n'),
157
+ ('未知の行', SAFE + 'foo=bar\n'),
158
+ ('_auth の行', SAFE + '//npm.pkg.github.com/:_auth=${A}\n')]:
159
+ put(text)
160
+ check(f'git add({label})', bash(f'git add {NAME}'), D)
161
+ check(f'git commit -m x({label})', bash(f'git commit -m x {NAME}'), D)
162
+ gone()
163
+ check('git add(まだ無い .npmrc)', bash(f'git add {NAME}'), D)
164
+
165
+ print('── ④ 場所で止まる形 ' + '─' * 46)
166
+ put(SAFE)
167
+ check('git -C "$DIR" add .npmrc(作業場所を確かめられない)', bash(f'git -C "$DIR" add {NAME}'), D)
168
+ check('git hash-object -w .npmrc(記録の別の入口は今までどおり)', bash(f'git hash-object -w {NAME}'), D)
169
+ link_dir = os.path.join(BASE, 'linked')
170
+ os.makedirs(link_dir)
171
+ os.symlink(P, os.path.join(link_dir, NAME))
172
+ check('Write: 近道の .npmrc', ev('Write', {'file_path': os.path.join(link_dir, NAME), 'content': SAFE},
173
+ link_dir), D)
174
+ check('git add: 近道の .npmrc', bash(f'git add {NAME}', link_dir), D)
175
+ ssh_dir = os.path.join(BASE, '.ssh')
176
+ os.makedirs(ssh_dir)
177
+ check('Write: 秘密の置き場の下の .npmrc',
178
+ ev('Write', {'file_path': os.path.join(ssh_dir, NAME), 'content': SAFE}, ssh_dir), D)
179
+ home_rc = os.path.join(os.path.realpath(os.path.expanduser('~')), NAME)
180
+ check('Write: ホームの直下(~/.npmrc)', ev('Write', {'file_path': home_rc, 'content': SAFE}), D)
181
+ check('Write: ~/.npmrc の書き方', ev('Write', {'file_path': '~/' + NAME, 'content': SAFE}), D)
182
+ check('Write: ホームの隠しフォルダの下',
183
+ ev('Write', {'file_path': os.path.expanduser('~/.config/x/' + NAME), 'content': SAFE}), D)
184
+
185
+ print('── ⑤ 読む・Bash で書くのは今までどおり止まる ' + '─' * 22)
186
+ put(SAFE)
187
+ check('Read .npmrc', ev('Read', {'file_path': P}), D)
188
+ check(f'cat {NAME}', bash(f'cat {NAME}'), D)
189
+ check(f'cp a {NAME}', bash(f'cp a {NAME}'), D)
190
+ check(f'echo x > {NAME}', bash(f'echo x > {NAME}'), D)
191
+ check(f'tee {NAME}', bash(f'tee {NAME} < a'), D)
192
+
193
+ print('── ⑥ .env など他の秘密のファイルは今までどおり止まる ' + '─' * 14)
194
+ for other in (ENV, ENV + '.local', 'id_' + 'rsa', 'server.pem', '.dev.vars', '.net' + 'rc'):
195
+ put('x=1\n', os.path.join(REPO, other))
196
+ check(f'Write {other}', ev('Write', {'file_path': os.path.join(REPO, other), 'content': SAFE}), D)
197
+ check(f'git add {other}', bash(f'git add {other}'), D)
198
+
199
+ print('── ⑦ 禁止の一覧から Edit(**/.npmrc) を外し、退役の一覧に入れた ' + '─' * 4)
200
+ root = os.path.dirname(os.path.dirname(HERE))
201
+ with open(os.path.join(root, 'sales-template', 'settings.json'), encoding='utf-8') as f:
202
+ deny = json.load(f)['permissions']['deny']
203
+ check('正本の禁止の一覧に Edit(**/.npmrc) が無い', f'Edit(**/{NAME})' in deny, False)
204
+ check('正本の禁止の一覧に Read(**/.npmrc) が無い(前の退役のまま)', f'Read(**/{NAME})' in deny, False)
205
+ with open(os.path.join(root, 'scripts', 'update-guard.sh'), encoding='utf-8') as f:
206
+ ug = f.read()
207
+ check('退役の一覧に "Edit(**/.npmrc)" が在る(各現場からも外す)', f'"Edit(**/{NAME})"' in ug, True)
208
+ check('実物の入った現場には Edit(/.npmrc) を狙い撃ちで戻す', f'"Edit(/{NAME})"' in ug, True)
209
+ finally:
210
+ shutil.rmtree(BASE, ignore_errors=True)
211
+
212
+ print()
213
+ if failures:
214
+ print(f'FAIL {len(failures)} 件')
215
+ for x in failures:
216
+ print(' ' + x)
217
+ sys.exit(1)
218
+ print('PASS')
@@ -223,7 +223,7 @@ def classify(head, work, ctx):
223
223
  if not isinstance(wd, list) or not isinstance(hd, list):
224
224
  why.append("permissions.deny が一覧ではない")
225
225
  else:
226
- allowed = set(ctx["canonical_deny"]) | set(ctx["retired"]) | {"Read(/.npmrc)"}
226
+ allowed = set(ctx["canonical_deny"]) | set(ctx["retired"]) | {"Read(/.npmrc)", "Edit(/.npmrc)"}
227
227
  added = [x for x in wd if x not in hd]
228
228
  odd = [x for x in added if x not in allowed]
229
229
  if odd:
@@ -1576,6 +1576,11 @@ RETIRED_DENY = frozenset({
1576
1576
  "Write(services/!(analytics)/**)",
1577
1577
  "Edit(/home/fshim/projects/TYHLD-platform/services/!(analytics)/**)",
1578
1578
  "Write(/home/fshim/projects/TYHLD-platform/services/!(analytics)/**)",
1579
+ # ★えふさん決定 2026-11-03(便 5751e7ae): 値の入っていない .npmrc は職人が作れる・記録に入れられる。
1580
+ # この行は中身を見られないので、値なしの .npmrc の Write まで止めていた(便 9ca0acd2)。守りは番人の
1581
+ # 中身の判定(policy.py の npmrc_write_is_ref_only)が持つ=値・未知の行が入る書き込みは今までどおり止まる。
1582
+ # ★実物の値が入った現場には、下の (2a-2) が Edit(/.npmrc) を狙い撃ちで戻す(2枚目の守りを残す)。
1583
+ "Edit(**/.npmrc)",
1579
1584
  })
1580
1585
 
1581
1586
  # ★git の状態(読むだけ)。記録されている settings.json には1バイトも書かない(②-b)。
@@ -1860,11 +1865,13 @@ try:
1860
1865
  del _v
1861
1866
  except OSError:
1862
1867
  pass
1863
- _targeted = "Read(/.npmrc)"
1864
- if _has_literal and _targeted not in cur:
1865
- cur = cur + [_targeted]
1866
- perms["deny"] = cur
1867
- changes.append("この現場の .npmrc に実値が直書きされているため Read(/.npmrc) を追記(秘密を守る)")
1868
+ # ★Edit(/.npmrc) も同じ時だけ戻す(便 5751e7ae)。丸ごとの Edit(**/.npmrc) は退役したので、実値の入った
1869
+ # .npmrc を書き換える・消す形は、番人の中身の判定に加えてこの行でも止める(2枚目の守り)。
1870
+ for _targeted in ("Read(/.npmrc)", "Edit(/.npmrc)"):
1871
+ if _has_literal and _targeted not in cur:
1872
+ cur = cur + [_targeted]
1873
+ perms["deny"] = cur
1874
+ changes.append(f"この現場の .npmrc に実値が直書きされているため {_targeted} を追記(秘密を守る)")
1868
1875
 
1869
1876
  # (2a-3) 書き方が壊れて【何も止めていない】禁止の行を、同じ守りが効く正しい書き方へ直す。
1870
1877
  # 【なぜ要るか(実地 2026-10-07)】現場 kenzokun と utatane-backend の禁止の一覧に、ホームに
@@ -260,6 +260,9 @@ description: 采配くんの便(プロンプト末尾に CONDUCTOR_JOB:<id>
260
260
  - ★**除外指定では通らない**(実測 2026-09-27)。`grep -rn 語 . --exclude=.npmrc` は、`.` の再帰でまず止まり、さらに**秘密のファイル名を引数に書いた事自体**でも止まる。「除いて探す」ではなく「場所を名指しする」が正解。
261
261
  - ★**上の形は最初から選ぶ物。** ただし全体を指す形が**書き方の決まりで止められた**(番人の文が `discipline` で始まり、理由と直し方が書いてある)ときは、冒頭④の(ア)〜(エ)をすべて満たす限り、上の形へ書き直して続けてよい(⑥のとおり報告に3つを書く)。★**フォルダ名を名指しした形でも止められたなら、それは書き方の決まりの種類ではない**(場所を名指しした形は書き方の決まりでは止まらない)ので、探す場所や道具を替えて打ち直さず、止められた命令の全文と番人の文を報告して止まる(冒頭の①〜③と⑤・便 b53481c2 §8 の1番がこの形だった)。
262
262
  - **秘密のファイルを読む・引数に名前を書く**(`cat ~/.npmrc`・`--exclude=.npmrc`)→ 止まる。**中身は見に行かない。** 差分は対象を名指しで `git diff -- src docs`、全体で見たいときは除いて `git diff -- . ':(exclude).npmrc'`(`git diff` は中身を読み出す動詞ではないので、この形は通る・鉄則1)。
263
+ - ★**値の入っていない `.npmrc` は、作る・直す・記録に入れるのが通る**(えふさん決定 2026-11-03・便 5751e7ae)。中身が「取り寄せ先の行(`@tyhld:registry=https://npm.pkg.github.com`)」と「`//<ホスト>/:_authToken=${NPM_TOKEN}`」の形の行だけ(空行・注釈は可)なら、**Write/Edit の道具**で作る・直す、**名指しの `git add .npmrc`・`git commit -m 説明 .npmrc`** で記録に入れる、が通る(番人が中身を見て決める・中身は外に出さない)。
264
+ - 通る例: Write の道具で `<現場>/.npmrc` に上の2行を書く / `git -C <実際のパス> add package.json .npmrc`
265
+ - ★止まる形(今までどおり): `_authToken` の右が `${…}` でなく実物の文字列/未知の行・`_auth`・`_password`・`always-auth`・`username` の行が混じる/元の `.npmrc` に実物の値が在る(上書き・直しで消させない)/`~/.npmrc`・近道・作業場所が変数の `git -C "$DIR"`/**読む**(Read の道具・`cat`)/**Bash で書く**(`cp`・`tee`・`>`=別の作業場所へ写すときも、Write の道具で同じ2行を書く)。★止められたら回避せず止めて報告する(`danger`)。
263
266
  - **標準エラーの捨て先を、あとで文字列の途中に差し込む変数やコマンド置換の中に入れる**(`S="$(何か 2>/dev/null)"` と置き、別の行で `"repos/<その変数>/branches/…"` のように使う/`gh api "repos/$(何か 2>/dev/null)/branches/main"` と直に書く)→ 止まる。番人は字面を展開してから測り直すので、捨て先が `/dev/null` ではなく**その後ろのパスが貼り付いた別の名前**として取り出され、`/dev` 直下への書き込みに見える(実測 2026-09-27。鉄則7の塊がこれで6便すべて止まっていた)。**文句を捨てる所を、小さな関数1か所に寄せる。**
264
267
  - 通る例: 先に `q() { "$@" 2>/dev/null; }` を置き、以後は `S="$(q 何か)"` と書く(★変数の値に捨て先が入らないので、どこに差し込んでも止まらない)。
265
268
  - ★**この形の番人の文は `discipline`(書き方の注意・直し方つき)になった**(便 227aeebb・2026-10-10)。それまでは `danger: redirect into system path (/dev)` と出ており、実態(無害)と合っていなかった。**止まること自体は変わらない。**④の(ア)〜(エ)がそろう限り、上の通る例へ書き直して続けてよい(⑥のとおり報告に3つを書く)。