@eliceio/cdk-cli 1.7.1-entryqa.1 → 1.7.2-sharedqa.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.
@@ -61,7 +61,7 @@ export declare function createLearnerUploadUrl(body: unknown, opts: {
61
61
  now?: number;
62
62
  }): Promise<LearnerUploadUrlResult>;
63
63
  /**
64
- * 콘텐츠 서버 `PUT /__ecdk/blob/learners/…`: 발급한 주소만, 알린 크기까지 받아 `.ecdk/learners/…`에 둔다.
64
+ * 콘텐츠 서버 `PUT /__ecdk/blob/learners/…` · `/__ecdk/blob/learner-shares/…`(공유 파일, dev/learner-shares.ts): 발급한 주소만, 알린 크기까지 받아 `.ecdk/learners/…`에 둔다.
65
65
  * Azure 블록 업로드(`comp=block` · `comp=blocklist`, SDK가 쓰는 방식)와 PUT 한 번 둘 다 받는다.
66
66
  * 처리했으면 true, 이 경로가 아니면 false
67
67
  */
@@ -4,6 +4,7 @@ import { mkdir, writeFile, rename, stat, rm } from 'node:fs/promises';
4
4
  import { join, dirname } from 'node:path';
5
5
  import { pipeline } from 'node:stream/promises';
6
6
  import { DEV_BLOB_PREFIX } from './assets.js';
7
+ import { SHARED_STORAGE_KEY, LEARNER_SHARES_DIR } from './learner-shares.js';
7
8
 
8
9
  /**
9
10
  * 학생 파일(엔트리 AI 학습 데이터 · 모델) 올리기 · 보기 흉내 (dev 전용). elice-material 명세 기준:
@@ -161,15 +162,17 @@ async function readBody(req, limit) {
161
162
  /** `<Latest>…</Latest>` 등 블록 목록 XML의 블록 id들 (Azure Put Block List) */
162
163
  const blockListIds = xml => [...xml.matchAll(/<(?:Latest|Committed|Uncommitted)>([^<]*)<\/(?:Latest|Committed|Uncommitted)>/g)].map(m => m[1] ?? '');
163
164
  /**
164
- * 콘텐츠 서버 `PUT /__ecdk/blob/learners/…`: 발급한 주소만, 알린 크기까지 받아 `.ecdk/learners/…`에 둔다.
165
+ * 콘텐츠 서버 `PUT /__ecdk/blob/learners/…` · `/__ecdk/blob/learner-shares/…`(공유 파일, dev/learner-shares.ts): 발급한 주소만, 알린 크기까지 받아 `.ecdk/learners/…`에 둔다.
165
166
  * Azure 블록 업로드(`comp=block` · `comp=blocklist`, SDK가 쓰는 방식)와 PUT 한 번 둘 다 받는다.
166
167
  * 처리했으면 true, 이 경로가 아니면 false
167
168
  */
