@rainyun/cli 0.0.0-stage → 1.0.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.
Files changed (68) hide show
  1. package/README.md +132 -2
  2. package/bin/postinstall.mjs +13 -0
  3. package/bin/rainyun-cli.mjs +13 -0
  4. package/catalog/human-names.json +340 -0
  5. package/catalog/list.openapi.json +354 -0
  6. package/catalog/openapi.json +34531 -0
  7. package/catalog/product-commands.json +332 -0
  8. package/catalog/public.openapi.json +1895 -0
  9. package/docs/AGENT_GUIDE.md +64 -0
  10. package/docs/install.md +44 -0
  11. package/docs/product-lists.md +48 -0
  12. package/docs/rgp.md +77 -0
  13. package/docs/terminal-exec.md +111 -0
  14. package/examples/public-panel.json +1 -0
  15. package/examples/public-rcs-price.json +1 -0
  16. package/examples/rca-terminal-input.json +1 -0
  17. package/examples/rcs-get.json +1 -0
  18. package/examples/rcs-list.json +1 -0
  19. package/examples/rcs-reboot.json +1 -0
  20. package/examples/terminal-controls.ndjson +3 -0
  21. package/examples/terminal-input.json +1 -0
  22. package/node_modules/ws/LICENSE +20 -0
  23. package/node_modules/ws/README.md +539 -0
  24. package/node_modules/ws/browser.js +8 -0
  25. package/node_modules/ws/index.js +22 -0
  26. package/node_modules/ws/lib/buffer-util.js +142 -0
  27. package/node_modules/ws/lib/constants.js +19 -0
  28. package/node_modules/ws/lib/event-target.js +292 -0
  29. package/node_modules/ws/lib/extension.js +203 -0
  30. package/node_modules/ws/lib/limiter.js +55 -0
  31. package/node_modules/ws/lib/permessage-deflate.js +530 -0
  32. package/node_modules/ws/lib/receiver.js +751 -0
  33. package/node_modules/ws/lib/sender.js +610 -0
  34. package/node_modules/ws/lib/stream.js +161 -0
  35. package/node_modules/ws/lib/subprotocol.js +62 -0
  36. package/node_modules/ws/lib/validation.js +152 -0
  37. package/node_modules/ws/lib/websocket-server.js +565 -0
  38. package/node_modules/ws/lib/websocket.js +1471 -0
  39. package/node_modules/ws/package.json +74 -0
  40. package/node_modules/ws/wrapper.mjs +21 -0
  41. package/package.json +29 -4
  42. package/skills/rainyun-cli/SKILL.md +46 -0
  43. package/src/api/catalog.mjs +230 -0
  44. package/src/api/http.mjs +222 -0
  45. package/src/api/request.mjs +178 -0
  46. package/src/api/titles.mjs +9 -0
  47. package/src/auth/commands.mjs +192 -0
  48. package/src/auth/store.mjs +162 -0
  49. package/src/cli.mjs +154 -0
  50. package/src/commands/dispatch.mjs +128 -0
  51. package/src/commands/fields.mjs +77 -0
  52. package/src/commands/products.mjs +209 -0
  53. package/src/commands/rgs.mjs +44 -0
  54. package/src/json.mjs +81 -0
  55. package/src/output/business.mjs +188 -0
  56. package/src/output/discovery.mjs +197 -0
  57. package/src/output/examples.mjs +71 -0
  58. package/src/output/format.mjs +164 -0
  59. package/src/output/help.json +181 -0
  60. package/src/output/help.mjs +334 -0
  61. package/src/rgp/commands.mjs +251 -0
  62. package/src/rgp/input.mjs +144 -0
  63. package/src/rgp/operations.json +625 -0
  64. package/src/rgp/result.mjs +103 -0
  65. package/src/rgp/transfer.mjs +213 -0
  66. package/src/terminal/commands.mjs +155 -0
  67. package/src/terminal/session.mjs +233 -0
  68. package/src/terminal/target.mjs +155 -0
