@athsra/cli 1.1.2 → 1.1.3

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": "@athsra/cli",
3
- "version": "1.1.2",
3
+ "version": "1.1.3",
4
4
  "description": "athsra CLI — E2EE secret manager on Cloudflare edge. Doppler-style dev UX + zero-knowledge encryption + soft-delete + version history. MIT.",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -1,8 +1,11 @@
1
+ import { removeRecipient, type SecretEnvelopeV2 } from '@athsra/crypto';
1
2
  import { loadAuthContext } from '../lib/auth-context.ts';
2
3
  import { CONFIG_USAGE_HINT, configTag, resolveProject } from '../lib/auto-project.ts';
4
+ import { promptConfirm } from '../lib/prompt.ts';
3
5
 
4
6
  const USAGE = [
5
- 'usage: athsra recipients <project>[:<env>]',
7
+ 'usage: athsra recipients <project>[:<env>] # recipient 목록 (읽기 전용)',
8
+ ' or: athsra recipients prune-orphans [<project>] [--apply] # orphan service recipient 정리',
6
9
  '',
7
10
  'envelope 의 recipient 목록(읽기 전용) — master / member / service token 분포 감사.',
8
11
  '값·평문 미노출 (recipient kind·id 만 표시). service recipient_id 는 비밀 아님',
@@ -11,12 +14,31 @@ const USAGE = [
11
14
  CONFIG_USAGE_HINT,
12
15
  ].join('\n');
13
16
 
17
+ const PRUNE_USAGE = [
18
+ 'usage: athsra recipients prune-orphans [<project>[:<env>]] [--apply|--yes]',
19
+ '',
20
+ 'auth_tokens 에 없는 service recipient(orphan — revoke/만료 후 envelope 에 남은 메타)를 제거.',
21
+ 'master/member recipient 는 절대 건드리지 않는다. DEK 는 회전하지 않음(메타 정리 — 완전 re-key 는',
22
+ '`athsra rotate-master`). project 생략 시 전 project 를 default 환경에서 스윕.',
23
+ '',
24
+ '기본은 dry-run(변경 없음). 실제 제거는 --apply (confirm: --yes 또는 ATHSRA_PRUNE_CONFIRMED=1).',
25
+ '제거는 org owner 권한 필요(worker 강제) — user(master-pw) 컨텍스트에서 실행.',
26
+ '',
27
+ CONFIG_USAGE_HINT,
28
+ ].join('\n');
29
+
14
30
  /**
15
- * 인시던트 후속(2026-06-14) — envelope recipient 구조 운영 가시성. founding sweep / rotate-master /
16
- * 멤버 removal service:* recipient 보존/탈락됐는지 `athsra service-token list` 대조 감사.
17
- * getEnvelope 이미 recipients[] 주므로 복호 불필요 모든 인증 모드(user/identity/service)에서 동작.
31
+ * 인시던트 후속(2026-06-14) — envelope recipient 구조 운영 가시성 + orphan 정리.
32
+ * - `athsra recipients <project>` : recipient 분포 감사 (읽기 전용, 모든 인증 모드).
33
+ * - `athsra recipients prune-orphans [...]` : auth_tokens 없는 service recipient 정리.
34
+ * getEnvelope 가 이미 recipients[] 를 주므로 복호 불필요.
18
35
  */
19
36
  export async function recipientsCmd(args: string[]): Promise<number> {
37
+ if (args[0] === 'prune-orphans') return pruneOrphansCmd(args.slice(1));
38
+ return listRecipientsCmd(args);
39
+ }
40
+
41
+ async function listRecipientsCmd(args: string[]): Promise<number> {
20
42
  if (args.includes('--help') || args.includes('-h')) {
21
43
  console.log(USAGE);
22
44
  return 0;
@@ -54,3 +76,93 @@ export async function recipientsCmd(args: string[]): Promise<number> {
54
76
  console.log(`\n요약: master ${master} · service ${service} · member ${member}`);
55
77
  return 0;
56
78
  }
79
+
80
+ /**
81
+ * orphan service recipient 정리 — auth_tokens 에 살아있는 service token 의 recipient_id 와
82
+ * envelope 의 service recipient 를 대조해, DB 에 없는 service recipient(revoke/만료 후 envelope 에
83
+ * 남은 메타)만 제거한다. master/member 는 절대 건드리지 않는다(removeRecipient 가 master 제거 차단,
84
+ * 우리는 kind==='service' 만 후보로 둠). DEK 미회전 — 메타 정리(완전 re-key 는 rotate-master).
85
+ */
86
+ async function pruneOrphansCmd(args: string[]): Promise<number> {
87
+ if (args.includes('--help') || args.includes('-h')) {
88
+ console.log(PRUNE_USAGE);
89
+ return 0;
90
+ }
91
+ const apply = args.includes('--apply');
92
+ const yes = args.includes('--yes') || args.includes('-y');
93
+ const positional = args.filter((a) => !a.startsWith('-'));
94
+ const { project, config } = resolveProject(positional, { requirePositional: true });
95
+
96
+ const ctx = await loadAuthContext(project);
97
+ if (!ctx) return 1;
98
+ const { client } = ctx;
99
+
100
+ // 살아있는 service token 의 recipient_id 집합 (전 project — recipient_id 는 전역 유일).
101
+ let live: Set<string>;
102
+ try {
103
+ const { tokens } = await client.listServiceTokens();
104
+ live = new Set(tokens.map((t) => t.recipient_id));
105
+ } catch (err) {
106
+ console.error(`service-token list 조회 실패: ${(err as Error).message}`);
107
+ return 1;
108
+ }
109
+
110
+ const targets = project ? [project] : await client.listProjects();
111
+ let totalOrphans = 0;
112
+ let prunedProjects = 0;
113
+
114
+ for (const proj of targets) {
115
+ const env = await client.getEnvelope(proj, config);
116
+ if (env?.version !== 2) continue;
117
+ const orphans = env.recipients.filter((r) => r.kind === 'service' && !live.has(r.id));
118
+ if (orphans.length === 0) continue;
119
+ totalOrphans += orphans.length;
120
+ const tag = configTag(config);
121
+
122
+ console.log(`${proj}${tag} — orphan service recipient(s) (auth_tokens 에 없음):`);
123
+ for (const r of orphans) console.log(` service ${r.id}`);
124
+
125
+ if (!apply) {
126
+ console.log('');
127
+ continue;
128
+ }
129
+
130
+ // confirm (dry-run 이 아닌 실제 제거).
131
+ if (!yes && process.env.ATHSRA_PRUNE_CONFIRMED !== '1') {
132
+ const ok = await promptConfirm(
133
+ `${proj}${tag}: 위 ${orphans.length} orphan service recipient 제거? (master/member 보존, DEK 불변)`,
134
+ false,
135
+ );
136
+ if (!ok) {
137
+ console.log(' 건너뜀.\n');
138
+ continue;
139
+ }
140
+ }
141
+
142
+ let pruned: SecretEnvelopeV2 = env;
143
+ for (const r of orphans) pruned = removeRecipient(pruned, r.id);
144
+ try {
145
+ await client.putEnvelope(proj, pruned, config);
146
+ } catch (err) {
147
+ console.error(
148
+ ` ✗ ${proj}${tag} 저장 실패 (owner 권한 필요할 수 있음): ${(err as Error).message}\n`,
149
+ );
150
+ continue;
151
+ }
152
+ prunedProjects += 1;
153
+ console.log(` ✓ ${orphans.length} recipient(s) 제거 — master/member 보존, DEK 불변.\n`);
154
+ }
155
+
156
+ if (totalOrphans === 0) {
157
+ console.log(
158
+ 'orphan service recipient 없음 (모든 service recipient 가 살아있는 token 과 일치).',
159
+ );
160
+ return 0;
161
+ }
162
+ if (!apply) {
163
+ console.log(`총 ${totalOrphans} orphan. dry-run (변경 없음). 제거하려면 --apply.`);
164
+ } else {
165
+ console.log(`완료: ${prunedProjects} project 에서 orphan 제거.`);
166
+ }
167
+ return 0;
168
+ }
@@ -1,9 +1,11 @@
1
+ import { removeRecipient } from '@athsra/crypto';
1
2
  import { loadAuthContext } from '../lib/auth-context.ts';
2
3
  import { resolveProject } from '../lib/auto-project.ts';
3
4
  import { red, yellow } from '../lib/colors.ts';
4
5
  import {
5
6
  type CreatedServiceToken,
6
7
  createServiceTokenWithRecipient,
8
+ createServiceTokenWithRecipientAsMember,
7
9
  } from '../lib/service-tokens.ts';
8
10
 
9
11
  /** worker expiry-notify (apps/worker/src/queue/expiry-notify.ts) 의 최임박 threshold 와 동기. */
@@ -17,6 +19,8 @@ const USAGE = [
17
19
  '',
18
20
  'service token = scoped + revocable + master-pw 없이 envelope 복호 가능한 token.',
19
21
  ' → headless 호스트 (NAS Docker, CI, 자동화) 용 — E2EE 유지, master pw 유출 X.',
22
+ '발급 컨텍스트: user(master pw) 또는 identity(`athsra login` 브라우저 — AI-native, master pw 불요).',
23
+ ' identity 모드는 v2 envelope + 본인 member recipient 전제(master pw 머신서 1회 준비).',
20
24
  ].join('\n');
21
25
 
22
26
  async function createCmd(args: string[]): Promise<number> {
@@ -57,20 +61,32 @@ async function createCmd(args: string[]): Promise<number> {
57
61
 
58
62
  const ctx = await loadAuthContext();
59
63
  if (!ctx) return 1;
60
- if (ctx.kind !== 'user') {
61
- console.error('athsra service-token create 은 user token (master pw) 가 필요합니다.');
64
+ if (ctx.kind === 'service') {
65
+ console.error(
66
+ 'service token 으로는 다른 service token 을 발급할 수 없습니다 — user(master pw) 또는 identity(device login) 컨텍스트 필요.',
67
+ );
62
68
  return 1;
63
69
  }
64
70
 
65
- // 발급 + recipient 추가 (lib/service-tokens.ts — MCP athsra_service_token_create 와 공용 경로)
71
+ // 발급 + recipient 추가 (lib/service-tokens.ts — MCP athsra_service_token_create 와 공용 경로).
72
+ // user 모드(master pw) → master recipient 로 DEK unwrap. identity 모드(device login, master pw
73
+ // 부재) → 본인 raw identity privkey(member 경로)로 DEK unwrap (AI-native onboarding).
66
74
  let created: CreatedServiceToken;
67
75
  try {
68
- created = await createServiceTokenWithRecipient(ctx, {
69
- project,
70
- label,
71
- perms,
72
- expiresInDays: expiresDays,
73
- });
76
+ created =
77
+ ctx.kind === 'identity'
78
+ ? await createServiceTokenWithRecipientAsMember(ctx, {
79
+ project,
80
+ label,
81
+ perms,
82
+ expiresInDays: expiresDays,
83
+ })
84
+ : await createServiceTokenWithRecipient(ctx, {
85
+ project,
86
+ label,
87
+ perms,
88
+ expiresInDays: expiresDays,
89
+ });
74
90
  } catch (err) {
75
91
  console.error((err as Error).message);
76
92
  return 1;
@@ -113,9 +129,27 @@ async function revokeCmd(args: string[]): Promise<number> {
113
129
 
114
130
  const res = await client.revoke(token);
115
131
  console.log(`✓ revoked: ${res.revoked}`);
116
- console.log(
117
- ' envelope recipient entry 그대로 남지만 보안상 무해 (worker auth hash 로 거부).',
118
- );
132
+
133
+ // 근본수정(2026-06-15): revoke envelope service recipient 동반 정리 orphan recipient
134
+ // 재발 차단. worker 가 service token 의 recipient_id + project 를 반환. removeRecipient 는
135
+ // master/member 미접근(service 만). PUT 은 owner 권한 필요(worker 강제) → 실패 시 best-effort
136
+ // 안내(prune-orphans 로 폴백). const 캡처로 closure narrowing 유지.
137
+ const recipientId = res.recipient_id;
138
+ const project = res.project;
139
+ if (recipientId && project) {
140
+ try {
141
+ const env = await client.getEnvelope(project);
142
+ if (env?.version === 2 && env.recipients.some((r) => r.id === recipientId)) {
143
+ await client.putEnvelope(project, removeRecipient(env, recipientId));
144
+ console.log(` ✓ envelope service recipient 정리: ${recipientId} (${project})`);
145
+ }
146
+ } catch (err) {
147
+ console.log(
148
+ ` ⚠ envelope recipient ${recipientId} 남음 (${(err as Error).message}) — ` +
149
+ `\`athsra recipients prune-orphans ${project}\` 로 정리하세요.`,
150
+ );
151
+ }
152
+ }
119
153
  return 0;
120
154
  }
121
155
 
@@ -124,8 +158,10 @@ async function listCmd(args: string[]): Promise<number> {
124
158
 
125
159
  const ctx = await loadAuthContext();
126
160
  if (!ctx) return 1;
127
- if (ctx.kind !== 'user') {
128
- console.error('athsra service-token list 는 user token (master pw) 가 필요합니다.');
161
+ if (ctx.kind === 'service') {
162
+ console.error(
163
+ 'service token 으로는 목록 조회 불가 — user(master pw) 또는 identity(device login) 필요.',
164
+ );
129
165
  return 1;
130
166
  }
131
167
  const { client } = ctx;
package/src/index.ts CHANGED
@@ -29,7 +29,7 @@ import { setCmd } from './commands/set.ts';
29
29
  import { unsetCmd } from './commands/unset.ts';
30
30
  import { versionsCmd } from './commands/versions.ts';
31
31
 
32
- const VERSION = '1.1.2';
32
+ const VERSION = '1.1.3';
33
33
 
34
34
  const commands: Record<string, (args: string[]) => Promise<number>> = {
35
35
  login: loginCmd,
@@ -89,6 +89,7 @@ Usage:
89
89
  athsra service-token list [<project>] 발급한 service token 메타 (revoke·만료 점검용)
90
90
  athsra service-token revoke <token> service token 무효화
91
91
  athsra recipients <project>[:<env>] envelope recipient 목록 감사 (master/member/service, 읽기 전용)
92
+ athsra recipients prune-orphans [<p>] [--apply] auth_tokens 에 없는 orphan service recipient 정리 (dry-run 기본)
92
93
  athsra audit [--actor=...] [--action=...] audit log 조회 (--all=cursor follow, --format=table|json|jsonl)
93
94
  athsra users {list|invite <id> [--role=R]} RBAC: user 목록 / 신규 invite (admin role 필요)
94
95
  athsra role {grant|revoke} <user_id> <R> role 부여/제거 (admin/dev/viewer/auditor/sa)
package/src/lib/client.ts CHANGED
@@ -411,14 +411,27 @@ export class AthsraClient {
411
411
  return (await res.json()) as { token: string; org_id: number; role: string };
412
412
  }
413
413
 
414
- async revoke(targetToken?: string): Promise<{ ok: boolean; revoked: string; self?: boolean }> {
414
+ async revoke(targetToken?: string): Promise<{
415
+ ok: boolean;
416
+ revoked: string;
417
+ self?: boolean;
418
+ /** service token revoke 시 worker 가 동반 반환 — CLI 가 envelope recipient 정리에 사용. */
419
+ recipient_id?: string;
420
+ project?: string;
421
+ }> {
415
422
  const res = await fetch(this.url('/auth/revoke'), {
416
423
  method: 'POST',
417
424
  headers: this.headers({ 'content-type': 'application/json' }),
418
425
  body: JSON.stringify(targetToken ? { token: targetToken } : {}),
419
426
  });
420
427
  if (!res.ok) throw new Error(`revoke ${res.status}: ${await res.text()}`);
421
- return (await res.json()) as { ok: boolean; revoked: string; self?: boolean };
428
+ return (await res.json()) as {
429
+ ok: boolean;
430
+ revoked: string;
431
+ self?: boolean;
432
+ recipient_id?: string;
433
+ project?: string;
434
+ };
422
435
  }
423
436
 
424
437
  /** DR — BACKUP_STORE → STORE 복원. dry_run=!execute. execute 는 content-bound confirm 필수. */
@@ -8,19 +8,24 @@
8
8
  * → loadAuthContext → kind 가드 → client 호출 → jsonOk.
9
9
  *
10
10
  * kind 가드 2단 (epic D-2):
11
- * - **master pw 소비 3종** (org_remove_member 의 owner DEK 회전 / project_share 의 envelope
12
- * 재포장 / service_token_create 의 recipient wrap) 은 user(master pw) 전용 — identity
13
- * 디바이스에선 masterPwDenied actionable 거부 (master pw 머신에 영원히 없음).
14
- * - 나머지 4종은 user|identity (둘 다 user-급 토큰) — service token 7종 전부 거부.
11
+ * - **master pw 소비 2종** (org_remove_member 의 owner DEK 회전 / project_share 의 envelope
12
+ * 재포장) 은 user(master pw) 전용 — identity 디바이스에선 masterPwDenied 로 actionable 거부.
13
+ * - service_token_create user(master 경로) | identity(member 경로, 본인 raw privkey DEK
14
+ * unwrap AI-native onboarding) 둘 다 — service token 거부.
15
+ * - 나머지는 user|identity (둘 다 user-급 토큰) — service token 은 7종 전부 거부.
15
16
  *
16
17
  * 시크릿 값 무노출 (epic D-1) — 유일 예외는 service_token_create 의 1회성 ats_* 반환
17
18
  * (ONE-TIME EXPOSURE warning 동반). 그 외 응답은 메타데이터만.
18
19
  */
19
20
 
21
+ import { removeRecipient } from '@athsra/crypto';
20
22
  import { loadAuthContext } from '../auth-context.ts';
21
23
  import type { AthsraClient } from '../client.ts';
22
24
  import { grantOrgAccess, rotateAfterRemoval } from '../org-rewrap.ts';
23
- import { createServiceTokenWithRecipient } from '../service-tokens.ts';
25
+ import {
26
+ createServiceTokenWithRecipient,
27
+ createServiceTokenWithRecipientAsMember,
28
+ } from '../service-tokens.ts';
24
29
  import { readInteger, readString } from './args.ts';
25
30
  import { requireConfirm } from './confirm.ts';
26
31
  import { jsonError, jsonOk, notLoggedIn, type ToolTextResult } from './result.ts';
@@ -191,7 +196,7 @@ export async function handleProjectUnshare(
191
196
  /**
192
197
  * athsra_service_token_create — scoped service token 발급 + envelope recipient 추가.
193
198
  * expires_days 필수 1..365 (MCP 발급 자격증명은 반드시 만료). 유일한 자격증명-반환 도구.
194
- * master pw 소비identity 거부.
199
+ * user(master pw) 또는 identity(device login, member 경로 AI-native) 컨텍스트. service 거부.
195
200
  */
196
201
  export async function handleServiceTokenCreate(
197
202
  args: Record<string, unknown> | undefined,
@@ -211,13 +216,21 @@ export async function handleServiceTokenCreate(
211
216
  }
212
217
  const ctx = await loadAuthContext();
213
218
  if (!ctx) return notLoggedIn();
214
- if (ctx.kind !== 'user') return masterPwDenied('service_token_create', ctx.kind);
215
- const created = await createServiceTokenWithRecipient(ctx, {
216
- project,
217
- label,
218
- perms,
219
- expiresInDays: expiresDays,
220
- });
219
+ if (ctx.kind === 'service') return masterPwDenied('service_token_create', 'service');
220
+ const created =
221
+ ctx.kind === 'identity'
222
+ ? await createServiceTokenWithRecipientAsMember(ctx, {
223
+ project,
224
+ label,
225
+ perms,
226
+ expiresInDays: expiresDays,
227
+ })
228
+ : await createServiceTokenWithRecipient(ctx, {
229
+ project,
230
+ label,
231
+ perms,
232
+ expiresInDays: expiresDays,
233
+ });
221
234
  return jsonOk({
222
235
  ...created,
223
236
  warning:
@@ -238,10 +251,29 @@ export async function handleServiceTokenRevoke(
238
251
  if (!ctx) return notLoggedIn();
239
252
  if (ctx.kind === 'service') return masterPwDenied('service_token_revoke', 'service');
240
253
  const res = await ctx.client.revoke(token);
254
+ // 근본수정: revoke 후 envelope service recipient 동반 정리(orphan 재발 차단). best-effort —
255
+ // PUT 은 owner 강제. const 캡처로 closure narrowing 유지.
256
+ const recipientId = res.recipient_id;
257
+ const project = res.project;
258
+ let recipientCleaned = false;
259
+ if (recipientId && project) {
260
+ try {
261
+ const env = await ctx.client.getEnvelope(project);
262
+ if (env?.version === 2 && env.recipients.some((r) => r.id === recipientId)) {
263
+ await ctx.client.putEnvelope(project, removeRecipient(env, recipientId));
264
+ recipientCleaned = true;
265
+ }
266
+ } catch {
267
+ // best-effort — prune-orphans 로 폴백 (note 로 안내).
268
+ }
269
+ }
241
270
  return jsonOk({
242
271
  ok: res.ok,
243
272
  revoked: res.revoked,
244
- note: 'worker auth rejects the token immediately; the stale envelope recipient entry left behind is harmless.',
273
+ recipient_cleaned: recipientCleaned,
274
+ note: recipientCleaned
275
+ ? 'worker auth rejects the token immediately; the envelope service recipient was also pruned.'
276
+ : 'worker auth rejects the token immediately. If a stale service recipient remains, run `athsra recipients prune-orphans <project>`.',
245
277
  });
246
278
  }
247
279
 
@@ -3,11 +3,15 @@
3
3
  *
4
4
  * `commands/service-token.ts` createCmd 에서 추출 — CLI 와 MCP(athsra_service_token_create)가
5
5
  * 같은 경로를 소비해 드리프트를 막는다. 발급(worker) → v1→v2 migrate(필요 시) →
6
- * addServiceRecipient(DEK 를 token secret 으로 wrap) → putEnvelope. master pw 필수
7
- * (recipient 추가에 master recipient DEK unwrap 이 필요) — identity 디바이스 불가.
6
+ * addServiceRecipient(DEK 를 token secret 으로 wrap) → putEnvelope.
7
+ *
8
+ * 두 경로: (1) user(master pw) — master recipient 로 DEK unwrap (v1 자동 migrate 가능). (2) identity
9
+ * 디바이스(master pw 부재) — 본인 raw identity privkey(member:userId 경로)로 DEK unwrap. AI-native
10
+ * onboarding: `athsra login`(브라우저) 후 master pw 없이도 발급(member recipient 존재 + v2 전제).
8
11
  */
9
12
  import { addServiceRecipient, migrateV1ToV2, type SecretEnvelopeV2 } from '@athsra/crypto';
10
- import type { UserAuthContext } from './auth-context.ts';
13
+ import { addServiceRecipientAsMember } from '@athsra/crypto/member';
14
+ import type { IdentityAuthContext, UserAuthContext } from './auth-context.ts';
11
15
 
12
16
  export interface CreatedServiceToken {
13
17
  token: string;
@@ -60,3 +64,52 @@ export async function createServiceTokenWithRecipient(
60
64
 
61
65
  return created;
62
66
  }
67
+
68
+ /**
69
+ * identity 디바이스 모드(master pw 부재) 발급 — 본인 raw identity privkey(member:userId 경로)로
70
+ * DEK 를 unwrap 해 service token secret 으로 wrap. v1 envelope / member recipient 부재 시 throw
71
+ * (둘 다 master pw 머신에서 1회 준비 필요 — v1→v2 마이그레이션, migrate-envelopes --self). recipient
72
+ * 추가는 worker 가 owner/admin 강제 — founding identity 디바이스(owner)는 자기 project 에 발급 가능.
73
+ */
74
+ export async function createServiceTokenWithRecipientAsMember(
75
+ ctx: Pick<IdentityAuthContext, 'client' | 'identityPrivateKey' | 'userId'>,
76
+ args: { project: string; label: string; perms: 'read' | 'write'; expiresInDays?: number },
77
+ ): Promise<CreatedServiceToken> {
78
+ const { client, identityPrivateKey, userId } = ctx;
79
+
80
+ const envelope = await client.getEnvelope(args.project);
81
+ if (!envelope) {
82
+ throw new Error(
83
+ `project ${args.project} envelope 없음 — master pw 머신에서 \`athsra set ${args.project} KEY=value\` 1회 실행.`,
84
+ );
85
+ }
86
+ if (envelope.version !== 2) {
87
+ throw new Error(
88
+ `identity 모드 발급은 v2 envelope 필요 — master pw 머신에서 \`athsra set ${args.project} ...\` 1회로 v1→v2 마이그레이션 후 재시도.`,
89
+ );
90
+ }
91
+ if (!envelope.recipients.some((r) => r.id === `member:${userId}`)) {
92
+ throw new Error(
93
+ `member:${userId} recipient 없음 — master pw 머신에서 \`athsra migrate-envelopes --self\` 1회 실행 후 재시도.`,
94
+ );
95
+ }
96
+
97
+ const created = await client.createServiceToken({
98
+ project: args.project,
99
+ label: args.label,
100
+ perms: args.perms,
101
+ expiresInDays: args.expiresInDays,
102
+ });
103
+
104
+ // raw identity privkey 로 member:userId recipient 의 DEK 를 unwrap → token secret 으로 wrap.
105
+ const updated = await addServiceRecipientAsMember(
106
+ envelope,
107
+ identityPrivateKey,
108
+ userId,
109
+ created.token,
110
+ created.recipient_id,
111
+ );
112
+ await client.putEnvelope(args.project, updated);
113
+
114
+ return created;
115
+ }