168
169
  async function handleLearnerBlobPut(req, res, url, opts) {
169
- if (!url.pathname.startsWith(`${DEV_BLOB_PREFIX}learners/`)) return false;
170
+ const shared = url.pathname.startsWith(`${DEV_BLOB_PREFIX}learner-shares/`);
171
+ if (!shared && !url.pathname.startsWith(`${DEV_BLOB_PREFIX}learners/`)) return false;
170
172
  const storageKey = decodeURIComponent(url.pathname.slice(DEV_BLOB_PREFIX.length));
171
173
  const upload = opts.pending.get(storageKey);
172
- if (req.method !== 'PUT' || !upload || !STORAGE_KEY.test(storageKey)) {
174
+ const keyPattern = shared ? SHARED_STORAGE_KEY : STORAGE_KEY;
175
+ if (req.method !== 'PUT' || !upload || !keyPattern.test(storageKey)) {
173
176
  req.resume();
174
177
  res.writeHead(req.method === 'PUT' ? 403 : 405).end();
175
178
  return true;
@@ -213,7 +216,7 @@ async function handleLearnerBlobPut(req, res, url, opts) {
213
216
  });
214
217
  await writeFile(`${file}.part`, content);
215
218
  await rename(`${file}.part`, file);
216
- opts.log?.(`학생 파일을 받았습니다: ${storageKey} (${content.length} bytes) → ${LEARNERS_DIR}/`);
219
+ opts.log?.(`${shared ? '공유 파일' : '학생 파일'}을 받았습니다: ${storageKey} (${content.length} bytes) → ${shared ? LEARNER_SHARES_DIR : LEARNERS_DIR}/`);
217
220
  res.writeHead(201).end();
218
221
  return true;
219
222
  }
@@ -0,0 +1,90 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import type { LearnerUploadRate, PendingLearnerUploads } from './learner-files.js';
3
+ /**
4
+ * 학생 공유 파일(보드 카드에 붙이는 그림 · PDF) 흉내 (dev 전용). elice-material 명세(learner-shares) 기준:
5
+ * 1. SDK `sharedFiles.post` → 흉내 API `POST /storage/upload-url` `{ key: "shared.{ext}", content_length, content_type }`
6
+ * (learn · edit 토큰, 튜터 403 `MATERIAL_READ_ONLY_MODE`) → `{ upload_url, key: "learner-shares/{material}/{account}/{uuid}.{ext}" }`.
7
+ * 검사 순서도 서버와 같게: 종류 → 크기 · content_type → 1분 10번 → 한 사람 50개
8
+ * 2. SDK가 `upload_url`로 Azure 블록 업로드 → 콘텐츠 서버 `/__ecdk/blob/learner-shares/…`가 받아 `.ecdk/learner-shares/…`에 둔다
9
+ * (dev/learner-files.ts `handleLearnerBlobPut`이 같이 받음)
10
+ * 3. 흉내 API `GET /materials/{id}/learner-shares/url` → `{ base_url, key_prefix, expires_at }`. 서명은 자료 폴더
11
+ * `learner-shares/{material}` 하나라 주소가 모두에게 같다. 파일 주소는 base_url + (key에서 key_prefix를 뺀 것).
12
+ * 운영처럼 출처는 콘텐츠 출처라(img-src에 있음) 콘텐츠 서버가 `/s/{exp}.{sig}/learner-shares/…`를 내준다
13
+ * 4. 흉내 API `DELETE /materials/{id}/learner-shares?key=` → 204. 본인 · 교육자(learn) · edit 토큰만, 튜터 403, 없는 파일도 204
14
+ */
15
+ /** 받은 공유 파일을 두는 곳 (프로젝트 기준). `.ecdk/`라 감시 · zip에서 빠진다 */
16
+ export declare const LEARNER_SHARES_DIR = ".ecdk/learner-shares";
17
+ /** 서명 주소 유효 시간 (초): 서버 LEARNER_FILES_URL_TTL_SECONDS와 같은 6시간 */
18
+ export declare const LEARNER_SHARES_URL_TTL_SECONDS: number;
19
+ /** 한 사람 × 자료마다 1분에 발급하는 업로드 주소 수 */
20
+ export declare const LEARNER_SHARE_UPLOADS_PER_MINUTE = 10;
21
+ /** 한 사람 × 자료마다 남길 수 있는 공유 파일 수 */
22
+ export declare const LEARNER_SHARE_MAX_FILES = 50;
23
+ /** 확장자(소문자만) → 받는 Content-Type · 최대 크기. gif · svg · html은 없음 (서버 LEARNER_SHARE_KINDS) */
24
+ export declare const LEARNER_SHARE_KINDS: Readonly<Record<string, {
25
+ type: string;
26
+ maxBytes: number;
27
+ }>>;
28
+ /** 저장 키 `learner-shares/{material}/{account}/{uuid}.{ext}` (서버 LEARNER_SHARE_KEY_REGEX) */
29
+ export declare const SHARED_STORAGE_KEY: RegExp;
30
+ type Failure = {
31
+ ok: false;
32
+ status: number;
33
+ code: string;
34
+ message: string;
35
+ details?: unknown[];
36
+ };
37
+ /**
38
+ * `POST /storage/upload-url`의 `shared.{ext}` 흉내. 권한(learn · edit 토큰, 튜터 403)은 부르는 쪽(mock-api)이 본다.
39
+ * 오류: 모르는 확장자 · 대문자 · gif · svg · html은 400 INVALID_INPUT `unsupported_upload_kind`, 한도 초과
40
+ * MATERIAL_PACKAGE_TOO_LARGE(`max_bytes`), 다른 content_type은 INVALID_INPUT `unsupported_content_type`,
41
+ * 1분 10번 초과 429 MATERIAL_TOO_MANY_LEARNER_UPLOADS(`learner_share_upload_rate_limited`),
42
+ * 50개 409 MATERIAL_TOO_MANY_LEARNER_SHARES(`limit`)
43
+ */
44
+ export declare function createSharedUploadUrl(body: unknown, opts: {
45
+ dir: string;
46
+ materialId: string;
47
+ accountId: number;
48
+ uploadOrigin: string;
49
+ pending: PendingLearnerUploads;
50
+ rate?: LearnerUploadRate;
51
+ now?: number;
52
+ }): Promise<{
53
+ ok: true;
54
+ data: {
55
+ upload_url: string;
56
+ key: string;
57
+ expires_in: number;
58
+ };
59
+ } | Failure>;
60
+ /**
61
+ * `GET /materials/{id}/learner-shares/url`의 응답: 자료 폴더 서명 주소, 파일 key에서 뺄 `key_prefix`, 만료 시각(ISO).
62
+ * @param contentOrigin 서명 경로를 붙일 콘텐츠 출처 (운영처럼 자료의 콘텐츠 출처)
63
+ */
64
+ export declare function learnerSharesUrl(contentOrigin: string, materialId: string, now?: number): {
65
+ base_url: string;
66
+ key_prefix: string;
67
+ expires_at: string;
68
+ };
69
+ /**
70
+ * 콘텐츠 서버 `GET · HEAD /s/{exp}.{sig}/learner-shares/{material}/{account}/{uuid}.{ext}`: 서명이 그 자료 폴더의 것이고
71
+ * 만료 전이면 받은 파일을 내준다 (inline, nosniff, `private, no-cache`). 모양이 틀리면 404, 서명이 틀리면 403.
72
+ * 이 경로가 아니면 false
73
+ */
74
+ export declare function serveLearnerShare(req: IncomingMessage, res: ServerResponse, pathname: string, dir: string): Promise<boolean>;
75
+ /**
76
+ * `DELETE /materials/{id}/learner-shares?key=`의 판정 (서버 순서): 모양이 틀린 key 422 VALIDATION_ERROR → 다른 자료 404
77
+ * RESOURCE_NOT_FOUND → 튜터 403 MATERIAL_READ_ONLY_MODE → 본인도 교육자 · edit도 아니면 403 AUTH_PERMISSION_DENIED →
78
+ * 지움(없어도 204). scope 검사(learn · edit)는 dev 토큰이 둘뿐이라 생략
79
+ */
80
+ export declare function deleteLearnerShare(key: string, claims: {
81
+ material_id: string;
82
+ account_id: number;
83
+ viewer: string;
84
+ scope: string;
85
+ }, materialId: string, dir: string): Promise<{
86
+ ok: true;
87
+ } | Failure>;
88
+ /** "처음 상태로": 받은 공유 파일도 지운다 */
89
+ export declare const removeLearnerShares: (dir: string) => Promise<void>;
90
+ export {};
@@ -0,0 +1,282 @@
1
+ import { randomBytes, timingSafeEqual, randomUUID, createHmac } from 'node:crypto';
2
+ import { createReadStream } from 'node:fs';
3
+ import { stat, unlink, rm, readdir } from 'node:fs/promises';
4
+ import { join } from 'node:path';
5
+ import { pipeline } from 'node:stream/promises';
6
+ import { DEV_BLOB_PREFIX } from './assets.js';
7
+
8
+ /**
9
+ * 학생 공유 파일(보드 카드에 붙이는 그림 · PDF) 흉내 (dev 전용). elice-material 명세(learner-shares) 기준:
10
+ * 1. SDK `sharedFiles.post` → 흉내 API `POST /storage/upload-url` `{ key: "shared.{ext}", content_length, content_type }`
11
+ * (learn · edit 토큰, 튜터 403 `MATERIAL_READ_ONLY_MODE`) → `{ upload_url, key: "learner-shares/{material}/{account}/{uuid}.{ext}" }`.
12
+ * 검사 순서도 서버와 같게: 종류 → 크기 · content_type → 1분 10번 → 한 사람 50개
13
+ * 2. SDK가 `upload_url`로 Azure 블록 업로드 → 콘텐츠 서버 `/__ecdk/blob/learner-shares/…`가 받아 `.ecdk/learner-shares/…`에 둔다
14
+ * (dev/learner-files.ts `handleLearnerBlobPut`이 같이 받음)
15
+ * 3. 흉내 API `GET /materials/{id}/learner-shares/url` → `{ base_url, key_prefix, expires_at }`. 서명은 자료 폴더
16
+ * `learner-shares/{material}` 하나라 주소가 모두에게 같다. 파일 주소는 base_url + (key에서 key_prefix를 뺀 것).
17
+ * 운영처럼 출처는 콘텐츠 출처라(img-src에 있음) 콘텐츠 서버가 `/s/{exp}.{sig}/learner-shares/…`를 내준다
18
+ * 4. 흉내 API `DELETE /materials/{id}/learner-shares?key=` → 204. 본인 · 교육자(learn) · edit 토큰만, 튜터 403, 없는 파일도 204
19
+ */
20
+ /** 받은 공유 파일을 두는 곳 (프로젝트 기준). `.ecdk/`라 감시 · zip에서 빠진다 */
21
+ const LEARNER_SHARES_DIR = '.ecdk/learner-shares';
22
+ /** 서명 주소 유효 시간 (초): 서버 LEARNER_FILES_URL_TTL_SECONDS와 같은 6시간 */
23
+ const LEARNER_SHARES_URL_TTL_SECONDS = 6 * 3600;
24
+ /** 한 사람 × 자료마다 1분에 발급하는 업로드 주소 수 */
25
+ const LEARNER_SHARE_UPLOADS_PER_MINUTE = 10;
26
+ /** 한 사람 × 자료마다 남길 수 있는 공유 파일 수 */
27
+ const LEARNER_SHARE_MAX_FILES = 50;
28
+ const MB = 1024 * 1024;
29
+ /** 확장자(소문자만) → 받는 Content-Type · 최대 크기. gif · svg · html은 없음 (서버 LEARNER_SHARE_KINDS) */
30
+ const LEARNER_SHARE_KINDS = Object.freeze({
31
+ png: {
32
+ type: 'image/png',
33
+ maxBytes: 10 * MB
34
+ },
35
+ jpg: {
36
+ type: 'image/jpeg',
37
+ maxBytes: 10 * MB
38
+ },
39
+ jpeg: {
40
+ type: 'image/jpeg',
41
+ maxBytes: 10 * MB
42
+ },
43
+ webp: {
44
+ type: 'image/webp',
45
+ maxBytes: 10 * MB
46
+ },
47
+ pdf: {
48
+ type: 'application/pdf',
49
+ maxBytes: 20 * MB
50
+ }
51
+ });
52
+ /** 저장 키 `learner-shares/{material}/{account}/{uuid}.{ext}` (서버 LEARNER_SHARE_KEY_REGEX) */
53
+ const SHARED_STORAGE_KEY = /^learner-shares\/([0-9a-f-]{36})\/([0-9]+)\/[0-9a-f-]{36}\.(png|jpg|jpeg|webp|pdf)$/;
54
+ const UPLOAD_URL_EXPIRES_IN = 900;
55
+ const detail = (ctx, msg) => [{
56
+ msg,
57
+ type: 'app_exception_detail',
58
+ ctx
59
+ }];
60
+ /** 그 사람 폴더에 남은 공유 파일 수 (서버는 한도를 넘는 큰 파일을 지우고 셈; dev는 크기 검사 뒤에만 저장하므로 그대로 셈) */
61
+ async function countFiles(dir, materialId, accountId) {
62
+ const names = await readdir(join(dir, LEARNER_SHARES_DIR, materialId, String(accountId))).catch(() => []);
63
+ return names.filter(name => !name.endsWith('.part')).length;
64
+ }
65
+ /**
66
+ * `POST /storage/upload-url`의 `shared.{ext}` 흉내. 권한(learn · edit 토큰, 튜터 403)은 부르는 쪽(mock-api)이 본다.
67
+ * 오류: 모르는 확장자 · 대문자 · gif · svg · html은 400 INVALID_INPUT `unsupported_upload_kind`, 한도 초과
68
+ * MATERIAL_PACKAGE_TOO_LARGE(`max_bytes`), 다른 content_type은 INVALID_INPUT `unsupported_content_type`,
69
+ * 1분 10번 초과 429 MATERIAL_TOO_MANY_LEARNER_UPLOADS(`learner_share_upload_rate_limited`),
70
+ * 50개 409 MATERIAL_TOO_MANY_LEARNER_SHARES(`limit`)
71
+ */
72
+ async function createSharedUploadUrl(body, opts) {
73
+ const b = body && typeof body === 'object' ? body : {};
74
+ const key = typeof b.key === 'string' ? b.key : '';
75
+ const ext = key.slice('shared.'.length);
76
+ const kind = key.startsWith('shared.') ? LEARNER_SHARE_KINDS[ext] : undefined;
77
+ if (!kind) {
78
+ const message = 'key: shared.{png|jpg|jpeg|webp|pdf}';
79
+ return {
80
+ ok: false,
81
+ status: 400,
82
+ code: 'INVALID_INPUT',
83
+ message,
84
+ details: detail({
85
+ field: 'key',
86
+ reason: 'unsupported_upload_kind'
87
+ }, message)
88
+ };
89
+ }
90
+ const length = Number(b.content_length ?? b.contentLength);
91
+ if (!Number.isInteger(length) || length <= 0) return {
92
+ ok: false,
93
+ status: 400,
94
+ code: 'INVALID_INPUT',
95
+ message: 'content_length: 1 byte or more'
96
+ };
97
+ if (length > kind.maxBytes) return {
98
+ ok: false,
99
+ status: 400,
100
+ code: 'MATERIAL_PACKAGE_TOO_LARGE',
101
+ message: `content_length: up to ${kind.maxBytes} bytes (${kind.maxBytes / MB}MB)`,
102
+ details: detail({
103
+ max_bytes: kind.maxBytes
104
+ }, 'too large')
105
+ };
106
+ const type = b.content_type ?? b.contentType;
107
+ if (type != null && type !== kind.type) {
108
+ const message = `content_type: ${kind.type} for .${ext}`;
109
+ return {
110
+ ok: false,
111
+ status: 400,
112
+ code: 'INVALID_INPUT',
113
+ message,
114
+ details: detail({
115
+ field: 'content_type',
116
+ reason: 'unsupported_content_type'
117
+ }, message)
118
+ };
119
+ }
120
+ if (opts.rate) {
121
+ const now = opts.now ?? Date.now();
122
+ const rateKey = `shared:${opts.materialId}/${opts.accountId}`;
123
+ const recent = (opts.rate.get(rateKey) ?? []).filter(t => t > now - 60_000);
124
+ if (recent.length >= LEARNER_SHARE_UPLOADS_PER_MINUTE) {
125
+ opts.rate.set(rateKey, recent);
126
+ const message = `up to ${LEARNER_SHARE_UPLOADS_PER_MINUTE} shared file uploads a minute per material`;
127
+ return {
128
+ ok: false,
129
+ status: 429,
130
+ code: 'MATERIAL_TOO_MANY_LEARNER_UPLOADS',
131
+ message,
132
+ details: detail({
133
+ reason: 'learner_share_upload_rate_limited'
134
+ }, message)
135
+ };
136
+ }
137
+ opts.rate.set(rateKey, [...recent, now]);
138
+ }
139
+ if ((await countFiles(opts.dir, opts.materialId, opts.accountId)) >= LEARNER_SHARE_MAX_FILES) {
140
+ const message = `up to ${LEARNER_SHARE_MAX_FILES} shared files per learner and material`;
141
+ return {
142
+ ok: false,
143
+ status: 409,
144
+ code: 'MATERIAL_TOO_MANY_LEARNER_SHARES',
145
+ message,
146
+ details: detail({
147
+ limit: LEARNER_SHARE_MAX_FILES
148
+ }, message)
149
+ };
150
+ }
151
+ const storageKey = `learner-shares/${opts.materialId}/${opts.accountId}/${randomUUID()}.${ext}`;
152
+ opts.pending.set(storageKey, {
153
+ allowed: length,
154
+ blocks: new Map()
155
+ });
156
+ return {
157
+ ok: true,
158
+ data: {
159
+ upload_url: `${opts.uploadOrigin}${DEV_BLOB_PREFIX}${storageKey}?sig=dev`,
160
+ key: storageKey,
161
+ expires_in: UPLOAD_URL_EXPIRES_IN
162
+ }
163
+ };
164
+ }
165
+ /** dev 서명 열쇠 (실행마다 새로). 서명 · 만료를 확인해 다른 자료 · 지난 주소는 403 */
166
+ const SIGNING_KEY = randomBytes(32);
167
+ const signFolder = (prefix, exp) => createHmac('sha256', SIGNING_KEY).update(`${exp}:${prefix}`).digest('base64url').slice(0, 22);
168
+ /**
169
+ * `GET /materials/{id}/learner-shares/url`의 응답: 자료 폴더 서명 주소, 파일 key에서 뺄 `key_prefix`, 만료 시각(ISO).
170
+ * @param contentOrigin 서명 경로를 붙일 콘텐츠 출처 (운영처럼 자료의 콘텐츠 출처)
171
+ */
172
+ function learnerSharesUrl(contentOrigin, materialId, now = Date.now()) {
173
+ const exp = Math.floor(now / 1000) + LEARNER_SHARES_URL_TTL_SECONDS;
174
+ const prefix = `learner-shares/${materialId}`;
175
+ return {
176
+ base_url: `${contentOrigin}/s/${exp}.${signFolder(prefix, exp)}/${prefix}/`,
177
+ key_prefix: `${prefix}/`,
178
+ expires_at: new Date(exp * 1000).toISOString()
179
+ };
180
+ }
181
+ /**
182
+ * 콘텐츠 서버 `GET · HEAD /s/{exp}.{sig}/learner-shares/{material}/{account}/{uuid}.{ext}`: 서명이 그 자료 폴더의 것이고
183
+ * 만료 전이면 받은 파일을 내준다 (inline, nosniff, `private, no-cache`). 모양이 틀리면 404, 서명이 틀리면 403.
184
+ * 이 경로가 아니면 false
185
+ */
186
+ async function serveLearnerShare(req, res, pathname, dir) {
187
+ const m = /^\/s\/(\d+)\.([A-Za-z0-9_-]+)\/(learner-shares\/.*)$/.exec(pathname);
188
+ if (!m) return false;
189
+ const [, expText = '', sig = '', storageKeyRaw = ''] = m;
190
+ const storageKey = decodeURIComponent(storageKeyRaw);
191
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
192
+ res.writeHead(405).end();
193
+ return true;
194
+ }
195
+ const key = SHARED_STORAGE_KEY.exec(storageKey);
196
+ if (!key) {
197
+ res.writeHead(404).end('not found');
198
+ return true;
199
+ }
200
+ const exp = Number(expText);
201
+ const expected = signFolder(`learner-shares/${key[1]}`, exp);
202
+ const valid = exp * 1000 > Date.now() && expected.length === sig.length && timingSafeEqual(Buffer.from(expected), Buffer.from(sig));
203
+ if (!valid) {
204
+ res.writeHead(403).end('invalid signature');
205
+ return true;
206
+ }
207
+ const file = join(dir, '.ecdk', storageKey);
208
+ const info = await stat(file).catch(() => null);
209
+ if (!info?.isFile()) {
210
+ res.writeHead(404).end('not found');
211
+ return true;
212
+ }
213
+ res.writeHead(200, {
214
+ 'Content-Type': LEARNER_SHARE_KINDS[key[3] ?? '']?.type ?? 'application/octet-stream',
215
+ 'Content-Length': String(info.size),
216
+ 'Content-Disposition': 'inline',
217
+ 'Cache-Control': 'private, no-cache'
218
+ });
219
+ if (req.method === 'HEAD') {
220
+ res.end();
221
+ return true;
222
+ }
223
+ await pipeline(createReadStream(file), res).catch(() => undefined);
224
+ return true;
225
+ }
226
+ /**
227
+ * `DELETE /materials/{id}/learner-shares?key=`의 판정 (서버 순서): 모양이 틀린 key 422 VALIDATION_ERROR → 다른 자료 404
228
+ * RESOURCE_NOT_FOUND → 튜터 403 MATERIAL_READ_ONLY_MODE → 본인도 교육자 · edit도 아니면 403 AUTH_PERMISSION_DENIED →
229
+ * 지움(없어도 204). scope 검사(learn · edit)는 dev 토큰이 둘뿐이라 생략
230
+ */
231
+ async function deleteLearnerShare(key, claims, materialId, dir) {
232
+ const match = SHARED_STORAGE_KEY.exec(key);
233
+ if (!match) return {
234
+ ok: false,
235
+ status: 422,
236
+ code: 'VALIDATION_ERROR',
237
+ message: `invalid key "${key}"`
238
+ };
239
+ if (match[1] !== materialId) return {
240
+ ok: false,
241
+ status: 404,
242
+ code: 'RESOURCE_NOT_FOUND',
243
+ message: 'shared file of another material',
244
+ details: detail({
245
+ resource_type: 'learner_share',
246
+ requested_id: key
247
+ }, 'not found')
248
+ };
249
+ if (claims.viewer === 'tutor') return {
250
+ ok: false,
251
+ status: 403,
252
+ code: 'MATERIAL_READ_ONLY_MODE',
253
+ message: 'tutor is read-only',
254
+ details: detail({
255
+ reason: 'tutor_read_only'
256
+ }, 'tutor is read-only')
257
+ };
258
+ const isOwner = Number(match[2]) === claims.account_id;
259
+ const isModerator = claims.scope === 'edit' || claims.viewer === 'instructor';
260
+ if (!isOwner && !isModerator) return {
261
+ ok: false,
262
+ status: 403,
263
+ code: 'AUTH_PERMISSION_DENIED',
264
+ message: "another learner's shared file",
265
+ details: detail({
266
+ resource: 'learner_share',
267
+ resource_id: key,
268
+ required_role: 'owner'
269
+ }, 'denied')
270
+ };
271
+ await unlink(join(dir, '.ecdk', key)).catch(() => undefined);
272
+ return {
273
+ ok: true
274
+ };
275
+ }
276
+ /** "처음 상태로": 받은 공유 파일도 지운다 */
277
+ const removeLearnerShares = dir => rm(join(dir, LEARNER_SHARES_DIR), {
278
+ recursive: true,
279
+ force: true
280
+ });
281
+
282
+ export { LEARNER_SHARES_DIR, LEARNER_SHARES_URL_TTL_SECONDS, LEARNER_SHARE_KINDS, LEARNER_SHARE_MAX_FILES, LEARNER_SHARE_UPLOADS_PER_MINUTE, SHARED_STORAGE_KEY, createSharedUploadUrl, deleteLearnerShare, learnerSharesUrl, removeLearnerShares, serveLearnerShare };
@@ -137,6 +137,34 @@ export interface MockApiOptions {
137
137
  }>;