@@ -0,0 +1,178 @@
1
+ import { createReadStream } from 'node:fs';
2
+ import { check, fail, resolve, isObject } from './catalog.mjs';
3
+
4
+ const inputLimit = 8 * 1024 * 1024;
5
+ export const executionFlags = ['yes', 'dry-run', 'base-url', 'timeout', 'max-response-bytes'];
6
+ export const callFlags = [...executionFlags, 'authenticated', 'input', 'path', 'query', 'body', 'file'];
7
+ function parse(text, ctx) {
8
+ try {
9
+ return ctx.jsonParse(text);
10
+ } catch {
11
+ fail('usage', 'input must be a single valid JSON value with unique keys');
12
+ }
13
+ }
14
+ export async function inputFile(file, ctx) {
15
+ const stream = file === '-' ? ctx.stdin : createReadStream(file);
16
+ check(stream, 'stdin unavailable');
17
+ const cancel = () => stream.destroy(new Error('canceled'));
18
+ if (ctx.signal?.aborted) fail('network', 'input reading canceled; API request not sent');
19
+ ctx.signal?.addEventListener('abort', cancel, { once: true });
20
+ try {
21
+ const chunks = [];
22
+ let length = 0;
23
+ for await (const part of stream) {
24
+ const chunk = Buffer.from(part);
25
+ length += chunk.length;
26
+ check(length <= inputLimit, 'JSON input exceeds 8 MiB');
27
+ chunks.push(chunk);
28
+ }
29
+ return new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks));
30
+ } catch (e) {
31
+ if (ctx.signal?.aborted) fail('network', 'input reading canceled; API request not sent');
32
+ fail('usage', e.kind ? e.message : 'cannot read UTF-8 JSON input');
33
+ } finally {
34
+ ctx.signal?.removeEventListener('abort', cancel);
35
+ }
36
+ }
37
+ export async function readInput(flags, ctx) {
38
+ const parts = ['path', 'query', 'body'];
39
+ let input = Object.create(null);
40
+ if ('input' in flags) {
41
+ check(
42
+ !parts.some((k) => Object.hasOwn(flags, k)),
43
+ '--input conflicts with --path, --query and --body'
44
+ );
45
+ input = parse(await inputFile(flags.input, ctx), ctx);
46
+ check(isObject(input), 'input must be an object');
47
+ for (const k of Object.keys(input))
48
+ check([...parts, 'headers'].includes(k), 'unknown input field ' + k);
49
+ } else {
50
+ check(
51
+ parts.reduce((size, k) => size + Buffer.byteLength(flags[k] ?? ''), 0) <= inputLimit,
52
+ 'JSON input exceeds 8 MiB'
53
+ );
54
+ for (const k of parts) if (Object.hasOwn(flags, k)) input[k] = parse(flags[k], ctx);
55
+ }
56
+ for (const k of ['path', 'query', 'headers'])
57
+ if (Object.hasOwn(input, k)) check(isObject(input[k]), k + ' must be a JSON object');
58
+ const files = Object.create(null);
59
+ for (const spec of [].concat(flags.file ?? [])) {
60
+ const pos = spec.indexOf('=');
61
+ check(pos > 0 && pos < spec.length - 1, '--file must be FIELD=PATH');
62
+ const k = spec.slice(0, pos);
63
+ check(!Object.hasOwn(files, k), 'duplicate file field ' + k);
64
+ files[k] = spec.slice(pos + 1);
65
+ }
66
+ return { ...input, files };
67
+ }
68
+ function scalar(v, s, label, ctx) {
69
+ const text = ctx.jsonStringify(v);
70
+ switch (s.type) {
71
+ case 'integer':
72
+ check(/^-?(0|[1-9]\d*)$/.test(text), label + ' must be a JSON integer');
73
+ break;
74
+ case 'number':
75
+ check(/^-?\d/.test(text), label + ' must be a JSON number');
76
+ break;
77
+ case 'string':
78
+ check(typeof v === 'string', label + ' must be a JSON string');
79
+ break;
80
+ case 'boolean':
81
+ check(typeof v === 'boolean', label + ' must be a JSON boolean');
82
+ break;
83
+ default:
84
+ fail('usage', 'unsupported scalar type for ' + label);
85
+ }
86
+ if (s.enum)
87
+ check(
88
+ s.enum.some((e) => ctx.jsonStringify(e) === text),
89
+ label + ' is outside documented enum'
90
+ );
91
+ return typeof v === 'string' ? v : text;
92
+ }
93
+ function validateBody(op, input, ctx) {
94
+ const files = input.files ?? {};
95
+ const fileCount = Object.keys(files).length,
96
+ hasBody = Object.hasOwn(input, 'body');
97
+ const body = resolve(op.request_body);
98
+ if (!body) {
99
+ check(!hasBody && !fileCount, 'operation accepts no body or files');
100
+ return;
101
+ }
102
+ if (body.content['application/json']) {
103
+ check(!fileCount, 'JSON operation does not accept files');
104
+ if (!hasBody) {
105
+ check(!body.required, 'body is required');
106
+ return;
107
+ }
108
+ const shape = resolve(body.content['application/json'].schema) ?? {};
109
+ if (input.body === null) check(shape.nullable, 'body must not be null');
110
+ else if (shape.type === 'object') check(isObject(input.body), 'body must be a JSON object');
111
+ else if (shape.type === 'array') check(Array.isArray(input.body), 'body must be a JSON array');
112
+ else if (shape.type) scalar(input.body, shape, 'body', ctx);
113
+ return;
114
+ }
115
+ check(body.content['multipart/form-data'], 'unsupported request content type');
116
+ check(
117
+ !hasBody && fileCount === 1 && Object.hasOwn(files, 'image') && files.image.trim(),
118
+ 'multipart operation requires --file image=PATH'
119
+ );
120
+ }
121
+ export function prepare(op, input, ctx) {
122
+ const query = new URLSearchParams(),
123
+ headers = { Accept: 'application/json' };
124
+ let path = op.path;
125
+ const params = op.parameters ?? [];
126
+ for (const section of ['path', 'query', 'headers']) {
127
+ const loc = section === 'headers' ? 'header' : section;
128
+ for (const k of Object.keys(input[section] ?? {}))
129
+ check(
130
+ params.some((p) => p.in === loc && p.name === k),
131
+ 'unknown ' + loc + ' parameter ' + k
132
+ );
133
+ }
134
+ for (const p of params) {
135
+ const section = p.in === 'header' ? 'headers' : p.in;
136
+ const fields = input[section] ?? {};
137
+ const label = p.in + '.' + p.name;
138
+ if (!Object.hasOwn(fields, p.name)) {
139
+ check(!p.required && p.in !== 'path', label + ' is required');
140
+ continue;
141
+ }
142
+ const v = fields[p.name],
143
+ shape = resolve(p.schema);
144
+ if (p.in === 'query' && shape.type === 'array') {
145
+ check(Array.isArray(v) && p.explode !== false, label + ' requires an array');
146
+ for (const item of v) query.append(p.name, scalar(item, resolve(shape.items), label, ctx));
147
+ } else if (p.in === 'query' && p.name === 'options' && shape.type === 'string') {
148
+ const options = typeof v === 'string' ? parse(v, ctx) : v;
149
+ check(isObject(options), 'query.options must be a JSON object or a string containing one');
150
+ query.set(p.name, ctx.jsonStringify(options));
151
+ } else {
152
+ const s = scalar(v, shape, label, ctx);
153
+ if (p.in === 'path') {
154
+ check(s !== '' && s !== '.' && s !== '..', label + ' must be a nonempty, non-traversal segment');
155
+ path = path.replaceAll('{' + p.name + '}', () => encodeURIComponent(s));
156
+ } else if (p.in === 'query') query.set(p.name, s);
157
+ else {
158
+ let url;
159
+ try {
160
+ url = new URL(s);
161
+ } catch {}
162
+ check(
163
+ p.name === 'Referer' &&
164
+ /^https?:\/\//i.test(s) &&
165
+ url?.hostname &&
166
+ !url.username &&
167
+ !url.password &&
168
+ !/[\s\\\u0000-\u001f\u007f]/u.test(s),
169
+ 'invalid Referer'
170
+ );
171
+ headers.Referer = s;
172
+ }
173
+ }
174
+ }
175
+ query.sort();
176
+ validateBody(op, input, ctx);
177
+ return { path, query, headers };
178
+ }
@@ -0,0 +1,9 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { fail } from './catalog.mjs';
3
+
4
+ const titles = JSON.parse(readFileSync(new URL('../../catalog/human-names.json', import.meta.url), 'utf8'));
5
+
6
+ export function titleOf(op) {
7
+ if (!Object.hasOwn(titles, op.operation_id)) fail('protocol', '此接口缺少中文操作名');
8
+ return titles[op.operation_id];
9
+ }
@@ -0,0 +1,192 @@
1
+ import { allow, lookup } from '../api/catalog.mjs';
2
+ import { execute } from '../api/http.mjs';
3
+
4
+ export const createKeyUrl = 'https://app.rainyun.com/account/settings/api-key';
5
+
6
+ function failure(kind, message) {
7
+ return Object.assign(new Error(message), { kind });
8
+ }
9
+ function valid(key) {
10
+ return (
11
+ typeof key === 'string' &&
12
+ key.length > 0 &&
13
+ Buffer.byteLength(key) <= 4096 &&
14
+ !/[\s\p{Cc}]/u.test(key)
15
+ );
16
+ }
17
+ const invalidInput = () =>
18
+ failure(
19
+ 'usage',
20
+ '请输入一行 API Key,长度为 1 至 4096 字节,不能含空格或控制字符。'
21
+ );
22
+
23
+ export async function getKey(base, ctx, localKey) {
24
+ let key = ctx.env.RAINYUN_API_KEY;
25
+ if (key) {
26
+ if (!valid(key))
27
+ throw failure('auth', 'Invalid RAINYUN_API_KEY. Fix or clear the environment value.');
28
+ } else {
29
+ if (base && !/^https:\/\/api\.v2\.rainyun\.com(?::443)?\/?$/i.test(String(base))) {
30
+ throw failure(
31
+ 'auth',
32
+ 'Local credentials are restricted to the official API. Supply RAINYUN_API_KEY for a custom gateway.'
33
+ );
34
+ }
35
+ key = localKey ?? (await ctx.store.get('api-key'));
36
+ if (key === null)
37
+ throw failure('auth', 'API Key is not configured. Run rainyun-cli auth login or set RAINYUN_API_KEY.');
38
+ if (!valid(key)) throw failure('auth', 'Invalid local API Key. Run rainyun-cli auth login to replace it.');
39
+ }
40
+ if (!ctx.redactionSecrets.includes(key)) ctx.redactionSecrets.push(key);
41
+ return key;
42
+ }
43
+
44
+ async function saveKey(ctx, interactive, optional = false) {
45
+ const input = ctx.stdin;
46
+ if (interactive && !input.isTTY) {
47
+ throw failure('usage', 'Run auth login in a terminal, or have a trusted host supply --stdin.');
48
+ }
49
+ if (ctx.signal?.aborted) throw failure('network', 'Credential input canceled.');
50
+ const chunks = [];
51
+ const aborted = () => {
52
+ input.destroy(failure('network', 'Credential input canceled.'));
53
+ };
54
+ ctx.signal?.addEventListener('abort', aborted, { once: true });
55
+ try {
56
+ if (interactive) {
57
+ ctx.stderr.write(`创建 API Key:${createKeyUrl}\n密钥将保存在当前用户的明文配置文件中。\n`);
58
+ ctx.stderr.write(optional ? '请输入或粘贴 API Key(直接回车可跳过):' : '请输入或粘贴 API Key(按回车保存):');
59
+ }
60
+ outer: for await (const chunk of input.iterator({ destroyOnReturn: false })) {
61
+ for (const byte of Buffer.from(chunk)) {
62
+ if (interactive && (byte === 13 || byte === 10)) break outer;
63
+ chunks.push(byte);
64
+ if (chunks.length > 4098) throw invalidInput();
65
+ }
66
+ }
67
+ let key;
68
+ try {
69
+ key = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(Uint8Array.from(chunks));
70
+ } catch {
71
+ throw invalidInput();
72
+ }
73
+ if (!interactive) key = key.replace(/\r?\n$/, '');
74
+ if (optional && !key) return false;
75
+ if (!valid(key)) throw invalidInput();
76
+ if (ctx.signal?.aborted) throw failure('network', 'Credential input canceled.');
77
+ await ctx.store.set('api-key', key);
78
+ return true;
79
+ } finally {
80
+ ctx.signal?.removeEventListener('abort', aborted);
81
+ chunks.fill(0);
82
+ if (interactive) input.pause();
83
+ }
84
+ }
85
+
86
+ export async function guideAfterInstall(ctx) {
87
+ const later = `请在自己的终端运行 rainyun-cli auth login。创建 API Key:${createKeyUrl}\n`;
88
+ if (ctx.env.CI || ctx.env.RAIN_CLI_OUTPUT === 'json' || !ctx.stdin.isTTY || !ctx.stderr.isTTY || !ctx.stdout.isTTY) {
89
+ ctx.stderr.write(later);
90
+ return;
91
+ }
92
+ if ((await readCredential(ctx)).value !== null) {
93
+ ctx.stderr.write('雨云 CLI 已配置 API Key。\n');
94
+ return;
95
+ }
96
+ ctx.stderr.write('欢迎使用雨云 CLI。现在可以登录雨云账号。\n');
97
+ const saved = await saveKey(ctx, true, true);
98
+ ctx.stderr.write(saved ? 'API Key 已保存。\n' : later);
99
+ }
100
+
101
+ async function readCredential(ctx) {
102
+ const envKey = ctx.env.RAINYUN_API_KEY;
103
+ if (envKey) {
104
+ if (!valid(envKey)) throw failure('auth', '环境变量 RAINYUN_API_KEY 的格式无效。');
105
+ return { value: envKey, storage: 'process-environment', source: 'environment' };
106
+ }
107
+ const { value, storage } = await ctx.store.read('api-key');
108
+ if (value !== null && !valid(value))
109
+ throw failure('auth', '本机 API Key 格式无效。请运行 rainyun-cli auth login 重新配置。');
110
+ return { value, storage, source: value === null ? 'none' : 'local' };
111
+ }
112
+
113
+ async function status(flags, ctx) {
114
+ const { value, storage, source } = await readCredential(ctx);
115
+ const data = {
116
+ configured: value !== null, source, storage, verified: false,
117
+ environment_override: source === 'environment',
118
+ };
119
+ if (!data.configured)
120
+ return { ...data, login_command: 'rainyun-cli auth login', create_api_key_url: createKeyUrl };
121
+
122
+ const op = lookup('get_user_b5c844ca');
123
+ let response;
124
+ try {
125
+ const result = await execute(op, {}, flags, { ...ctx, getKey: (base) => getKey(base, ctx, value) });
126
+ response = result.response;
127
+ } catch (err) {
128
+ // The account endpoint can return personal data even on failure.
129
+ // Forward its status codes, never its message or response body.
130
+ const { kind, http_status, business_code } = err;
131
+ let message;
132
+ if (business_code === 10005)
133
+ message = '当前 API Key 没有读取账号资料的权限。此接口需要 user:read:self。';
134
+ else if (business_code === 30093)
135
+ message = '账号资料接口未对此 API Key 开放。';
136
+ else if (business_code === 30039)
137
+ message = 'API Key 无效或已过期。请检查当前凭据来源。';
138
+ else if (kind === 'network')
139
+ message = '无法连接账号资料接口,未能验证 API Key。';
140
+ else if (http_status !== undefined)
141
+ message = '未能从账号资料接口验证当前账号。';
142
+ else throw err;
143
+ throw Object.assign(failure(kind, message), { http_status, business_code, details: data });
144
+ }
145
+ const id = response.data?.ID;
146
+ if (!(Number.isSafeInteger(id) || typeof id === 'bigint') || id <= 0)
147
+ throw Object.assign(failure('protocol', '账号资料缺少有效用户 ID。'), { details: data });
148
+ const name = response.data.Name;
149
+ const user = { id, name: typeof name === 'string' && !name.includes(value) ? name : null };
150
+ return { ...data, verified: true, user };
151
+ }
152
+
153
+ export async function auth(args, flags, ctx) {
154
+ if (ctx.signal?.aborted) throw failure('network', 'Credential operation canceled.');
155
+ const [action] = args;
156
+ if (args.length !== 1 || !['status', 'login', 'logout'].includes(action)) {
157
+ throw failure('usage', 'Usage: rainyun-cli auth login [--stdin] | status | logout');
158
+ }
159
+ if (action === 'status') {
160
+ allow(flags, ['base-url', 'timeout', 'max-response-bytes']);
161
+ return { ok: true, data: await status(flags, ctx) };
162
+ }
163
+ allow(flags, action === 'login' ? ['stdin'] : []);
164
+ const envKey = ctx.env.RAINYUN_API_KEY;
165
+ const base = { source: 'none', storage: 'none', verified: false, environment_override: false };
166
+ const override = {
167
+ source: 'environment',
168
+ storage: 'process-environment',
169
+ verified: false,
170
+ environment_override: true,
171
+ };
172
+ let data;
173
+ if (action === 'login') {
174
+ await saveKey(ctx, !flags.stdin);
175
+ data = { ...base, source: 'local', storage: 'config-file', saved: true };
176
+ if (envKey)
177
+ Object.assign(data, {
178
+ source: 'environment',
179
+ environment_override: true,
180
+ environment_format_valid: valid(envKey),
181
+ });
182
+ } else {
183
+ const removed = await ctx.store.remove('api-key');
184
+ data = { ...base, removed, configured: false, remote_revoked: false };
185
+ if (envKey)
186
+ Object.assign(data, override, {
187
+ configured: valid(envKey),
188
+ environment_format_valid: valid(envKey),
189
+ });
190
+ }
191
+ return { ok: true, data };
192
+ }
@@ -0,0 +1,162 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { lstat, mkdir, open, rename, unlink } from 'node:fs/promises';
4
+ import { homedir } from 'node:os';
5
+ import { dirname, isAbsolute, join } from 'node:path';
6
+ import { jsonParse, jsonStringify } from '../json.mjs';
7
+
8
+ function storageError() {
9
+ return Object.assign(
10
+ new Error(
11
+ 'Cannot access the current user’s rainyun-cli configuration. Check the file format and permissions.'
12
+ ),
13
+ { kind: 'auth' }
14
+ );
15
+ }
16
+
17
+ function defaultDirectory(env) {
18
+ if (process.platform === 'win32')
19
+ return join(env.APPDATA || join(homedir(), 'AppData', 'Roaming'), 'rain-cli');
20
+ if (process.platform === 'darwin')
21
+ return join(homedir(), 'Library', 'Application Support', 'rain-cli');
22
+ const base = env.XDG_CONFIG_HOME;
23
+ return join(base && isAbsolute(base) ? base : join(homedir(), '.config'), 'rain-cli');
24
+ }
25
+
26
+ async function readExisting(file) {
27
+ let handle;
28
+ try {
29
+ const info = await lstat(file, { bigint: true });
30
+ if (!info.isFile() || info.size > 65536) throw storageError();
31
+ handle = await open(file, 'r');
32
+ const opened = await handle.stat({ bigint: true });
33
+ if (
34
+ !opened.isFile() ||
35
+ opened.size > 65536n ||
36
+ opened.ino !== info.ino ||
37
+ (info.dev !== 0n && opened.dev !== 0n && info.dev !== opened.dev)
38
+ )
39
+ throw storageError();
40
+ const data = Buffer.alloc(65537);
41
+ let total = 0;
42
+ while (total < data.length) {
43
+ const { bytesRead } = await handle.read(data, total, data.length - total);
44
+ if (!bytesRead) break;
45
+ total += bytesRead;
46
+ }
47
+ if (total === data.length) throw storageError();
48
+ return data.subarray(0, total);
49
+ } catch (err) {
50
+ if (err.code === 'ENOENT') return null;
51
+ throw storageError();
52
+ } finally {
53
+ await handle?.close();
54
+ }
55
+ }
56
+
57
+ // Read pre-0.7 DPAPI files with Windows' own component. Input/output are
58
+ // private pipes. The command line only contains the constant decoder.
59
+ async function readLegacy(file) {
60
+ if (process.platform !== 'win32') return null;
61
+ const contents = await readExisting(file);
62
+ if (!contents) return null;
63
+ const header = Buffer.from('rain-cli-dpapi-v1\0');
64
+ if (!contents.subarray(0, header.length).equals(header)) throw storageError();
65
+ const script = [
66
+ "$ErrorActionPreference='Stop'",
67
+ 'Add-Type -AssemblyName System.Security',
68
+ '$cipher=[Convert]::FromBase64String([Console]::In.ReadToEnd())',
69
+ "$entropy=[Text.Encoding]::UTF8.GetBytes('rain-cli/api-key/v1')",
70
+ '$plain=[Security.Cryptography.ProtectedData]::Unprotect($cipher,$entropy,[Security.Cryptography.DataProtectionScope]::CurrentUser)',
71
+ '[Console]::Write([Convert]::ToBase64String($plain))',
72
+ ].join(';');
73
+ const exe = join(
74
+ process.env.SystemRoot || 'C:\\Windows',
75
+ 'System32',
76
+ 'WindowsPowerShell',
77
+ 'v1.0',
78
+ 'powershell.exe'
79
+ );
80
+ return new Promise((resolve, reject) => {
81
+ const child = execFile(
82
+ exe,
83
+ ['-NoProfile', '-NonInteractive', '-Command', script],
84
+ { windowsHide: true, timeout: 10000, maxBuffer: 65536 },
85
+ (err, out) => {
86
+ if (err) reject(storageError());
87
+ else resolve(Buffer.from(out, 'base64').toString('utf8'));
88
+ }
89
+ );
90
+ child.stdin.on('error', () => reject(storageError()));
91
+ child.stdin.end(contents.subarray(header.length).toString('base64'));
92
+ });
93
+ }
94
+
95
+ export function createStore({ root, env = process.env } = {}) {
96
+ function paths(name) {
97
+ const base = root ?? defaultDirectory(env);
98
+ if (!isAbsolute(base)) throw storageError();
99
+ const account = name === 'api-key';
100
+ if (!account && !/^rca-[1-9]\d*-[1-9]\d*$/.test(name)) throw storageError();
101
+ const dir = account ? base : join(base, 'terminal', name);
102
+ return { file: join(dir, 'config.json'), legacy: join(dir, 'credentials.bin'), account };
103
+ }
104
+ async function read(name) {
105
+ const { file, legacy, account } = paths(name);
106
+ const current = await readExisting(file);
107
+ if (!current) {
108
+ const value = await readLegacy(legacy);
109
+ return { value, storage: value === null ? 'none' : 'windows-dpapi' };
110
+ }
111
+ try {
112
+ const data = jsonParse(new TextDecoder('utf-8', { fatal: true }).decode(current));
113
+ if (!data || typeof data !== 'object' || Array.isArray(data)) throw storageError();
114
+ if (account && typeof data.api_key !== 'string') throw storageError();
115
+ return { value: account ? data.api_key : jsonStringify(data), storage: 'config-file' };
116
+ } catch {
117
+ throw storageError();
118
+ }
119
+ }
120
+ return {
121
+ storage: 'config-file',
122
+ read,
123
+ async get(name) {
124
+ return (await read(name)).value;
125
+ },
126
+ async set(name, value) {
127
+ const { file, account } = paths(name);
128
+ const tmp = join(dirname(file), '.config-' + randomUUID() + '.tmp');
129
+ let handle;
130
+ try {
131
+ const data = account ? { api_key: value } : jsonParse(value);
132
+ const bytes = Buffer.from(jsonStringify(data) + '\n');
133
+ if (bytes.length > 65536) throw storageError();
134
+ await mkdir(dirname(file), { recursive: true, mode: 0o700 });
135
+ handle = await open(tmp, 'wx', 0o600);
136
+ await handle.writeFile(bytes);
137
+ await handle.sync();
138
+ await handle.close();
139
+ handle = undefined;
140
+ await rename(tmp, file);
141
+ } catch {
142
+ throw storageError();
143
+ } finally {
144
+ await handle?.close();
145
+ await unlink(tmp).catch(() => {});
146
+ }
147
+ },
148
+ async remove(name) {
149
+ const { file, legacy } = paths(name);
150
+ let removed = false;
151
+ for (const path of process.platform === 'win32' ? [legacy, file] : [file]) {
152
+ try {
153
+ await unlink(path);
154
+ removed = true;
155
+ } catch (err) {
156
+ if (err.code !== 'ENOENT') throw storageError();
157
+ }
158
+ }
159
+ return removed;
160
+ },
161
+ };
162
+ }