@sayren/store-sdk 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,255 @@
1
+ import { z } from "zod";
2
+
3
+ /**
4
+ * 감사 로그와 승인 요청 — `/v1/audit-logs`, `/v1/approval-requests` (이슈 #36).
5
+ *
6
+ * 관리 API 쓰기(`/v1/**`의 GET 외 요청)는 모두 요청 단위 기록(`source: REQUEST`) 한 줄을 남긴다. 환불·직권취소 같은
7
+ * 도메인 동작은 그 안에서 변경 전후를 담은 기록(`source: DOMAIN`)을 따로 남기고 `requestId`로 요청 기록과 이어진다.
8
+ */
9
+
10
+ export const auditActorTypeSchema = z
11
+ .enum(["USER", "AGENT", "APP", "TOKEN", "SYSTEM"])
12
+ .describe(
13
+ "행위자 유형. `USER`=콘솔 사용자, `AGENT`=AI 에이전트(MCP·에이전트용 API 토큰), `APP`=앱(OAuth 클라이언트·M2M), " +
14
+ "`TOKEN`=API 토큰, `SYSTEM`=자동화(주기 잡)",
15
+ );
16
+ export type AuditActorType = z.infer<typeof auditActorTypeSchema>;
17
+
18
+ export const auditActorSchema = z.object({
19
+ type: auditActorTypeSchema,
20
+ id: z
21
+ .string()
22
+ .describe(
23
+ "행위자 ID. `USER`=userId, `TOKEN`·`AGENT`(API 토큰)=`pat:{tokenId}`, `APP`=`client:{clientId}`, `SYSTEM`=`system`. " +
24
+ "사람이 앱에 위임한 호출은 `APP`이고 위임한 사람은 `metadata.onBehalfOf`에 있다",
25
+ ),
26
+ name: z.string().nullable().describe("기록 시점의 표시 이름. 알 수 없으면 null"),
27
+ });
28
+ export type AuditActor = z.infer<typeof auditActorSchema>;
29
+
30
+ export const auditLogSourceSchema = z
31
+ .enum(["REQUEST", "DOMAIN"])
32
+ .describe(
33
+ "기록 단위. `REQUEST`=관리 API 쓰기 요청 한 건, `DOMAIN`=환불·취소 같은 도메인 동작의 상세",
34
+ );
35
+ export type AuditLogSource = z.infer<typeof auditLogSourceSchema>;
36
+
37
+ export const auditLogOutcomeSchema = z
38
+ .enum(["SUCCEEDED", "FAILED", "PENDING_APPROVAL", "DENIED", "DRY_RUN"])
39
+ .describe(
40
+ "요청 결과. `PENDING_APPROVAL`=승인 대기로 보류(202), `DENIED`=에이전트 정책으로 거부(403 `AGENT_OPERATION_DENIED`), " +
41
+ "`DRY_RUN`=드라이런(`x-sayren-dry-run: 1`)이라 실행하지 않음",
42
+ );
43
+ export type AuditLogOutcome = z.infer<typeof auditLogOutcomeSchema>;
44
+
45
+ export const auditLogSchema = z.object({
46
+ auditId: z.string().describe("감사 로그 ID"),
47
+ occurredAt: z.string().describe("기록 일시 (ISO 8601)"),
48
+ source: auditLogSourceSchema,
49
+ action: z
50
+ .string()
51
+ .describe(
52
+ "동작. `REQUEST`는 오퍼레이션 ID(OpenAPI `operationId`, 예: `ProductsController_patch`), `DOMAIN`은 도메인 코드(예: `ORDER_ITEM_CANCELED_BY_SELLER`)",
53
+ ),
54
+ actor: auditActorSchema,
55
+ actorRole: z
56
+ .string()
57
+ .nullable()
58
+ .describe("요청 시점의 스토어 역할. 역할이 없는 토큰·자동화는 null"),
59
+ target: z.object({
60
+ type: z.string().describe("대상 리소스 유형 (예: `products`, `order-items`, `claim`)"),
61
+ id: z
62
+ .string()
63
+ .nullable()
64
+ .describe("대상 리소스 ID. 목록 대상 요청처럼 하나로 정할 수 없으면 null"),
65
+ }),
66
+ requestId: z
67
+ .string()
68
+ .nullable()
69
+ .describe(
70
+ "요청 ID. 같은 요청에서 나온 `REQUEST`·`DOMAIN` 기록이 같은 값을 가진다. 자동화는 null",
71
+ ),
72
+ method: z.string().nullable().describe("HTTP 메서드 (`REQUEST`만)"),
73
+ path: z
74
+ .string()
75
+ .nullable()
76
+ .describe("요청 경로와 쿼리 (`REQUEST`만). 민감한 쿼리 값은 `***`로 가린다"),
77
+ statusCode: z.number().int().nullable().describe("응답 HTTP 상태 코드 (`REQUEST`만)"),
78
+ outcome: auditLogOutcomeSchema.nullable().describe("요청 결과 (`REQUEST`만)"),
79
+ errorCode: z.string().nullable().describe("에러 응답의 `error.code` (실패한 요청만)"),
80
+ traceId: z.string().nullable().describe("추적 ID. 에러 응답의 `error.traceId`와 같다"),
81
+ idempotencyKey: z.string().nullable().describe("요청의 멱등키"),
82
+ approvalId: z
83
+ .string()
84
+ .nullable()
85
+ .describe("승인 요청 ID. 승인 대기로 보류된 요청과 승인 뒤 실행된 요청에 실린다"),
86
+ metadata: z
87
+ .record(z.string(), z.unknown())
88
+ .describe(
89
+ "부가 정보. 도메인 기록은 변경 전후 값·사유를, 승인 실행 기록은 승인자(`approvedBy`)를 싣는다",
90
+ ),
91
+ });
92
+ export type AuditLog = z.infer<typeof auditLogSchema>;
93
+
94
+ /** 쉼표 구분 목록 쿼리 → 배열 */
95
+ function commaList<T extends z.ZodType<string, string>>(item: T) {
96
+ return z
97
+ .union([z.string(), z.array(z.string())])
98
+ .transform((value) =>
99
+ (Array.isArray(value) ? value : [value])
100
+ .flatMap((part) => part.split(","))
101
+ .map((part) => part.trim())
102
+ .filter((part) => part.length > 0),
103
+ )
104
+ .pipe(z.array(item).min(1));
105
+ }
106
+
107
+ /** 감사 로그 조회 쿼리 — `GET /audit-logs` */
108
+ export const auditLogListQuerySchema = z.object({
109
+ from: z.string().optional().describe("조회 시작 일시 (ISO 8601, 포함)"),
110
+ to: z.string().optional().describe("조회 종료 일시 (ISO 8601, 미포함)"),
111
+ actorType: commaList(auditActorTypeSchema)
112
+ .optional()
113
+ .describe("행위자 유형 필터. 여러 개는 쉼표로 구분한다 (예: `AGENT,APP`)"),
114
+ actorId: z.string().optional().describe("행위자 ID 필터 (정확히 일치)"),
115
+ action: z.string().optional().describe("동작 필터 (정확히 일치)"),
116
+ targetType: z.string().optional().describe("대상 유형 필터 (정확히 일치)"),
117
+ targetId: z.string().optional().describe("대상 ID 필터 (정확히 일치)"),
118
+ source: auditLogSourceSchema.optional(),
119
+ outcome: auditLogOutcomeSchema.optional(),
120
+ requestId: z
121
+ .string()
122
+ .optional()
123
+ .describe("요청 ID 필터 — 한 요청의 요청·도메인 기록을 함께 본다"),
124
+ approvalId: z.string().optional().describe("승인 요청 ID 필터"),
125
+ cursor: z.string().optional().describe("이전 응답의 `nextCursor`. 생략하면 가장 최신부터"),
126
+ limit: z.coerce.number().int().min(1).max(100).optional().describe("최대 건수 (1~100, 기본 50)"),
127
+ });
128
+ /** 파싱된 조회 쿼리 (서버 측). `actorType`은 항상 배열이다 */
129
+ export type AuditLogListParams = z.infer<typeof auditLogListQuerySchema>;
130
+
131
+ /** 클라이언트 `auditLogs.list` 인자. `actorType`은 단일 값·배열 모두 받고 쉼표로 직렬화한다 */
132
+ export type AuditLogListOptions = Omit<AuditLogListParams, "actorType"> & {
133
+ actorType?: AuditActorType | AuditActorType[];
134
+ };
135
+
136
+ export const auditLogPageSchema = z.object({
137
+ items: z.array(auditLogSchema),
138
+ nextCursor: z.string().nullable().describe("다음 페이지 커서. 마지막 페이지면 null"),
139
+ });
140
+ export type AuditLogPage = z.infer<typeof auditLogPageSchema>;
141
+
142
+ // ─── 에이전트 쓰기 정책·영향 미리보기 ──────────────────────────
143
+
144
+ export const agentPolicyDecisionSchema = z
145
+ .enum(["ALLOW", "APPROVAL_REQUIRED", "DENIED"])
146
+ .describe(
147
+ "에이전트 쓰기 판정. `ALLOW`=바로 실행, `APPROVAL_REQUIRED`=콘솔 승인 뒤 실행, `DENIED`=에이전트는 실행할 수 없음",
148
+ );
149
+ export type AgentPolicyDecision = z.infer<typeof agentPolicyDecisionSchema>;
150
+
151
+ const previewValueSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]);
152
+
153
+ export const writePreviewSchema = z.object({
154
+ operationId: z.string().describe("오퍼레이션 ID"),
155
+ method: z.string(),
156
+ path: z.string(),
157
+ target: z.object({ type: z.string(), id: z.string().nullable() }),
158
+ changes: z
159
+ .array(
160
+ z.object({
161
+ field: z.string().describe("바뀌는 필드"),
162
+ before: z.unknown().describe("현재 값. 새로 만드는 요청이거나 읽을 수 없으면 null"),
163
+ after: z.unknown().describe("요청이 넣을 값"),
164
+ }),
165
+ )
166
+ .describe("값이 달라지는 필드. 서버가 현재 값과 비교할 수 있는 오퍼레이션만 채운다"),
167
+ facts: z
168
+ .record(z.string(), previewValueSchema)
169
+ .describe("영향 요약 (예: 취소 수량·주문상품 금액·예상 환불액). 오퍼레이션마다 다르다"),
170
+ });
171
+ export type WritePreview = z.infer<typeof writePreviewSchema>;
172
+
173
+ /** `x-sayren-dry-run: 1`을 실은 쓰기 요청의 응답(200) — 실행하지 않고 판정과 영향만 돌려준다 */
174
+ export const writeDryRunResultSchema = z.object({
175
+ dryRun: z.literal(true),
176
+ decision: agentPolicyDecisionSchema,
177
+ reason: z.string().nullable().describe("승인 필요·거부 사유. `ALLOW`면 null"),
178
+ preview: writePreviewSchema,
179
+ });
180
+ export type WriteDryRunResult = z.infer<typeof writeDryRunResultSchema>;
181
+
182
+ // ─── 승인 요청 ───────────────────────────────────────────────
183
+
184
+ export const approvalStatusSchema = z
185
+ .enum(["PENDING", "EXECUTING", "SUCCEEDED", "FAILED", "UNKNOWN", "REJECTED", "EXPIRED"])
186
+ .describe(
187
+ "승인 요청 상태. `PENDING` 승인 대기 → 승인하면 `EXECUTING`(원 요청 실행 중) → `SUCCEEDED`·`FAILED`(원 요청의 응답 기준), " +
188
+ "거절하면 `REJECTED`, 기한이 지나면 `EXPIRED`. 실행 응답을 받지 못했으면(타임아웃·서버 종료) `UNKNOWN`이다 — " +
189
+ "서버가 감사 로그로 결과를 확정하면 `SUCCEEDED`·`FAILED`로 바뀌고, 확정하지 못하면 `UNKNOWN`에 남는다. " +
190
+ "`UNKNOWN`은 다시 실행하지 않는다(이미 실행됐을 수 있다)",
191
+ );
192
+ export type ApprovalStatus = z.infer<typeof approvalStatusSchema>;
193
+
194
+ export const approvalRequestSchema = z.object({
195
+ approvalId: z.string().describe("승인 요청 ID"),
196
+ status: approvalStatusSchema,
197
+ operationId: z.string().describe("보류된 오퍼레이션 ID"),
198
+ method: z.string().describe("HTTP 메서드"),
199
+ path: z.string().describe("요청 경로와 쿼리"),
200
+ body: z.unknown().describe("요청 본문. 승인하면 이 본문 그대로 실행한다. 없으면 null"),
201
+ idempotencyKey: z.string().nullable().describe("원 요청의 멱등키"),
202
+ reason: z.string().describe("승인이 필요한 이유"),
203
+ actor: auditActorSchema.describe("요청한 행위자"),
204
+ preview: writePreviewSchema.nullable().describe("요청 시점에 서버가 계산한 영향 미리보기"),
205
+ createdAt: z.string().describe("요청 일시 (ISO 8601)"),
206
+ expiresAt: z.string().describe("승인 기한 (ISO 8601). 지나면 `EXPIRED`가 된다"),
207
+ decidedAt: z.string().nullable().describe("승인·거절 일시"),
208
+ decidedBy: z
209
+ .object({ id: z.string(), name: z.string().nullable() })
210
+ .nullable()
211
+ .describe("승인·거절한 콘솔 사용자"),
212
+ decisionNote: z.string().nullable().describe("승인·거절 메모"),
213
+ executedAt: z.string().nullable().describe("원 요청 실행을 마친 일시"),
214
+ result: z
215
+ .object({
216
+ statusCode: z.number().int().describe("원 요청의 응답 상태 코드"),
217
+ data: z.unknown().describe("성공 응답의 `data` (큰 응답은 잘린다)"),
218
+ error: z
219
+ .object({ code: z.string(), message: z.string() })
220
+ .nullable()
221
+ .describe("실패 응답의 `error` 요약"),
222
+ })
223
+ .nullable()
224
+ .describe(
225
+ "실행 결과. `SUCCEEDED`·`FAILED`·`UNKNOWN`에서 값이 있다. 감사 로그로 확정한 결과는 `data`가 null이다",
226
+ ),
227
+ approvalUrl: z
228
+ .string()
229
+ .nullable()
230
+ .describe("셀러 콘솔의 승인 화면 주소. 이 배포의 콘솔 주소를 알 수 없으면 null"),
231
+ });
232
+ export type ApprovalRequest = z.infer<typeof approvalRequestSchema>;
233
+
234
+ export const approvalListQuerySchema = z.object({
235
+ status: commaList(approvalStatusSchema)
236
+ .optional()
237
+ .describe("상태 필터. 여러 개는 쉼표로 구분한다 (예: `PENDING,EXECUTING`)"),
238
+ cursor: z.string().optional().describe("이전 응답의 `nextCursor`. 생략하면 가장 최신부터"),
239
+ limit: z.coerce.number().int().min(1).max(100).optional().describe("최대 건수 (1~100, 기본 50)"),
240
+ });
241
+ export type ApprovalListParams = z.infer<typeof approvalListQuerySchema>;
242
+ export type ApprovalListOptions = Omit<ApprovalListParams, "status"> & {
243
+ status?: ApprovalStatus | ApprovalStatus[];
244
+ };
245
+
246
+ export const approvalPageSchema = z.object({
247
+ items: z.array(approvalRequestSchema),
248
+ nextCursor: z.string().nullable().describe("다음 페이지 커서. 마지막 페이지면 null"),
249
+ });
250
+ export type ApprovalPage = z.infer<typeof approvalPageSchema>;
251
+
252
+ export const approvalDecisionRequestSchema = z.object({
253
+ note: z.string().trim().max(500).optional().describe("승인·거절 메모 (최대 500자)"),
254
+ });
255
+ export type ApprovalDecisionRequest = z.infer<typeof approvalDecisionRequestSchema>;
@@ -65,6 +65,12 @@ export const apiTokenSchema = z.object({
65
65
  createdAt: z.string(),
66
66
  expiresAt: z.string().nullable(),
67
67
  lastUsedAt: z.string().nullable(),
68
+ agent: z
69
+ .boolean()
70
+ .default(false)
71
+ .describe(
72
+ "AI 에이전트(MCP)용 토큰인가. true면 이 토큰의 쓰기는 행위자 `AGENT`로 기록되고 에이전트 쓰기 정책(승인 필요·거부)을 따른다",
73
+ ),
68
74
  });