138
138
  /** `GET /materials/{id}/learner-files/url` (dev/learner-files.ts `learnerFolderUrl`) */
139
139
  learnerFolderUrl?: (materialId: string, accountId: number) => unknown;
140
+ /** `POST /storage/upload-url`의 `shared.{ext}` (dev/learner-shares.ts `createSharedUploadUrl`) */
141
+ createSharedUploadUrl?: (body: unknown, materialId: string, accountId: number) => Promise<{
142
+ ok: true;
143
+ data: unknown;
144
+ } | {
145
+ ok: false;
146
+ status: number;
147
+ code: string;
148
+ message: string;
149
+ details?: unknown[];
150
+ }>;
151
+ /** `GET /materials/{id}/learner-shares/url` (dev/learner-shares.ts `learnerSharesUrl`) */
152
+ learnerSharesUrl?: (materialId: string) => unknown;
153
+ /** `DELETE /materials/{id}/learner-shares?key=` (dev/learner-shares.ts `deleteLearnerShare`) */
154
+ deleteLearnerShare?: (key: string, claims: {
155
+ material_id: string;
156
+ account_id: number;
157
+ viewer: string;
158
+ scope: string;
159
+ }, materialId: string) => Promise<{
160
+ ok: true;
161
+ } | {
162
+ ok: false;
163
+ status: number;
164
+ code: string;
165
+ message: string;
166
+ details?: unknown[];
167
+ }>;
140
168
  onEvent?: (message: string) => void;
