kintone-plugin-ide 0.0.0-stage → 0.3.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,50 @@
1
+ // パッケージング(Web Crypto + fflate)― 公式パッカーとバイト単位で一致することを確認済み
2
+ import { zipSync, unzipSync } from 'fflate';
3
+ import { b64, unb64 } from '../util/bytes.js';
4
+
5
+ const ALG = { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-1' };
6
+ const RSA_ALG = new Uint8Array([0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00]);
7
+ const derLen = (n) => (n < 128 ? [n] : n < 256 ? [0x81, n] : [0x82, n >> 8, n & 255]);
8
+ const cat = (...a) => { const o = new Uint8Array(a.reduce((s, x) => s + x.length, 0)); let i = 0; for (const x of a) { o.set(x, i); i += x.length; } return o; };
9
+ const pemBody = (pem) => unb64(pem.replace(/-----[^-]+-----|\s/g, ''));
10
+ const toPem = (der, label) => `-----BEGIN ${label}-----\n${b64(der).match(/.{1,64}/g).join('\n')}\n-----END ${label}-----\n`;
11
+ // .ppk は PKCS#1。Web Crypto は PKCS#8 しか読めないので包む / 剥がす
12
+ const p1to8 = (p1) => {
13
+ const body = cat(new Uint8Array([0x02, 0x01, 0x00]), RSA_ALG, cat(new Uint8Array([0x04, ...derLen(p1.length)]), p1));
14
+ return cat(new Uint8Array([0x30, ...derLen(body.length)]), body);
15
+ };
16
+ const p8to1 = (p8) => {
17
+ let i = 0;
18
+ const len = () => { let l = p8[i++]; if (l & 0x80) { const n = l & 0x7f; l = 0; for (let k = 0; k < n; k++) l = (l << 8) | p8[i++]; } return l; };
19
+ const skip = () => { i++; const l = len(); i += l; };
20
+ i++; len(); skip(); skip(); i++; const l = len();
21
+ return p8.slice(i, i + l);
22
+ };
23
+
24
+ export async function generateKey() {
25
+ const kp = await crypto.subtle.generateKey({ ...ALG, modulusLength: 1024, publicExponent: new Uint8Array([1, 0, 1]) }, true, ['sign', 'verify']);
26
+ return toPem(p8to1(new Uint8Array(await crypto.subtle.exportKey('pkcs8', kp.privateKey))), 'RSA PRIVATE KEY');
27
+ }
28
+ export async function idFromSpki(spki) {
29
+ const hex = [...new Uint8Array(await crypto.subtle.digest('SHA-256', spki))].map((b) => b.toString(16).padStart(2, '0')).join('').slice(0, 32);
30
+ return hex.replace(/[0-9a-f]/g, (c) => 'abcdefghijklmnop'['0123456789abcdef'.indexOf(c)]);
31
+ }
32
+ export async function pack(contentsZip, ppk) {
33
+ const key = await crypto.subtle.importKey('pkcs8', p1to8(pemBody(ppk)), ALG, true, ['sign']);
34
+ const signature = new Uint8Array(await crypto.subtle.sign(ALG, key, contentsZip));
35
+ const jwk = await crypto.subtle.exportKey('jwk', key);
36
+ const pub = await crypto.subtle.importKey('jwk', { kty: 'RSA', n: jwk.n, e: jwk.e, alg: 'RS1', ext: true }, ALG, true, ['verify']);
37
+ const spki = new Uint8Array(await crypto.subtle.exportKey('spki', pub));
38
+ return { id: await idFromSpki(spki), plugin: zipSync({ 'contents.zip': contentsZip, PUBKEY: spki, SIGNATURE: signature }) };
39
+ }
40
+ // プラグインzip の署名を検証して中身を取り出す(import 用)。プラグインでなければ null
41
+ export async function unpack(pluginZip) {
42
+ const outer = unzipSync(pluginZip);
43
+ if (!outer['contents.zip']) return null;
44
+ let verified = false;
45
+ if (outer.PUBKEY && outer.SIGNATURE) {
46
+ const pub = await crypto.subtle.importKey('spki', outer.PUBKEY, ALG, false, ['verify']);
47
+ verified = await crypto.subtle.verify(ALG, pub, outer.SIGNATURE, outer['contents.zip']);
48
+ }
49
+ return { contents: unzipSync(outer['contents.zip']), verified, id: outer.PUBKEY ? await idFromSpki(outer.PUBKEY) : null };
50
+ }
@@ -0,0 +1,15 @@
1
+ import { BINARY_PREFIX } from '../config.js';
2
+
3
+ export const enc = new TextEncoder();
4
+ export const dec = new TextDecoder();
5
+ export const b64 = (u8) => { let s = ''; for (let i = 0; i < u8.length; i += 0x8000) s += String.fromCharCode(...u8.subarray(i, i + 0x8000)); return btoa(s); };
6
+ export const unb64 = (s) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0));
7
+ export const isBinary = (text) => text.startsWith(BINARY_PREFIX);
8
+ export const toBytes = (text) => (isBinary(text) ? unb64(text.slice(BINARY_PREFIX.length)) : enc.encode(text));
9
+ export const looksBinary = (u8) => {
10
+ const n = Math.min(u8.length, 4000);
11
+ for (let i = 0; i < n; i++) if (u8[i] === 0) return true;
12
+ try { new TextDecoder('utf-8', { fatal: true }).decode(u8.subarray(0, n)); return false; } catch { return true; }
13
+ };
14
+ export const fromBytes = (u8) => (looksBinary(u8) ? BINARY_PREFIX + b64(u8) : dec.decode(u8));
15
+ export const kb = (n) => `${(n / 1024).toFixed(1)} KB`;
@@ -0,0 +1,15 @@
1
+ export const el = (tag, attrs = {}, ...children) => {
2
+ const e = Object.assign(document.createElement(tag), attrs);
3
+ for (const c of children) if (c != null) e.append(c);
4
+ return e;
5
+ };
6
+ export function downloadBlob(bytes, name, type = 'application/zip') {
7
+ const url = URL.createObjectURL(new Blob([bytes], { type }));
8
+ el('a', { href: url, download: name }).click();
9
+ setTimeout(() => URL.revokeObjectURL(url), 10000);
10
+ }
11
+ export const pickFile = (accept) => new Promise((resolve) => {
12
+ const input = el('input', { type: 'file', accept });
13
+ input.onchange = () => resolve(input.files[0] || null);
14
+ input.click();
15
+ });
@@ -0,0 +1,18 @@
1
+ // 小さな IndexedDB の key-value(npm のパッケージのキャッシュに使う)
2
+ const open = () => new Promise((resolve, reject) => {
3
+ const r = indexedDB.open('kintone-plugin-ide', 1);
4
+ r.onupgradeneeded = () => r.result.createObjectStore('kv');
5
+ r.onsuccess = () => resolve(r.result);
6
+ r.onerror = () => reject(r.error);
7
+ });
8
+ const tx = async (mode, fn) => {
9
+ const db = await open();
10
+ return new Promise((resolve, reject) => {
11
+ const t = db.transaction('kv', mode);
12
+ const req = fn(t.objectStore('kv'));
13
+ t.oncomplete = () => { resolve(req && req.result); db.close(); };
14
+ t.onerror = () => { reject(t.error); db.close(); };
15
+ });
16
+ };
17
+ export const idbGet = (key) => tx('readonly', (s) => s.get(key)).catch(() => undefined);
18
+ export const idbSet = (key, value) => tx('readwrite', (s) => s.put(value, key)).catch(() => {});
@@ -0,0 +1,14 @@
1
+ import { NODE_MODULES } from '../config.js';
2
+
3
+ export const dirname = (p) => p.split('/').slice(0, -1).join('/');
4
+ export const normalize = (p) => {
5
+ const out = [];
6
+ for (const s of String(p).split('/')) { if (!s || s === '.') continue; if (s === '..') out.pop(); else out.push(s); }
7
+ return out.join('/');
8
+ };
9
+ export const ext = (p) => p.split('.').pop().toLowerCase();
10
+ export const langOf = (p) => ({ ts: 'typescript', tsx: 'typescript', mts: 'typescript', js: 'javascript', jsx: 'javascript', mjs: 'javascript', json: 'json', css: 'css', html: 'html', md: 'markdown', svelte: 'svelte', vue: 'vue', scss: 'scss', sass: 'sass', less: 'less', yaml: 'yaml', yml: 'yaml' })[ext(p)] || 'plaintext';
11
+ // node_modules の中は npm が置くもの。レコードには保存しない
12
+ export const isVendor = (p) => p === 'node_modules' || p.startsWith(NODE_MODULES);
13
+ export const asDir = (p) => normalize(p) + '/';
14
+ export const safeName = (s) => String(s).replace(/[\\/:*?"<>|]/g, '_');
@@ -0,0 +1,5 @@
1
+ import { SETTINGS_KEY } from '../config.js';
2
+
3
+ const DEFAULTS = { prod: false, watch: false, typecheck: true, format: false };
4
+ export const loadSettings = () => { try { return { ...DEFAULTS, ...JSON.parse(localStorage.getItem(SETTINGS_KEY) || '{}') }; } catch { return { ...DEFAULTS }; } };
5
+ export const saveSettings = (s) => { try { localStorage.setItem(SETTINGS_KEY, JSON.stringify(s)); } catch {} };
@@ -0,0 +1,49 @@
1
+ export interface FieldCodes {
2
+ /** 添付ファイル: ソース一式の zip(既定: source_zip) */
3
+ source?: string;
4
+ /** 添付ファイル: 秘密鍵 .ppk(既定: private_key) */
5
+ key?: string;
6
+ /** 添付ファイル: 作ったプラグイン(既定: plugin_zip) */
7
+ zip?: string;
8
+ /** 文字列(1行): プラグインID(既定: plugin_id) */
9
+ id?: string;
10
+ /** 数値: テスト用アプリのID(既定: test_app) */
11
+ testApp?: string;
12
+ /** 前の版のサブテーブル(移行用) */
13
+ legacy?: { files?: string; path?: string; content?: string } | null;
14
+ }
15
+
16
+ export interface SetupOptions {
17
+ /** インストールしてよい kintone のホスト名(例: 'example.cybozu.com')。入っていない環境ではインストールしない */
18
+ installHosts?: string[];
19
+ /** アプリのフィールドコード */
20
+ fields?: FieldCodes;
21
+ /** エディタのテーマ(modern-monaco / Shiki のテーマ名) */
22
+ theme?: string;
23
+ /** 外部ライブラリの URL を差し替える(社内に置いたものを使う場合など) */
24
+ cdn?: Record<string, unknown>;
25
+ }
26
+
27
+ export interface IDEHandle {
28
+ open(): Promise<unknown>;
29
+ config: unknown;
30
+ }
31
+
32
+ /** 詳細画面に「IDEで開く」を出す。カスタマイズから1回呼ぶ */
33
+ export function setup(options?: SetupOptions): IDEHandle;
34
+ export function configure(options?: SetupOptions): unknown;
35
+ export function openIDE(): Promise<unknown>;
36
+
37
+ /** files: パス → 中身(バイナリは "base64:..." )。manifest.json に従ってビルドし contents.zip を作る */
38
+ export function buildPlugin(
39
+ files: Map<string, string>,
40
+ log: { info(t: string): void; ok(t: string): void; warn(t: string): void; error(t: string): void },
41
+ options?: { prod?: boolean },
42
+ ): Promise<{ manifest: any; contentsZip: Uint8Array; outputs: Map<string, Uint8Array> }>;
43
+
44
+ /** 1024bit RSA の秘密鍵(.ppk、PKCS#1 PEM)を作る */
45
+ export function generateKey(): Promise<string>;
46
+ /** contents.zip に署名してプラグインの zip を作る */
47
+ export function pack(contentsZip: Uint8Array, ppk: string): Promise<{ id: string; plugin: Uint8Array }>;
48
+ /** プラグインの zip の署名を確かめて中身を取り出す */
49
+ export function unpack(pluginZip: Uint8Array): Promise<{ contents: Record<string, Uint8Array>; verified: boolean; id: string | null } | null>;