69
75
  export type ApiToken = z.infer<typeof apiTokenSchema>;
70
76
 
@@ -77,5 +83,7 @@ export const apiTokenCreateRequestSchema = z.object({
77
83
  scopes: z.array(z.string()).min(1),
78
84
  /** 일 단위 만료. null = 무기한, 생략 = 90일 */
79
85
  expiresInDays: z.number().int().nullable().optional(),
86
+ /** AI 에이전트(MCP)용 토큰. 생략 = false. 발급 뒤에는 바꿀 수 없다 */
87
+ agent: z.boolean().optional(),
80
88
  });
81
89
  export type ApiTokenCreateRequest = z.infer<typeof apiTokenCreateRequestSchema>;
@@ -14,7 +14,7 @@ export const scopeAccessSchema = z
14
14
  .describe("접근 수준. `r`=읽기, `rw`=읽기+쓰기(r을 함의)");
15
15
  export type ScopeAccess = z.infer<typeof scopeAccessSchema>;
16
16
 
17
- /** 리소스별로 부여 가능한 접근 수준. settlement·analytics는 쓰기 API가 없어 `r`만 존재한다 */
17
+ /** 리소스별로 부여 가능한 접근 수준. settlement·analytics·audit는 쓰기 API가 없어 `r`만 존재한다 */
18
18
  export const STORE_SCOPE_RESOURCES = {
19
19
  product: ["r", "rw"],
20
20
  category: ["r", "rw"],
@@ -28,6 +28,7 @@ export const STORE_SCOPE_RESOURCES = {
28
28
  store: ["r", "rw"],
29
29
  member: ["r", "rw"],
30
30
  customer: ["r", "rw"],
31
+ audit: ["r"],
31
32
  } as const satisfies Record<string, readonly ScopeAccess[]>;
32
33
 
33
34
  export type StoreScopeResource = keyof typeof STORE_SCOPE_RESOURCES;
@@ -63,6 +64,7 @@ export const STORE_ROLE_SCOPES = {
63
64
  "store:rw",
64
65
  "member:rw",
65
66
  "customer:rw",
67
+ "audit:r",
66
68
  ],
67
69
  ADMIN: [
68
70
  "product:rw",
@@ -76,6 +78,7 @@ export const STORE_ROLE_SCOPES = {
76
78
  "store:rw",
77
79
  "member:rw",
78
80
  "customer:rw",
81
+ "audit:r",
79
82
  ],
80
83
  STAFF: [
81
84
  "product:rw",
@@ -0,0 +1,74 @@
1
+ import { z } from "zod";
2
+
3
+ /**
4
+ * MCP 도구 호출 계측 (`POST /v1/telemetry/mcp`, 이슈 #34).
5
+ *
6
+ * `@sayren/mcp`가 `verify_storefront` 같은 도구를 돌린 뒤 결과 요약을 보낸다. 목적은 하나다 —
7
+ * AI가 만든 스토어프론트가 **처음에** 규칙을 통과하는지, 통과하지 못하면 어떤 규칙에서 막히는지를
8
+ * 세는 것이다. 그 숫자가 규칙과 안내를 고치는 근거가 된다.
9
+ *
10
+ * **보내지 않는 것**: 파일 경로·소스 코드·위반 상세(`detail`)·토큰·사람 식별자. 규칙 id와 개수뿐이다.
11
+ * 테넌트는 요청 토큰이 정한다(본문에 스토어 id가 없다). 옵트아웃은 클라이언트의 `SAYREN_TELEMETRY=0`이다.
12
+ *
13
+ * 알 수 없는 키는 저장하지 않고 버린다(`.strict()`를 쓰지 않는다) — 새 버전 클라이언트가 필드를
14
+ * 하나 더 실었다고 계측 전체가 400으로 날아가면 그 버전의 숫자가 통째로 빈다.
15
+ */
16
+
17
+ /** 규칙 하나의 검사 결과. `ruleId`는 늘어나므로 enum이 아니라 형식만 좁힌다 */
18
+ export const mcpRuleResultSchema = z.object({
19
+ ruleId: z
20
+ .string()
21
+ .min(1)
22
+ .max(64)
23
+ .regex(/^[a-z0-9][a-z0-9-]*$/, "규칙 id는 소문자·숫자·하이픈입니다")
24
+ .describe("검사한 규칙 id (예: `payment-popup-prepare`)"),
25
+ status: z.enum(["pass", "violation"]).describe("통과했는가"),
26
+ count: z.number().int().min(0).max(10_000).describe("이 규칙으로 잡힌 위반 수. 통과면 0"),
27
+ });
28
+ export type McpRuleResult = z.infer<typeof mcpRuleResultSchema>;
29
+
30
+ /**
31
+ * 한 번에 실을 수 있는 규칙 결과 수 — 규칙 수(현재 16개)의 두 배까지다.
32
+ *
33
+ * 규칙 수 수준으로 좁게 둔다. 이 배열이 그대로 `mcp_tool_events.results` jsonb가 되므로 상한이
34
+ * 넉넉하면 한 행의 크기가 그만큼 커지고, 집계가 그 jsonb를 펼친다.
35
+ */
36
+ export const MCP_TELEMETRY_MAX_RESULTS = 32;
37
+
38
+ export const mcpToolEventSchema = z.object({
39
+ tool: z
40
+ .string()
41
+ .regex(/^[a-z][a-z0-9_]{0,39}$/, "도구 이름 형식이 올바르지 않습니다")
42
+ .describe("도구 이름 (예: `verify_storefront`). CLI가 부른 검사는 `create`"),
43
+ clientVersion: z
44
+ .string()
45
+ .max(40)
46
+ .regex(/^[\w.+-]+$/, "버전 형식이 올바르지 않습니다")
47
+ .optional()
48
+ .describe("`@sayren/mcp` 버전. 버전별로 첫 통과율이 나아졌는지 본다"),
49
+ sessionId: z
50
+ .string()
51
+ .min(8)
52
+ .max(64)
53
+ .regex(/^[A-Za-z0-9_-]+$/, "세션 id 형식이 올바르지 않습니다")
54
+ .describe("클라이언트 프로세스당 랜덤 값. 사람·기기를 식별하지 않는다"),
55
+ attempt: z
56
+ .number()
57
+ .int()
58
+ .min(1)
59
+ .max(1_000)
60
+ .describe("이 세션 안에서 같은 도구를 부른 순번(1부터)"),
61
+ durationMs: z.number().int().min(0).max(3_600_000).optional().describe("도구 실행 시간(ms)"),
62
+ ok: z.boolean().describe("위반이 없었는가"),
63
+ checkedFiles: z.number().int().min(0).max(100_000).describe("검사한 소스 파일 수"),
64
+ results: z
65
+ .array(mcpRuleResultSchema)
66
+ .max(MCP_TELEMETRY_MAX_RESULTS)
67
+ // 규칙 하나당 한 줄이다. 같은 id를 여러 줄로 실으면 집계가 한 스토어의 한 규칙을 몇 번 세야
68
+ // 하는지 정할 수 없고, 상한만큼 같은 규칙을 반복해 보내는 것이 저장을 부풀리는 길이 된다.
69
+ .refine((results) => new Set(results.map((result) => result.ruleId)).size === results.length, {
70
+ message: "같은 규칙 id를 두 번 실을 수 없습니다",
71
+ })
72
+ .describe("규칙별 통과·위반. 규칙 id는 중복될 수 없고 파일 경로와 위반 상세는 싣지 않는다"),
73
+ });
74
+ export type McpToolEvent = z.infer<typeof mcpToolEventSchema>;