141
169
  }
142
170
  /** `/api` 아래 요청을 처리한다 */
@@ -233,6 +233,20 @@ async function handleMockApi(req, res, path, opts) {
233
233
  log(`학생 파일 업로드 주소를 발급했습니다 (${key})`);
234
234
  return send(res, 200, r.data);
235
235
  }
236
+ // 공유 파일(key `shared.{ext}`, SDK sharedFiles.post): learn · edit 토큰, 튜터 403, 계정 · 자료는 토큰에서
237
+ if (typeof key === 'string' && key.startsWith('shared.')) {
238
+ if (claims.viewer === 'tutor') return fail(res, 403, 'MATERIAL_READ_ONLY_MODE', 'tutor is read-only', [{
239
+ type: 'app_exception_detail',
240
+ ctx: {
241
+ reason: 'tutor_read_only'
242
+ }
243
+ }]);
244
+ if (!opts.createSharedUploadUrl) return fail(res, 404, 'RESOURCE_NOT_FOUND', 'uploads are off (dev)');
245
+ const r = await opts.createSharedUploadUrl(json, claims.material_id, claims.account_id);
246
+ if (!r.ok) return fail(res, r.status, r.code, r.message, r.details);
247
+ log(`공유 파일 업로드 주소를 발급했습니다 (${key}, ${claims.viewer} ${claims.account_id})`);
248
+ return send(res, 200, r.data);
249
+ }
236
250
  if (claims.scope !== 'edit') return fail(res, 403, 'AUTH_PERMISSION_DENIED', 'upload only with an edit token');
