aicommunicator-plugin-check 0.0.0-stage → 0.2.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.
package/LICENSE ADDED
@@ -0,0 +1,55 @@
1
+ Apache License
2
+
3
+ Version 2.0, January 2004
4
+
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
16
+
17
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
18
+
19
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
20
+
21
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
22
+
23
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
24
+
25
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
26
+
27
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
28
+
29
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
30
+
31
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
32
+
33
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
34
+
35
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
36
+
37
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
38
+
39
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
40
+
41
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
42
+
43
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
package/README.md CHANGED
@@ -1,3 +1,58 @@
1
- # Temporary Holding Version
1
+ # aicommunicator-plugin-check
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ AIC(aicommunicator) 플러그인의 manifest 와 묶음 파일(`.tgz`)의 규칙을 확인하는 코드입니다. AIC 코어, `aic` 명령, 플러그인 등록 사이트가 이 패키지 하나를 함께 써서, 셋이 같은 플러그인을 같은 규칙으로 받아들이거나 거절합니다.
4
+
5
+ - 다른 패키지에 기대지 않고 Node 내장 모듈(`node:crypto`, `node:zlib`)만 씁니다. Node 22.13 이상에서 돕니다.
6
+ - 플러그인 코드를 실행하지 않습니다. manifest 의 글, 묶음 안의 파일 이름과 크기, 설명서와 예제 파일의 글만 봅니다.
7
+ - 설계는 aicommunicator 저장소의 `doc/036_plugin_registry_design.md` 에 있고, 설명서와 예제는 `doc/037_plugin_manual_design.md` 에 있습니다.
8
+
9
+ ```bash
10
+ npm install aicommunicator-plugin-check
11
+ ```
12
+
13
+ ```js
14
+ import { readBundle, checkBundleForRegistry, BundleError } from 'aicommunicator-plugin-check';
15
+
16
+ try {
17
+ const bundle = readBundle(buffer); // .tgz 의 Buffer
18
+ const problem = checkBundleForRegistry(bundle);
19
+ if (problem) console.log(problem.code, problem.message);
20
+ } catch (e) {
21
+ if (e instanceof BundleError) console.log(e.code, e.message);
22
+ }
23
+ ```
24
+
25
+ ## 내보내는 것
26
+
27
+ | 이름 | 하는 일 |
28
+ | --- | --- |
29
+ | `PROTOCOL_VERSION` | 코어의 플러그인 계약 버전. 지금 `"0.1"` |
30
+ | `checkManifest(manifest)` | 코어가 쓰는 manifest 검사. 틀리면 까닭의 글, 맞으면 `null` |
31
+ | `checkForRegistry(manifest)` | `checkManifest` 에 더해 사이트에 올릴 때 필요한 칸(`protocol`, `license`, `title`, `about`)을 본다 |
32
+ | `checkBundleForRegistry(bundle)` | `checkForRegistry` 와 `LICENSE` 파일을 본다. 문제가 있으면 `{ code, message }`(code 는 `bad_manifest` 나 `bad_bundle`), 없으면 `null` |
33
+ | `readBundle(buffer)` | `.tgz` 를 풀어 규칙(들어갈 수 있는 파일, 5MB, 200개, 묶음 밖 경로, 링크, 설명서와 예제)을 확인하고 `{ manifest, files, sha256, size }` 를 돌려준다. 틀리면 `BundleError` 를 던진다 |
34
+ | `BundleError` | `code` 가 `too_large`, `bad_bundle`, `bad_manifest` 가운데 하나다 |
35
+ | `packBundle(files)` | 파일 목록으로 `.tgz` 를 만든다. 같은 입력이면 같은 바이트가 나온다 |
36
+ | `compareVersions(a, b)` | semver 순서. -1, 0, 1 |
37
+ | `satisfies(version, range)` | `1.2.3`, `^1.2.3`, `~1.2.3`, `>=1.2.3` 네 가지 범위. 뜻은 npm 과 같다 |
38
+ | `protocolAccepts(range, core?)` | manifest 의 `protocol` 이 코어의 계약 버전을 받는지 |
39
+ | `stateId(plugins)`, `canonicalState(plugins)`, `checkState(plugins)` | 플러그인 구성의 상태 id 계산과 목록의 모양 검사 |
40
+ | `isPluginId`, `idOwner`, `isVersion`, `isPrerelease`, `isRange`, `isProtocolRange`, `isStateId` | 모양 확인 |
41
+ | `bundleFileName`, `bundlePathAllowed`, `sha256Hex` | 묶음 파일 이름, 묶음에 들어갈 수 있는 경로인지, sha256 |
42
+ | `BUNDLE_MAX_BYTES`, `BUNDLE_MAX_FILES`, `MAX_DEPENDENCIES`, `STATE_MAX_PLUGINS`, `RESERVED_IDS` | 한도와 쓰지 못하는 id |
43
+ | `checkMessageTable(data)` | 외부 연결의 메시지 표(`aic-link-messages/1`) 파일의 바이트를 검사한다. 맞으면 `{ ok: true, table }`, 틀리면 `{ ok: false, problems }` |
44
+ | `renderMessage(table, id, values)` | 표에 등록한 메시지 id 와 값을 글로 푼다. 등록하지 않은 id, 값이 틀린 것, 모양이 틀린 id 는 글을 만들지 않고 까닭(`unknown_id`, `bad_values`, `malformed_id`)을 돌려준다 |
45
+ | `isMessageId`, `MESSAGE_TABLE_FORMAT`, `MESSAGE_TABLE_MAX_BYTES`, `MESSAGE_TABLE_MAX_MESSAGES`, `MESSAGE_TEXT_MAX` | 메시지 표의 모양 확인과 한도 |
46
+ | `docsProblem(manifest, files)` | manifest 의 `manual`(설명서)과 `samples`(예제)가 가리키는 파일이 있는지, 한도와 모양이 맞는지 본다. `readBundle` 이 함께 부른다 |
47
+ | `bundleNotices(manifest)` | 거절하지 않고 알리기만 하는 것. 지금은 설명서가 없을 때 한 줄이다 |
48
+ | `checkSample(value)`, `parseSample(data)`, `parseManual(data)` | 예제 파일(`aic-sample/1`)의 모양 검사, 예제와 설명서 파일의 글자 한도와 UTF-8 검사 |
49
+ | `sampleNarrative(sample, { installed?, self? })`, `samplePluginLines`, `missingPlugins` | 예제를 revision 마다 사람의 말, AI 가 한 일, 화면 변화의 차례 글로 옮기고, 설치되지 않은 플러그인을 알린다 |
50
+ | `SAMPLE_FORMAT`, `MANUAL_MAX_CHARS`, `SAMPLE_MAX_CHARS`, `MAX_SAMPLES`, `SAMPLE_WHO` | 예제 형식의 이름, 설명서 50,000자, 예제 하나 200,000자, 예제 다섯 개, 참여자 표기("사람", "AI", "코어") |
51
+
52
+ ## 버전
53
+
54
+ 검사 규칙을 바꾸면 이 패키지의 버전을 올리고, 등록 사이트가 그 버전을 따라 올립니다. 0 으로 시작하는 동안은 가운데 숫자가 바뀌면 규칙이 호환되지 않게 바뀐 것입니다.
55
+
56
+ ## 라이선스
57
+
58
+ Apache-2.0
@@ -0,0 +1,61 @@
1
+ import { type Manifest } from './manifest.ts';
2
+ /** 묶음 파일의 크기 한도와 풀린 파일 크기 합의 한도(036 12절 3번). */
3
+ export declare const BUNDLE_MAX_BYTES: number;
4
+ /** 묶음 안 파일 수의 한도. */
5
+ export declare const BUNDLE_MAX_FILES = 200;
6
+ export interface Bundle {
7
+ manifest: Manifest;
8
+ /** 경로마다 파일 내용. 경로는 `/` 로 나눈 상대 경로다. */
9
+ files: Map<string, Buffer>;
10
+ /** 묶음 파일 전체의 sha256(16진 소문자). */
11
+ sha256: string;
12
+ /** 묶음 파일의 바이트 수. */
13
+ size: number;
14
+ }
15
+ export type BundleErrorCode = 'too_large' | 'bad_bundle' | 'bad_manifest';
16
+ /** 묶음이 규칙에 맞지 않을 때 던진다. code 는 등록 사이트의 오류 코드와 같다. */
17
+ export declare class BundleError extends Error {
18
+ readonly code: BundleErrorCode;
19
+ constructor(code: BundleErrorCode, message: string);
20
+ }
21
+ /** 묶음 파일의 이름. 예: rawdev.novel-0.3.0.tgz */
22
+ export declare function bundleFileName(id: string, version: string): string;
23
+ export declare function sha256Hex(data: Uint8Array | string): string;
24
+ /**
25
+ * 이 경로의 파일이 묶음에 들어갈 수 있는가(036 3절). manifest, 논리 파일, ui/ 의 파일, LICENSE, README.md, 그리고 manifest 가 가리키는
26
+ * 설명서와 예제 파일(037 5.1절)뿐이다.
27
+ */
28
+ export declare function bundlePathAllowed(p: string, manifest: Pick<Manifest, 'logic' | 'manual' | 'samples'>): boolean;
29
+ /**
30
+ * 설명서와 예제 파일의 검사(037 5절, 7절 4번). manifest 가 가리키는 파일이 묶음에 있어야 하고, 설명서는 50,000자, 예제는 하나에
31
+ * 200,000자까지다. 예제는 aic-sample/1 모양이어야 하고 쓴 플러그인에 이 플러그인이 있어야 한다. 틀리면 까닭이고 없으면 null 이다.
32
+ */
33
+ export declare function docsProblem(manifest: Pick<Manifest, 'id' | 'manual' | 'samples'>, files: ReadonlyMap<string, Uint8Array>): string | null;
34
+ /** 아이콘 파일의 검사(036 16절). manifest 가 가리키는 파일이 묶음에 있어야 하고 iconProblem 을 지나야 한다. 틀리면 까닭이고 없으면 null 이다. */
35
+ export declare function iconFileProblem(manifest: Pick<Manifest, 'icon'>, files: ReadonlyMap<string, Uint8Array>): string | null;
36
+ /**
37
+ * 묶음에 대한 알림. 거절하지 않고 알리기만 한다. 설명서가 없을 때 한 줄(037 7절 3번: 등록 사이트는 설명서를 권하되 요구하지 않는다)과
38
+ * 대표 아이콘이 없을 때 한 줄(036 16절)이다.
39
+ */
40
+ export declare function bundleNotices(manifest: Pick<Manifest, 'manual' | 'icon'>): string[];
41
+ /**
42
+ * 파일 목록으로 `.tgz` 를 만든다. 경로의 글자 순서(UTF-16 코드 단위)로 늘어놓고 시각, 권한, 소유자를 고정하므로 같은 node 에서
43
+ * 같은 입력이면 같은 바이트가 나온다. 경로가 플러그인 폴더 안의 상대 경로가 아니면 던진다. manifest 의 검사는 하지 않는다.
44
+ */
45
+ export declare function packBundle(files: Map<string, Uint8Array | string> | Record<string, Uint8Array | string>): Buffer;
46
+ /**
47
+ * `.tgz` 를 풀어 036 3절의 규칙을 확인한다. 묶음 크기, 풀린 크기, 파일 수, 묶음 밖 경로, 보통 파일이 아닌 항목(링크 같은 것),
48
+ * 같은 경로 둘, 들어갈 수 없는 파일, manifest 검사, 논리 파일과 화면 파일이 있는지, 설명서와 예제 파일(docsProblem), 아이콘 파일
49
+ * (iconFileProblem)을 본다. 틀리면
50
+ * 까닭이 든 BundleError 를 던진다.
51
+ * 풀린 크기는 gzip 을 풀면서 한도로 막으므로 아주 크게 부풀리는 묶음도 메모리에 다 풀지 않는다.
52
+ */
53
+ export declare function readBundle(buffer: Uint8Array): Bundle;
54
+ /**
55
+ * 등록 사이트에 올릴 때 묶음에 더 요구하는 것. manifest 의 칸(checkForRegistry)과 LICENSE 파일이다. 문제가 없으면 null 이고, 있으면
56
+ * 등록 사이트의 오류 코드(manifest 의 칸이면 bad_manifest, 파일이면 bad_bundle)와 까닭이다.
57
+ */
58
+ export declare function checkBundleForRegistry(bundle: Bundle): {
59
+ code: 'bad_manifest' | 'bad_bundle';
60
+ message: string;
61
+ } | null;
package/dist/bundle.js ADDED
@@ -0,0 +1,318 @@
1
+ // 플러그인 묶음 파일(036 3절). `.tgz`(gzip 으로 줄인 ustar) 하나에 플러그인 한 버전이 든다. 파일은 경로 앞에 폴더를 붙이지 않고
2
+ // 플러그인 폴더의 상대 경로 그대로 넣는다. node 내장 모듈만 쓴다.
3
+ import { createHash } from 'node:crypto';
4
+ import zlib from 'node:zlib';
5
+ import { checkForRegistry, checkManifest, isFileName, isPluginPath } from "./manifest.js";
6
+ import { iconProblem } from "./icon.js";
7
+ import { parseManual, parseSample } from "./sample.js";
8
+ /** 묶음 파일의 크기 한도와 풀린 파일 크기 합의 한도(036 12절 3번). */
9
+ export const BUNDLE_MAX_BYTES = 5 * 1024 * 1024;
10
+ /** 묶음 안 파일 수의 한도. */
11
+ export const BUNDLE_MAX_FILES = 200;
12
+ /** 묶음이 규칙에 맞지 않을 때 던진다. code 는 등록 사이트의 오류 코드와 같다. */
13
+ export class BundleError extends Error {
14
+ code;
15
+ constructor(code, message) {
16
+ super(message);
17
+ this.name = 'BundleError';
18
+ this.code = code;
19
+ }
20
+ }
21
+ /** 묶음 파일의 이름. 예: rawdev.novel-0.3.0.tgz */
22
+ export function bundleFileName(id, version) {
23
+ return `${id}-${version}.tgz`;
24
+ }
25
+ export function sha256Hex(data) {
26
+ return createHash('sha256').update(data).digest('hex');
27
+ }
28
+ /**
29
+ * 이 경로의 파일이 묶음에 들어갈 수 있는가(036 3절). manifest, 논리 파일, ui/ 의 파일, LICENSE, README.md, 그리고 manifest 가 가리키는
30
+ * 설명서와 예제 파일(037 5.1절)뿐이다.
31
+ */
32
+ export function bundlePathAllowed(p, manifest) {
33
+ if (p === 'manifest.json' || p === 'LICENSE' || p === 'README.md' || p === manifest.logic)
34
+ return true;
35
+ if (p === manifest.manual || (manifest.samples ?? []).some((s) => s.file === p))
36
+ return true;
37
+ return p.startsWith('ui/') && isFileName(p.slice(3));
38
+ }
39
+ /**
40
+ * 설명서와 예제 파일의 검사(037 5절, 7절 4번). manifest 가 가리키는 파일이 묶음에 있어야 하고, 설명서는 50,000자, 예제는 하나에
41
+ * 200,000자까지다. 예제는 aic-sample/1 모양이어야 하고 쓴 플러그인에 이 플러그인이 있어야 한다. 틀리면 까닭이고 없으면 null 이다.
42
+ */
43
+ export function docsProblem(manifest, files) {
44
+ if (manifest.manual !== undefined) {
45
+ const data = files.get(manifest.manual);
46
+ if (!data)
47
+ return `설명서 파일 ${manifest.manual} 이 없다`;
48
+ const read = parseManual(data);
49
+ if (!read.ok)
50
+ return `${manifest.manual}: ${read.problem}`;
51
+ }
52
+ for (const s of manifest.samples ?? []) {
53
+ const data = files.get(s.file);
54
+ if (!data)
55
+ return `예제 ${s.id} 의 파일 ${s.file} 이 없다`;
56
+ const read = parseSample(data);
57
+ if (!read.ok)
58
+ return `예제 ${s.id}(${s.file}): ${read.problem}`;
59
+ if (!read.sample.plugins.some((p) => p.package === manifest.id))
60
+ return `예제 ${s.id}(${s.file}) 의 plugins 에 이 플러그인 ${manifest.id} 이 없다. 이 플러그인을 쓴 작업을 내보낸다`;
61
+ }
62
+ return null;
63
+ }
64
+ /** 아이콘 파일의 검사(036 16절). manifest 가 가리키는 파일이 묶음에 있어야 하고 iconProblem 을 지나야 한다. 틀리면 까닭이고 없으면 null 이다. */
65
+ export function iconFileProblem(manifest, files) {
66
+ if (manifest.icon === undefined)
67
+ return null;
68
+ const data = files.get(manifest.icon);
69
+ if (!data)
70
+ return `아이콘 파일 ${manifest.icon} 이 없다`;
71
+ const problem = iconProblem(data);
72
+ return problem ? `${manifest.icon}: ${problem}` : null;
73
+ }
74
+ /**
75
+ * 묶음에 대한 알림. 거절하지 않고 알리기만 한다. 설명서가 없을 때 한 줄(037 7절 3번: 등록 사이트는 설명서를 권하되 요구하지 않는다)과
76
+ * 대표 아이콘이 없을 때 한 줄(036 16절)이다.
77
+ */
78
+ export function bundleNotices(manifest) {
79
+ return [
80
+ ...(manifest.manual === undefined ? ['설명서(manifest 의 manual)가 없다. 등록 사이트는 설명서를 권한다. 없어도 올라간다'] : []),
81
+ ...(manifest.icon === undefined ? ['대표 아이콘(manifest 의 icon)이 없다. 플러그인을 고르는 화면은 이름의 첫 글자를 보인다. 없어도 올라간다'] : []),
82
+ ];
83
+ }
84
+ // ---- ustar ----
85
+ const BLOCK = 512;
86
+ /** gzip 머리말. 시각 0, 운영체제 "모름"(255)으로 두어 어느 컴퓨터에서 만들어도 머리말이 같게 한다. */
87
+ const GZIP_HEADER = Buffer.from([0x1f, 0x8b, 0x08, 0x00, 0, 0, 0, 0, 0x00, 0xff]);
88
+ function octal(value, width) {
89
+ return value.toString(8).padStart(width - 1, '0') + '\0';
90
+ }
91
+ function writeString(buf, offset, width, s) {
92
+ const bytes = Buffer.from(s, 'utf8');
93
+ if (bytes.length > width)
94
+ throw new BundleError('bad_bundle', `묶음 안의 이름이 너무 길다: ${s}`);
95
+ bytes.copy(buf, offset);
96
+ }
97
+ /** 이름이 100바이트를 넘으면 ustar 의 prefix(155바이트)로 나눈다. */
98
+ function splitName(p) {
99
+ if (Buffer.byteLength(p) <= 100)
100
+ return { name: p, prefix: '' };
101
+ for (let i = p.lastIndexOf('/'); i > 0; i = p.lastIndexOf('/', i - 1)) {
102
+ const prefix = p.slice(0, i);
103
+ const name = p.slice(i + 1);
104
+ if (Buffer.byteLength(prefix) <= 155 && Buffer.byteLength(name) <= 100)
105
+ return { name, prefix };
106
+ }
107
+ throw new BundleError('bad_bundle', `묶음 안의 경로가 너무 길다: ${p}`);
108
+ }
109
+ function header(p, size) {
110
+ const h = Buffer.alloc(BLOCK);
111
+ const { name, prefix } = splitName(p);
112
+ writeString(h, 0, 100, name);
113
+ writeString(h, 100, 8, octal(0o644, 8));
114
+ writeString(h, 108, 8, octal(0, 8));
115
+ writeString(h, 116, 8, octal(0, 8));
116
+ writeString(h, 124, 12, octal(size, 12));
117
+ writeString(h, 136, 12, octal(0, 12));
118
+ h.fill(0x20, 148, 156);
119
+ h[156] = 0x30; // '0' 보통 파일
120
+ writeString(h, 257, 6, 'ustar\0');
121
+ writeString(h, 263, 2, '00');
122
+ writeString(h, 345, 155, prefix);
123
+ let sum = 0;
124
+ for (const b of h)
125
+ sum += b;
126
+ writeString(h, 148, 8, sum.toString(8).padStart(6, '0') + '\0 ');
127
+ return h;
128
+ }
129
+ /**
130
+ * 파일 목록으로 `.tgz` 를 만든다. 경로의 글자 순서(UTF-16 코드 단위)로 늘어놓고 시각, 권한, 소유자를 고정하므로 같은 node 에서
131
+ * 같은 입력이면 같은 바이트가 나온다. 경로가 플러그인 폴더 안의 상대 경로가 아니면 던진다. manifest 의 검사는 하지 않는다.
132
+ */
133
+ export function packBundle(files) {
134
+ const entries = (files instanceof Map ? [...files.entries()] : Object.entries(files)).map(([p, data]) => [p, typeof data === 'string' ? Buffer.from(data, 'utf8') : Buffer.from(data)]);
135
+ entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
136
+ const parts = [];
137
+ const seen = new Set();
138
+ for (const [p, data] of entries) {
139
+ if (!isPluginPath(p))
140
+ throw new BundleError('bad_bundle', `묶음에 넣을 수 없는 경로다: ${JSON.stringify(p)}`);
141
+ if (seen.has(p))
142
+ throw new BundleError('bad_bundle', `같은 경로가 둘이다: ${p}`);
143
+ seen.add(p);
144
+ parts.push(header(p, data.length), data);
145
+ const pad = (BLOCK - (data.length % BLOCK)) % BLOCK;
146
+ if (pad)
147
+ parts.push(Buffer.alloc(pad));
148
+ }
149
+ parts.push(Buffer.alloc(BLOCK * 2));
150
+ const tar = Buffer.concat(parts);
151
+ const body = zlib.deflateRawSync(tar, { level: 9 });
152
+ const trailer = Buffer.alloc(8);
153
+ trailer.writeUInt32LE(zlib.crc32(tar) >>> 0, 0);
154
+ trailer.writeUInt32LE(tar.length % 0x100000000, 4);
155
+ return Buffer.concat([GZIP_HEADER, body, trailer]);
156
+ }
157
+ function readString(buf, offset, width) {
158
+ const slice = buf.subarray(offset, offset + width);
159
+ const end = slice.indexOf(0);
160
+ return slice.subarray(0, end === -1 ? width : end).toString('utf8');
161
+ }
162
+ function readOctal(buf, offset, width, what) {
163
+ if (buf[offset] & 0x80)
164
+ throw new BundleError('bad_bundle', `묶음의 ${what} 를 읽지 못했다(256진 표기는 받지 않는다)`);
165
+ const s = readString(buf, offset, width).trim();
166
+ if (s === '')
167
+ return 0;
168
+ if (!/^[0-7]+$/.test(s))
169
+ throw new BundleError('bad_bundle', `묶음의 ${what} 가 8진 숫자가 아니다`);
170
+ return parseInt(s, 8);
171
+ }
172
+ /** pax 머리말의 "길이 key=value\n" 기록에서 path 를 꺼낸다. */
173
+ function paxPath(data) {
174
+ let found;
175
+ let i = 0;
176
+ while (i < data.length) {
177
+ const space = data.indexOf(0x20, i);
178
+ if (space === -1)
179
+ break;
180
+ const len = Number(data.subarray(i, space).toString('ascii'));
181
+ if (!Number.isInteger(len) || len <= 0 || i + len > data.length)
182
+ throw new BundleError('bad_bundle', '묶음의 pax 머리말을 읽지 못했다');
183
+ const record = data.subarray(space + 1, i + len - 1).toString('utf8');
184
+ const eq = record.indexOf('=');
185
+ if (eq > 0 && record.slice(0, eq) === 'path')
186
+ found = record.slice(eq + 1);
187
+ i += len;
188
+ }
189
+ return found;
190
+ }
191
+ /** 묶음 안 경로를 고르게 한다. 앞의 `./` 를 떼고, 폴더 항목의 끝 `/` 를 뗀다. 묶음 밖을 가리키거나 모양이 틀리면 던진다. */
192
+ function cleanPath(raw, dir) {
193
+ let p = raw;
194
+ while (p.startsWith('./'))
195
+ p = p.slice(2);
196
+ if (dir)
197
+ p = p.replace(/\/+$/, '');
198
+ if (dir && (p === '' || p === '.'))
199
+ return '';
200
+ if (!isPluginPath(p))
201
+ throw new BundleError('bad_bundle', `묶음 안의 경로가 플러그인 폴더 안의 상대 경로가 아니다: ${JSON.stringify(raw)}`);
202
+ return p;
203
+ }
204
+ /**
205
+ * `.tgz` 를 풀어 036 3절의 규칙을 확인한다. 묶음 크기, 풀린 크기, 파일 수, 묶음 밖 경로, 보통 파일이 아닌 항목(링크 같은 것),
206
+ * 같은 경로 둘, 들어갈 수 없는 파일, manifest 검사, 논리 파일과 화면 파일이 있는지, 설명서와 예제 파일(docsProblem), 아이콘 파일
207
+ * (iconFileProblem)을 본다. 틀리면
208
+ * 까닭이 든 BundleError 를 던진다.
209
+ * 풀린 크기는 gzip 을 풀면서 한도로 막으므로 아주 크게 부풀리는 묶음도 메모리에 다 풀지 않는다.
210
+ */
211
+ export function readBundle(buffer) {
212
+ const buf = Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength);
213
+ if (buf.length > BUNDLE_MAX_BYTES)
214
+ throw new BundleError('too_large', `묶음이 ${BUNDLE_MAX_BYTES} 바이트를 넘는다(${buf.length} 바이트)`);
215
+ // 파일 내용의 합은 BUNDLE_MAX_BYTES 까지이고, 머리말과 채움은 파일마다 1,024 바이트를 넘지 않는다
216
+ const maxTar = BUNDLE_MAX_BYTES + (BUNDLE_MAX_FILES + 8) * BLOCK * 2;
217
+ let tar;
218
+ try {
219
+ tar = zlib.gunzipSync(buf, { maxOutputLength: maxTar });
220
+ }
221
+ catch (e) {
222
+ if (e instanceof RangeError || e.code === 'ERR_BUFFER_TOO_LARGE') {
223
+ throw new BundleError('too_large', `풀린 묶음이 한도(${BUNDLE_MAX_BYTES} 바이트)를 넘는다`);
224
+ }
225
+ throw new BundleError('bad_bundle', `묶음이 gzip 파일이 아니다(${e.message})`);
226
+ }
227
+ const files = new Map();
228
+ let total = 0;
229
+ let offset = 0;
230
+ let nextPath;
231
+ let ended = false;
232
+ while (offset + BLOCK <= tar.length) {
233
+ const h = tar.subarray(offset, offset + BLOCK);
234
+ if (h.every((b) => b === 0)) {
235
+ ended = true;
236
+ break;
237
+ }
238
+ let sum = 0;
239
+ for (let i = 0; i < BLOCK; i += 1)
240
+ sum += i >= 148 && i < 156 ? 0x20 : h[i];
241
+ if (readOctal(h, 148, 8, '검사합') !== sum)
242
+ throw new BundleError('bad_bundle', '묶음의 머리말 검사합이 맞지 않는다');
243
+ const size = readOctal(h, 124, 12, '파일 크기');
244
+ const type = String.fromCharCode(h[156]);
245
+ const dataStart = offset + BLOCK;
246
+ const dataEnd = dataStart + size;
247
+ if (dataEnd > tar.length)
248
+ throw new BundleError('bad_bundle', '묶음이 중간에 끊겼다');
249
+ const data = tar.subarray(dataStart, dataEnd);
250
+ offset = dataStart + Math.ceil(size / BLOCK) * BLOCK;
251
+ if (type === 'x') {
252
+ nextPath = paxPath(data) ?? nextPath;
253
+ continue;
254
+ }
255
+ if (type === 'g')
256
+ continue;
257
+ if (type === 'L') {
258
+ nextPath = readString(data, 0, data.length);
259
+ continue;
260
+ }
261
+ const prefix = readString(h, 345, 155);
262
+ const rawName = nextPath ?? (prefix ? `${prefix}/${readString(h, 0, 100)}` : readString(h, 0, 100));
263
+ nextPath = undefined;
264
+ if (type === '5') {
265
+ cleanPath(rawName, true);
266
+ continue;
267
+ }
268
+ if (type !== '0' && type !== '\0')
269
+ throw new BundleError('bad_bundle', `묶음에 보통 파일이 아닌 항목이 있다: ${rawName}`);
270
+ const p = cleanPath(rawName, false);
271
+ if (files.has(p))
272
+ throw new BundleError('bad_bundle', `묶음에 같은 경로가 둘이다: ${p}`);
273
+ if (files.size + 1 > BUNDLE_MAX_FILES)
274
+ throw new BundleError('too_large', `묶음의 파일이 ${BUNDLE_MAX_FILES}개를 넘는다`);
275
+ total += size;
276
+ if (total > BUNDLE_MAX_BYTES)
277
+ throw new BundleError('too_large', `묶음의 파일 크기 합이 ${BUNDLE_MAX_BYTES} 바이트를 넘는다`);
278
+ files.set(p, Buffer.from(data));
279
+ }
280
+ if (!ended)
281
+ throw new BundleError('bad_bundle', '묶음의 끝 표시가 없다');
282
+ const manifestFile = files.get('manifest.json');
283
+ if (!manifestFile)
284
+ throw new BundleError('bad_bundle', '묶음에 manifest.json 이 없다');
285
+ let manifest;
286
+ try {
287
+ manifest = JSON.parse(manifestFile.toString('utf8'));
288
+ }
289
+ catch (e) {
290
+ throw new BundleError('bad_manifest', `manifest.json 이 JSON 이 아니다(${e.message})`);
291
+ }
292
+ const problem = checkManifest(manifest);
293
+ if (problem)
294
+ throw new BundleError('bad_manifest', problem);
295
+ const m = manifest;
296
+ if (!files.has(m.logic))
297
+ throw new BundleError('bad_bundle', `묶음에 논리 파일 ${m.logic} 이 없다`);
298
+ if (m.ui !== undefined && !files.has(m.ui))
299
+ throw new BundleError('bad_bundle', `묶음에 화면 파일 ${m.ui} 가 없다`);
300
+ const extra = [...files.keys()].filter((p) => !bundlePathAllowed(p, m));
301
+ if (extra.length > 0) {
302
+ throw new BundleError('bad_bundle', `묶음에 넣을 수 없는 파일이 있다: ${extra.join(', ')}. manifest.json, 논리 파일, ui/ 의 파일, LICENSE, README.md, manifest 의 manual 과 samples 가 가리키는 파일만 넣는다`);
303
+ }
304
+ const docs = docsProblem(m, files) ?? iconFileProblem(m, files);
305
+ if (docs)
306
+ throw new BundleError('bad_bundle', docs);
307
+ return { manifest: m, files, sha256: sha256Hex(buf), size: buf.length };
308
+ }
309
+ /**
310
+ * 등록 사이트에 올릴 때 묶음에 더 요구하는 것. manifest 의 칸(checkForRegistry)과 LICENSE 파일이다. 문제가 없으면 null 이고, 있으면
311
+ * 등록 사이트의 오류 코드(manifest 의 칸이면 bad_manifest, 파일이면 bad_bundle)와 까닭이다.
312
+ */
313
+ export function checkBundleForRegistry(bundle) {
314
+ const problem = checkForRegistry(bundle.manifest);
315
+ if (problem)
316
+ return { code: 'bad_manifest', message: problem };
317
+ return bundle.files.has('LICENSE') ? null : { code: 'bad_bundle', message: '사이트에 올리려면 묶음에 LICENSE 파일이 있어야 한다' };
318
+ }
package/dist/icon.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ /** 아이콘 파일의 크기 한도. 작은 그림 하나에 넉넉하고 목록에 여러 개를 올려도 가볍다. */
2
+ export declare const ICON_MAX_BYTES: number;
3
+ /** 아이콘 경로인가. ui/ 바로 아래의 .svg 파일이다. 코어가 `/plugin/<id>/ui/<파일>` 로 내보내는 곳과 같다. */
4
+ export declare function isIconPath(p: unknown): p is string;
5
+ /**
6
+ * 아이콘 파일의 검사. 문제의 설명이고 없으면 null 이다. UTF-8 글이고 `<svg` 로 시작하는 SVG 여야 한다. 스크립트, 다른 문서를 넣는 요소,
7
+ * 움직임(animate, set), 이벤트 속성, 바깥 주소(href, src, url() 은 문서 안의 #id 만), DOCTYPE 과 ENTITY, @import 는 받지 않는다. 그림으로만 보일 때는 돌지 않는
8
+ * 것들이지만, 아이콘을 다른 방식으로 보이는 화면이 생겨도 안전하게 하려는 것이다.
9
+ */
10
+ export declare function iconProblem(data: Uint8Array): string | null;
package/dist/icon.js ADDED
@@ -0,0 +1,61 @@
1
+ // 플러그인의 대표 아이콘(036 16절, rawdev 2026-11-25). manifest 의 icon 은 ui/ 바로 아래의 SVG 파일 하나다. 새 작업 화면과 등록
2
+ // 사이트가 플러그인을 고르는 곳에 보인다. 올린 사람이 만든 파일이므로 그림으로만(img) 보이고, 그 전제에서도 스크립트, 바깥 주소,
3
+ // 다른 문서를 끌어오는 것은 파일에 들어 있지 못하게 검사한다. 코어, aic 명령, 등록 사이트가 같은 검사를 쓴다.
4
+ import { isUiPath } from "./manifest.js";
5
+ /** 아이콘 파일의 크기 한도. 작은 그림 하나에 넉넉하고 목록에 여러 개를 올려도 가볍다. */
6
+ export const ICON_MAX_BYTES = 32 * 1024;
7
+ /** 아이콘 경로인가. ui/ 바로 아래의 .svg 파일이다. 코어가 `/plugin/<id>/ui/<파일>` 로 내보내는 곳과 같다. */
8
+ export function isIconPath(p) {
9
+ return isUiPath(p) && p.toLowerCase().endsWith('.svg');
10
+ }
11
+ /** 주소를 받는 속성의 값이 문서 안의 것(#id)인가. */
12
+ function insideOnly(text, pattern) {
13
+ for (const m of text.matchAll(pattern)) {
14
+ const value = (m[2] ?? m[3] ?? '').trim();
15
+ if (!value.startsWith('#'))
16
+ return false;
17
+ }
18
+ return true;
19
+ }
20
+ /**
21
+ * 아이콘 파일의 검사. 문제의 설명이고 없으면 null 이다. UTF-8 글이고 `<svg` 로 시작하는 SVG 여야 한다. 스크립트, 다른 문서를 넣는 요소,
22
+ * 움직임(animate, set), 이벤트 속성, 바깥 주소(href, src, url() 은 문서 안의 #id 만), DOCTYPE 과 ENTITY, @import 는 받지 않는다. 그림으로만 보일 때는 돌지 않는
23
+ * 것들이지만, 아이콘을 다른 방식으로 보이는 화면이 생겨도 안전하게 하려는 것이다.
24
+ */
25
+ export function iconProblem(data) {
26
+ if (data.length === 0)
27
+ return '아이콘 파일이 비어 있다';
28
+ if (data.length > ICON_MAX_BYTES)
29
+ return `아이콘 파일이 ${ICON_MAX_BYTES.toLocaleString('en-US')} 바이트를 넘는다(${data.length.toLocaleString('en-US')} 바이트)`;
30
+ let text;
31
+ try {
32
+ text = new TextDecoder('utf-8', { fatal: true }).decode(data);
33
+ }
34
+ catch {
35
+ return '아이콘 파일이 UTF-8 글이 아니다';
36
+ }
37
+ if (/<!DOCTYPE|<!ENTITY/i.test(text))
38
+ return '아이콘에 DOCTYPE 이나 ENTITY 를 넣지 않는다';
39
+ const body = text
40
+ .replace(new RegExp('^' + String.fromCharCode(0xfeff)), '')
41
+ .replace(/^\s*<\?xml[^>]*\?>/, '')
42
+ .replace(/<!--[\s\S]*?-->/g, '');
43
+ if (!/^\s*<svg[\s>]/i.test(body))
44
+ return '아이콘 파일이 <svg 로 시작하는 SVG 가 아니다';
45
+ if (!/<\/svg>\s*$/i.test(body))
46
+ return '아이콘 파일이 </svg> 로 끝나지 않는다';
47
+ const banned = /<\s*(script|foreignObject|iframe|object|embed|audio|video|link|meta|style|animate|animateTransform|animateMotion|set)\b/i.exec(body);
48
+ if (banned)
49
+ return `아이콘에 ${banned[1]} 요소를 넣지 않는다`;
50
+ if (/[\s"'/]on[a-z]+\s*=/i.test(body))
51
+ return '아이콘에 이벤트 속성(on...)을 넣지 않는다';
52
+ if (/javascript\s*:|@import/i.test(body))
53
+ return '아이콘에 javascript: 주소나 @import 를 넣지 않는다';
54
+ if (!insideOnly(body, /\b(xlink:href|href|src)\s*=\s*(?:"([^"]*)"|'([^']*)')/gi))
55
+ return '아이콘의 href 와 src 는 문서 안의 #id 만 가리킨다(바깥 주소와 data: 주소는 받지 않는다)';
56
+ for (const m of body.matchAll(/url\(\s*(["']?)([^)"']*)\1\s*\)/gi)) {
57
+ if (!m[2].trim().startsWith('#'))
58
+ return '아이콘의 url() 은 문서 안의 #id 만 가리킨다';
59
+ }
60
+ return null;
61
+ }
@@ -0,0 +1,7 @@
1
+ export * from './version.ts';
2
+ export * from './manifest.ts';
3
+ export * from './icon.ts';
4
+ export * from './bundle.ts';
5
+ export * from './state.ts';
6
+ export * from './messages.ts';
7
+ export * from './sample.ts';
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ // aicommunicator-plugin-check(packages/manifest): 플러그인 manifest 검사, 버전 범위, 묶음 파일, 상태 id(036), 외부 연결의 메시지 표(032 31.3절),
2
+ // 설명서와 예제 파일(037 5절). 코어, aic 명령, 등록 사이트가 함께 쓴다. 다른 패키지에 기대지 않고 node 내장 모듈만 쓴다. 타입을 지우기만 하면
3
+ // 도는 TypeScript 로만 쓴다(enum, 생성자 인자 칸 없음).
4
+ export * from "./version.js";
5
+ export * from "./manifest.js";
6
+ export * from "./icon.js";
7
+ export * from "./bundle.js";
8
+ export * from "./state.js";
9
+ export * from "./messages.js";
10
+ export * from "./sample.js";