237
251
  if (!opts.createUploadUrl) return fail(res, 404, 'RESOURCE_NOT_FOUND', 'uploads are off (dev)');
238
252
  const r = opts.createUploadUrl(json, claims.material_id);
@@ -244,7 +258,7 @@ async function handleMockApi(req, res, path, opts) {
244
258
  if (await handlePublicKvApi(req, res, path, {
245
259
  store: state.publicKv,
246
260
  kv: state.kv})) return;
247
- const m = path.match(/^\/materials\/([0-9a-f-]{36})(\/me|\/draft|\/submissions|\/submissions\/me|\/kv\/account|\/learner-files\/url)?$/);
261
+ const m = path.match(/^\/materials\/([0-9a-f-]{36})(\/me|\/draft|\/submissions|\/submissions\/me|\/kv\/account|\/learner-files\/url|\/learner-shares\/url|\/learner-shares)?$/);
248
262
  if (!m) return fail(res, 404, 'RESOURCE_NOT_FOUND', `no route: ${method} ${path}`);
249
263
  const claims = readClaims(req);
250
264
  if (!claims) return fail(res, 401, 'AUTHENTICATION_INVALID', 'missing or expired token (dev)');
@@ -516,6 +530,23 @@ async function handleMockApi(req, res, path, opts) {
516
530
  if (!opts.learnerFolderUrl) return fail(res, 404, 'RESOURCE_NOT_FOUND', 'learner files are off (dev)');
517
531
  return send(res, 200, opts.learnerFolderUrl(claims.material_id, subject));
518
532
  }
533
+ // 공유 파일 서명 주소: 자료 하나에 하나 (모두에게 같은 주소, 튜터도 읽음)
534
+ if (sub === '/learner-shares/url') {
535
+ if (method !== 'GET') return fail(res, 405, 'RESOURCE_NOT_FOUND', `${method} ${path}`);
536
+ if (!opts.learnerSharesUrl) return fail(res, 404, 'RESOURCE_NOT_FOUND', 'shared files are off (dev)');
537
+ return send(res, 200, opts.learnerSharesUrl(claims.material_id));
538
+ }
539
+ // 공유 파일 지우기: 본인 · 교육자 · edit 토큰 (dev/learner-shares.ts deleteLearnerShare)
540
+ if (sub === '/learner-shares') {
541
+ if (method !== 'DELETE') return fail(res, 405, 'RESOURCE_NOT_FOUND', `${method} ${path}`);
542
+ if (!opts.deleteLearnerShare) return fail(res, 404, 'RESOURCE_NOT_FOUND', 'shared files are off (dev)');
543
+ const shareKey = new URL(req.url ?? '', 'http://x').searchParams.get('key') ?? '';
544
+ const r = await opts.deleteLearnerShare(shareKey, claims, claims.material_id);
545
+ if (!r.ok) return fail(res, r.status, r.code, r.message, r.details);
546
+ log(`공유 파일을 지웠습니다 (${shareKey}, ${claims.viewer} ${claims.account_id})`);
547
+ res.writeHead(204).end();
548
+ return;
549
+ }
519
550
  // kvstore: 보는 사람(튜터는 보고 있는 학생) · 이 자료. 맨 위 key마다 값 하나
520
551
  if (sub === '/kv/account') {
521
552
  const doc = state.kv.get(subject) ?? {};
@@ -48,5 +48,8 @@ export declare const devOnlyConnectSrc: (contentOrigin: string) => string[];
48
48
  * - 학생 파일 흉내 (dev/learner-files.ts): upload-url `learner/…`(learn 토큰, 학생 × 자료 1분 30번) → 같은 PUT 경로
49
49
  * (/__ecdk/blob/learners/…, Azure 블록 업로드도 받음) → .ecdk/learners/, learner-files/url의 폴더 서명
50
50
  * 주소(흉내 API /api/s/{exp}.{sig}/learners/{material}/{account}/) 아래 파일을 내준다
51
+ * - 공유 파일 흉내 (dev/learner-shares.ts): upload-url `shared.{ext}`(learn · edit 토큰, 1분 10번, 한 사람 50개) → 같은 PUT
52
+ * 경로(/__ecdk/blob/learner-shares/…) → .ecdk/learner-shares/, learner-shares/url의 자료 폴더 서명 주소(콘텐츠 출처
53
+ * /s/{exp}.{sig}/learner-shares/{material}/) 아래 파일을 내준다. DELETE는 본인 · 교육자 · edit
51
54
  */
52
55
  export declare function startDevServer(opts: DevServerOptions): Promise<DevServer>;
package/es/dev/server.js CHANGED
@@ -17,6 +17,7 @@ import { isCompletionPolicy, recommendedCompletionPolicy } from './grading.js';
17
17
  import { hostPage } from './host-page.js';
18
18
  import { closePublicKv } from './kv-public-mock.js';
19
19
  import { handleLearnerBlobPut, serveLearnerFile, learnerFolderUrl, createLearnerUploadUrl, removeLearnerFiles } from './learner-files.js';
20
+ import { serveLearnerShare, deleteLearnerShare, learnerSharesUrl, createSharedUploadUrl, removeLearnerShares } from './learner-shares.js';
20
21
  import { DEV_MATERIAL_ID, handleMockApi, isTokenScenario, issueToken, createState } from './mock-api.js';
21
22
 
22
23
  /** 운영 콘텐츠 경로(/s/{exp}.{sig}/materials/{id}/{draft}/…)와 같은 모양. SDK가 여기서 자료 id를 읽는다 */
@@ -71,6 +72,9 @@ const listen = (server, port) => new Promise((ok, fail) => {
71
72
  * - 학생 파일 흉내 (dev/learner-files.ts): upload-url `learner/…`(learn 토큰, 학생 × 자료 1분 30번) → 같은 PUT 경로
72
73
  * (/__ecdk/blob/learners/…, Azure 블록 업로드도 받음) → .ecdk/learners/, learner-files/url의 폴더 서명
73
74
  * 주소(흉내 API /api/s/{exp}.{sig}/learners/{material}/{account}/) 아래 파일을 내준다
75
+ * - 공유 파일 흉내 (dev/learner-shares.ts): upload-url `shared.{ext}`(learn · edit 토큰, 1분 10번, 한 사람 50개) → 같은 PUT
76
+ * 경로(/__ecdk/blob/learner-shares/…) → .ecdk/learner-shares/, learner-shares/url의 자료 폴더 서명 주소(콘텐츠 출처
77
+ * /s/{exp}.{sig}/learner-shares/{material}/) 아래 파일을 내준다. DELETE는 본인 · 교육자 · edit
74
78
  */
75
79
  async function startDevServer(opts) {
76
80
  const dir = resolve(opts.dir);
@@ -177,6 +181,12 @@ async function startDevServer(opts) {
177
181
  });
178
182
  return;
179
183
  }
184
+ // 공유 파일 (sharedFiles base_url + {account}/{uuid}.{ext}): 운영처럼 콘텐츠 출처의 자료 폴더 서명 경로
185
+ if (url.pathname.startsWith('/s/') && url.pathname.includes('/learner-shares/')) {
186
+ for (const [k, v] of Object.entries(headers)) res.setHeader(k, v);
187
+ res.setHeader('Cache-Control', 'private, no-cache');
188
+ if (await serveLearnerShare(req, res, url.pathname, dir)) return;
189
+ }
180
190
  if (!url.pathname.startsWith(CONTENT_PREFIX)) {
181
191
  res.writeHead(404, headers).end('not found');
182
192
  return;
@@ -244,6 +254,16 @@ async function startDevServer(opts) {
244
254
  rate: learnerUploadRate
245
255
  }),
246
256
  learnerFolderUrl: (materialId, accountId) => learnerFolderUrl(`${hostOrigin}/api`, materialId, accountId),
257
+ createSharedUploadUrl: (body, materialId, accountId) => createSharedUploadUrl(body, {
258
+ dir,
259
+ materialId,
260
+ accountId,
261
+ uploadOrigin: contentOrigin,
262
+ pending: pendingLearnerUploads,
263
+ rate: learnerUploadRate
264
+ }),
265
+ learnerSharesUrl: materialId => learnerSharesUrl(contentOrigin, materialId),
266
+ deleteLearnerShare: (key, claims, materialId) => deleteLearnerShare(key, claims, materialId, dir),
247
267
  onEvent: m => log(`[api] ${m}`)
248
268
  });
249
269
  return;
@@ -360,8 +380,9 @@ async function startDevServer(opts) {
360
380
  });
361
381
  await removeAssets(dir);
362
382
  await removeLearnerFiles(dir);
383
+ await removeLearnerShares(dir);
363
384
  learnerUploadRate.clear();
364
- log(`[api] 저장 내용(${SETTINGS_DATA_FILE}) · 올린 파일 · 학생 파일 · 제출 기록 · 보드를 지웠습니다`);
385
+ log(`[api] 저장 내용(${SETTINGS_DATA_FILE}) · 올린 파일 · 학생 파일 · 공유 파일 · 제출 기록 · 보드를 지웠습니다`);
365
386
  res.writeHead(204).end();
366
387
  return;
367
388
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eliceio/cdk-cli",
3
- "version": "1.7.1-entryqa.1",
3
+ "version": "1.7.2-sharedqa.0",
4
4
  "description": "교육자용 Custom HTML 콘텐츠 CLI",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
@@ -47,7 +47,7 @@
47
47
  "rollup": "4.62.4",
48
48
  "tslib": "2.8.1",
49
49
  "typescript": "6.0.3",
50
- "@eliceio/cdk": "^1.7.1-entryqa.1"
50
+ "@eliceio/cdk": "^1.7.2-sharedqa.0"
51
51
  },
52
52
  "scripts": {
53
53
  "prebuild": "del-cli \"buildcache/*\" \"es/*\"",
@@ -89,6 +89,7 @@ app.useSave({ getContent: () => app.content, getGrading: () => grading.getGradin
89
89
  - Saving on the edit screen (`useSave`) **saves to the material's draft** (SDK `saveSettings`, with the edit token LXP opens the edit screen with). LXP's previews show the draft right away; learners see it only after the person presses '수업 자료에 반영' at the top of the LXP edit page, which publishes the draft as a new version. In `ecdk dev` there is no publish step, so the student view changes at once. The kit shows the result and the failure messages (the upload is not saved yet, the upload is still processing, session expired, and for a server 422 `VALIDATION_ERROR` a message by the server's error type: "배점 합계는 100점 이상이어야 합니다." · "문항별 정답과 점수의 개수가 맞지 않아요." · "정답 형식이 올바르지 않아요.", otherwise "저장할 내용의 형식이 올바르지 않아요."), so the screen code does not announce "saved" itself. A submission the server rejects with 422 (the saved grading and the answer shape do not match, for example `partial_pattern` with a string answer) shows "이 자료의 채점 설정과 답 모양이 맞지 않아 제출하지 못했어요. 교육자에게 알려 주세요." in every template.
90
90
  - Materials without a submission do not call `useSubmit` (only `on_access` fits them in LXP).
91
91
  - **No personal data in what you submit, save, upload or send to AI.** `getAnswer`, `useSave` content, `assets` uploads and `mlapi` bodies never hold a learner's name, phone number, email, address, date of birth, student number, resident registration number, bank account, face photo or location, and the screens have no input for them. Submissions stay on the server for instructors and operators, the content reaches every viewer, and AI calls go to an outside model. To tell learners apart use `app.account.anonymousId`; `app.account.fullname` may only be shown, never stored or sent ([2](02-design-the-material.md) "Personal data").
92
+ - **Files the whole class sees** (pictures and PDFs on board cards): SDK `app.sdk.sharedFiles` (provisional API) — `post(file)` gives `{ key, size, contentType }` (PNG · JPEG · WebP up to 10MB, PDF up to 20MB, no GIF or SVG; pictures are redrawn at most 2048px without EXIF), `url(key)` the signed URL for `<img>` or a link, `delete(key)`. Keep only the `key` in `kvstore`, delete the file with its card, and open a PDF in a new tab (`target="_blank"`), never in an `<iframe>` (the browser PDF viewer is blocked inside the LXP sandbox). A tutor only reads; an editor preview keeps files in memory. The board template already does all of this
92
93
  - Use `app.viewer` (`student` · `instructor` · `tutor`), `app.readOnly` (tutoring) and `app.account.anonymousId` (for example a per-person fixed random seed) only when needed. The kit handles per-viewer behavior such as the tutoring lock, so the screen code does not branch on the viewer.
93
94
  - **The instructor screen shows only in the LXP editor preview** (student/instructor switch → instructor; `app.screen` `instructor`). On the learning page an instructor gets the student screen (`app.screen` `learn`, `app.viewer` `instructor`, submissions graded but not recorded). Never add instructor-only parts to the student screen with `if (app.viewer === 'instructor')`: the editor preview's student switch also has viewer `instructor`, so the author would not see what students see, and everything in the student screen (code and `settings`) reaches students anyway. Put explanations and teaching tips on the instructor screen instead. In `ecdk dev` open it with the '교육자 화면 (미리보기)' view (`?view=instructor`): like the editor preview it runs with an edit token, so submissions there are rejected.
94
95
  - Steps inside one material: turn on the kit's stepper and give each step a layout ([14](14-layouts.md)). Never draw an LXP-like bottom 이전 · 다음 bar or your own `n / N`.
@@ -181,6 +181,21 @@ interface LearnerFiles {
181
181
  url(path: string): Promise<string | null>;
182
182
  }
183
183
 
184
+ interface SharedFiles {
185
+ /** The mock keeps the file in memory as it is (no canvas re-encoding) */
186
+ post(
187
+ file: Blob,
188
+ options?: {
189
+ reencode?: boolean;
190
+ onProgress?: (progress: { loaded: number; total: number }) => void;
191
+ signal?: AbortSignal;
192
+ }
193
+ ): Promise<{ key: string; size: number; contentType: string; width?: number; height?: number }>;
194
+ /** Object URL of a file posted in this page, else null */
195
+ url(key: string): Promise<string | null>;
196
+ delete(key: string): Promise<void>;
197
+ }
198
+
184
199
  interface Mlapi {
185
200
  /** Same as `fetch`. The mock answers 503 SERVICE_UNAVAILABLE (reason ai_not_configured) */
186
201
  fetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;
@@ -214,6 +229,7 @@ export declare class MockEliceCDK {
214
229
  readonly assets: Assets;
215
230
  readonly kvstore: Kvstore;
216
231
  readonly learnerFiles: LearnerFiles;
232
+ readonly sharedFiles: SharedFiles;
217
233
  readonly mlapi: Mlapi;
218
234
  readonly accessToken: string | null;
219
235
  readonly videoPlayerUrl: string | null;