@vibechain/os 0.4.1 → 0.5.1

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 (84) hide show
  1. package/AGENTS.md +80 -48
  2. package/README.md +143 -55
  3. package/SECURITY.md +47 -20
  4. package/dist/app-client.d.ts +4 -1
  5. package/dist/app-client.js +15 -4
  6. package/dist/app-host.d.ts +124 -9
  7. package/dist/app-host.js +395 -57
  8. package/dist/app-protocol.d.ts +17 -1
  9. package/dist/app-protocol.js +12 -0
  10. package/dist/app-runtime.d.ts +18 -2
  11. package/dist/app-runtime.js +75 -11
  12. package/dist/app-wire.d.ts +215 -0
  13. package/dist/app-wire.js +268 -0
  14. package/dist/browser.d.ts +3 -0
  15. package/dist/browser.js +3 -0
  16. package/dist/bundle.js +6 -6
  17. package/dist/canvas.d.ts +2 -2
  18. package/dist/canvas.js +3 -1
  19. package/dist/capture.d.ts +22 -0
  20. package/dist/capture.js +99 -0
  21. package/dist/check.d.ts +12 -0
  22. package/dist/check.js +167 -0
  23. package/dist/cli-publish.d.ts +24 -0
  24. package/dist/cli-publish.js +288 -0
  25. package/dist/cli-session.d.ts +108 -0
  26. package/dist/cli-session.js +245 -0
  27. package/dist/cli.d.ts +10 -0
  28. package/dist/cli.js +46 -10
  29. package/dist/index.d.ts +8 -0
  30. package/dist/index.js +4 -0
  31. package/dist/links.d.ts +15 -0
  32. package/dist/links.js +41 -0
  33. package/dist/listing.d.ts +3 -3
  34. package/dist/listing.js +1 -1
  35. package/dist/loop.d.ts +18 -2
  36. package/dist/loop.js +13 -1
  37. package/dist/manifest.d.ts +90 -4
  38. package/dist/manifest.js +340 -5
  39. package/dist/os.d.ts +63 -0
  40. package/dist/os.js +383 -0
  41. package/dist/preview-parent.d.ts +42 -0
  42. package/dist/preview-parent.js +134 -11
  43. package/dist/preview-ui.js +1 -1
  44. package/dist/preview.js +25 -7
  45. package/dist/redact.d.ts +6 -0
  46. package/dist/redact.js +16 -0
  47. package/dist/runtime-policy.d.ts +20 -0
  48. package/dist/runtime-policy.js +45 -0
  49. package/dist/scaffold.d.ts +13 -2
  50. package/dist/scaffold.js +95 -31
  51. package/dist/submit-notice.d.ts +26 -0
  52. package/dist/submit-notice.js +34 -0
  53. package/dist/templates/plain/game.js +18 -0
  54. package/dist/testing.d.ts +68 -0
  55. package/dist/testing.js +181 -1
  56. package/dist/transport.d.ts +22 -0
  57. package/dist/transport.js +71 -19
  58. package/dist/vibemarket-os.js +1 -0
  59. package/dist/worker.d.ts +18 -0
  60. package/dist/worker.js +34 -0
  61. package/examples/paw-beat/README.md +20 -8
  62. package/examples/paw-beat/cat.ts +665 -89
  63. package/examples/paw-beat/game.ts +162 -28
  64. package/examples/paw-beat/index.html +114 -40
  65. package/examples/paw-beat/main.ts +264 -149
  66. package/examples/paw-beat/music.ts +314 -65
  67. package/examples/paw-beat/stage.ts +560 -0
  68. package/examples/paw-beat/store/icon.png +0 -0
  69. package/examples/paw-beat/store/screenshot-1.webp +0 -0
  70. package/examples/paw-beat/store/screenshot-2.webp +0 -0
  71. package/examples/paw-beat/vibemarket.json +2 -2
  72. package/examples/vibexp-app/README.md +7 -7
  73. package/examples/vibexp-app/index.html +3 -2
  74. package/examples/vibexp-app/plain/game.ts +20 -0
  75. package/examples/vibexp-app/plain/index.html +6 -0
  76. package/examples/vibexp-app/plain/vibemarket.json +17 -0
  77. package/examples/vibexp-app/src/main.ts +46 -31
  78. package/examples/vibexp-app/store/icon.png +0 -0
  79. package/examples/vibexp-app/three/README.md +21 -0
  80. package/examples/vibexp-app/three/index.html +4 -0
  81. package/examples/vibexp-app/three/src/main.ts +45 -0
  82. package/examples/vibexp-app/three/vibemarket.json +19 -0
  83. package/examples/vibexp-app/vibemarket.json +17 -11
  84. package/package.json +6 -2
@@ -0,0 +1,288 @@
1
+ import { zipSync } from "fflate";
2
+ import { readBuiltBundle, compareAssetNames } from "./bundle.js";
3
+ import { APP_BUNDLE_LIMITS } from "./manifest.js";
4
+ import { SUBMIT_CODES, SUBMIT_ERRORS, SUBMIT_PUBLICATION, SUBMIT_TERMS } from "./submit-notice.js";
5
+ import { apiCall, CLI_PAGE, CLI_TOKEN, CLI_TOKEN_ID, credentialPath, deleteCredential, DEVICE_CODE, deviceLabel, messageOf, printable, readCredential, redact, resolveOrigin, TOKEN_ENV, USER_CODE, writeCredential, } from "./cli-session.js";
6
+ /**
7
+ * `os login`, `os logout`, `os whoami`, `os submit` and `os status` (VibeStore's build contract, section 11). Sign-in is a
8
+ * browser device grant: the CLI prints a code and the page's address, the person approves it on vibechain.com/os/cli while
9
+ * signed in with Steam, and the CLI receives a token that can only submit apps to review and read their own submissions.
10
+ */
11
+ export const PUBLISH_COMMANDS = ["login", "logout", "whoami", "submit", "status"];
12
+ export const PUBLISH_USAGE = [
13
+ "os login [--no-browser] [--device <name>]",
14
+ "os whoami",
15
+ "os submit <built-directory> [--yes]",
16
+ "os status [app-id]",
17
+ "os logout",
18
+ " (each also takes --verbose, and --origin http://127.0.0.1:<port> for local development)",
19
+ ].join("\n");
20
+ const MiB = 1024 * 1024;
21
+ /** Every ZIP entry's time, so the same build is the same bytes on every machine and every run (ZIP's earliest date). */
22
+ const ZIP_TIME = new Date(1980, 0, 1, 0, 0, 0);
23
+ const FLAGS = {
24
+ login: ["--no-browser", "--device", "--origin", "--verbose"], logout: ["--origin", "--verbose"], whoami: ["--origin", "--verbose"],
25
+ submit: ["--yes", "--origin", "--verbose"], status: ["--origin", "--verbose"],
26
+ };
27
+ const POSITIONAL = { login: [0, 0], logout: [0, 0], whoami: [0, 0], submit: [1, 1], status: [0, 1] };
28
+ function parseFlags(command, args) {
29
+ const flags = { positional: [], yes: false, noBrowser: false, verbose: false };
30
+ const usage = () => Error(`Usage: ${PUBLISH_USAGE.split("\n").find(line => line.startsWith(`os ${command}`))}`);
31
+ for (let i = 0; i < args.length; i++) {
32
+ const arg = args[i], [name, inline] = arg.startsWith("--") ? arg.split(/=(.*)/s, 2) : [arg, undefined];
33
+ if (!arg.startsWith("--")) {
34
+ flags.positional.push(arg);
35
+ continue;
36
+ }
37
+ if (!FLAGS[command].includes(name))
38
+ throw usage();
39
+ if (name === "--origin" || name === "--device") {
40
+ const value = inline ?? args[++i];
41
+ if (value === undefined || value === "")
42
+ throw usage();
43
+ if (name === "--origin")
44
+ flags.origin = value;
45
+ else
46
+ flags.device = value;
47
+ }
48
+ else if (inline !== undefined)
49
+ throw usage();
50
+ else if (name === "--yes")
51
+ flags.yes = true;
52
+ else if (name === "--no-browser")
53
+ flags.noBrowser = true;
54
+ else
55
+ flags.verbose = true;
56
+ }
57
+ const [min, max] = POSITIONAL[command];
58
+ if (flags.positional.length < min || flags.positional.length > max)
59
+ throw usage();
60
+ return flags;
61
+ }
62
+ const record = (value) => !!value && typeof value === "object" && !Array.isArray(value);
63
+ const when = (iso) => typeof iso === "string" && !Number.isNaN(Date.parse(iso)) ? new Date(iso).toISOString().slice(0, 10) : "?";
64
+ const size = (bytes) => bytes >= MiB ? `${(bytes / MiB).toFixed(1)} MiB` : `${Math.max(1, Math.round(bytes / 1024))} KiB`;
65
+ const NOT_SIGNED_IN = "Not signed in. Run os login.";
66
+ const INVALID = "This sign-in is not valid any more (it expired or was revoked). Run os login.";
67
+ class Session {
68
+ context;
69
+ origin;
70
+ verbose;
71
+ constructor(context, origin, verbose) {
72
+ this.context = context;
73
+ this.origin = origin;
74
+ this.verbose = verbose;
75
+ }
76
+ call(call) {
77
+ return apiCall(this.context.request, this.origin, call, this.verbose ? line => this.context.seams.warn(line) : undefined, () => this.context.seams.now());
78
+ }
79
+ /** The token to use: `VIBEMARKET_OS_TOKEN` (never written anywhere), else the saved sign-in, which must belong to this origin. */
80
+ async token() {
81
+ const env = this.context.seams.storage.env[TOKEN_ENV];
82
+ if (env !== undefined && env !== "") {
83
+ if (!CLI_TOKEN.test(env))
84
+ throw Error(`${TOKEN_ENV} is not a VibeMarket OS CLI token. Copy the token field of a saved sign-in from os login.`);
85
+ return { token: env, source: "env" };
86
+ }
87
+ const saved = await readCredential(this.context.seams.storage);
88
+ if (!saved)
89
+ throw Error(NOT_SIGNED_IN);
90
+ if (saved.origin !== this.origin.origin)
91
+ throw Error(`Your saved sign-in is for ${printable(saved.origin, 100)}. Pass --origin ${printable(saved.origin, 100)}, or run os login.`);
92
+ return { token: saved.token, source: "file" };
93
+ }
94
+ }
95
+ function start(context, flags) {
96
+ const origin = resolveOrigin(flags.origin);
97
+ if (origin.development)
98
+ context.seams.warn(`WARNING: development origin ${origin.origin}. Your CLI sign-in is sent there, not to https://vibechain.com.`);
99
+ return new Session(context, origin, flags.verbose);
100
+ }
101
+ /** An answer that is not the expected success, as one error line. */
102
+ function refusal(answer, what) {
103
+ if (answer.status === 401)
104
+ return Error(INVALID);
105
+ if (answer.status === 403 && record(answer.body) && answer.body.error === "cli_account")
106
+ return Error("This VibeMarket OS account is unavailable.");
107
+ if (answer.status === 429 || answer.status === 503)
108
+ return Error(`${messageOf(answer, "VibeStore is busy.")} Try again${answer.retryAfter ? ` in ${answer.retryAfter} s` : " shortly"}.`);
109
+ return Error(`${what} failed (${answer.status}): ${messageOf(answer, "VibeStore sent an answer the CLI could not read.")}`);
110
+ }
111
+ async function login(context, flags) {
112
+ const session = start(context, flags), { seams, log } = context;
113
+ if (seams.storage.env[TOKEN_ENV])
114
+ seams.warn(`${TOKEN_ENV} is set: whoami, submit and status will keep using it instead of this sign-in.`);
115
+ const device = flags.device === undefined ? deviceLabel(seams.hostname, seams.storage.platform) : printable(flags.device, 64).trim();
116
+ if (!device)
117
+ throw Error("--device needs a name of 1 to 64 characters.");
118
+ const answer = await session.call({ method: "POST", path: "v1/grants", json: { device } });
119
+ const grant = answer.body;
120
+ if (answer.status !== 200 || !record(grant) || typeof grant.deviceCode !== "string" || !DEVICE_CODE.test(grant.deviceCode) || typeof grant.userCode !== "string"
121
+ || !USER_CODE.test(grant.userCode) || typeof grant.expiresIn !== "number" || typeof grant.interval !== "number")
122
+ throw refusal(answer, "Starting a sign-in");
123
+ const deviceCode = grant.deviceCode, page = `${session.origin.origin}${CLI_PAGE}`;
124
+ // the address is built here from the pinned origin; whatever the server names is ignored
125
+ log(`To sign in, open ${page}`);
126
+ log(`sign in with Steam if asked, and enter this code: ${grant.userCode}`);
127
+ log(`Check that the page shows the same code and "${device}". The code expires in ${Math.round(grant.expiresIn / 60)} minutes.`);
128
+ if (!flags.noBrowser)
129
+ seams.openBrowser(page);
130
+ const deadline = seams.now() + Math.min(grant.expiresIn, 900) * 1000;
131
+ let interval = Math.min(Math.max(grant.interval, 1), 60);
132
+ for (;;) {
133
+ await seams.sleep(interval * 1000);
134
+ if (seams.now() >= deadline)
135
+ throw Error("The code expired before it was approved. Run os login again.");
136
+ const poll = await session.call({ method: "POST", path: "v1/token", json: { deviceCode } });
137
+ const body = poll.body, error = record(body) ? body.error : undefined;
138
+ if (poll.status === 200) {
139
+ if (!record(body) || typeof body.token !== "string" || !CLI_TOKEN.test(body.token) || typeof body.tokenId !== "string" || !CLI_TOKEN_ID.test(body.tokenId)
140
+ || typeof body.expiresAt !== "string" || !record(body.account))
141
+ throw Error("VibeStore sent a sign-in the CLI could not read. Run os login again.");
142
+ const account = printable(body.account.name, 64);
143
+ const prior = await readCredential(seams.storage).catch(() => null);
144
+ const file = await writeCredential(seams.storage, { version: 1, origin: session.origin.origin, token: body.token, tokenId: body.tokenId, account, device, expiresAt: body.expiresAt });
145
+ // the previous sign-in on this computer for this origin is revoked, best effort
146
+ if (prior && prior.origin === session.origin.origin && prior.token !== body.token)
147
+ await session.call({ method: "POST", path: "v1/logout", token: prior.token, json: {} }).catch(() => null);
148
+ log(`Signed in to ${session.origin.origin} as ${account}. This sign-in can submit apps and read your submissions until ${when(body.expiresAt)}.`);
149
+ log(`Saved to ${file}`);
150
+ return;
151
+ }
152
+ if (poll.status === 400 && error === "authorization_pending")
153
+ continue;
154
+ if (poll.status === 400 && error === "slow_down") {
155
+ interval = record(body) && typeof body.interval === "number" ? Math.min(Math.max(body.interval, interval + 1), 60) : Math.min(interval + 5, 60);
156
+ continue;
157
+ }
158
+ if (poll.status === 400 && error === "access_denied")
159
+ throw Error("The sign-in was denied in the browser. Nothing was saved.");
160
+ if (poll.status === 400 && error === "expired_token")
161
+ throw Error("The code expired before it was approved. Run os login again.");
162
+ if (poll.status === 429 || poll.status >= 500) {
163
+ interval = Math.min(Math.max(interval + 5, poll.retryAfter ?? 0), 60);
164
+ continue;
165
+ }
166
+ throw refusal(poll, "Signing in");
167
+ }
168
+ }
169
+ async function logout(context, flags) {
170
+ const session = start(context, flags), { seams, log } = context;
171
+ if (seams.storage.env[TOKEN_ENV])
172
+ seams.warn(`${TOKEN_ENV} is set. os logout does not revoke it; revoke it at ${session.origin.origin}${CLI_PAGE} and remove it from your CI secrets.`);
173
+ const saved = await readCredential(seams.storage);
174
+ if (!saved) {
175
+ log("Not signed in on this computer.");
176
+ return;
177
+ }
178
+ if (saved.origin !== session.origin.origin)
179
+ throw Error(`Your saved sign-in is for ${printable(saved.origin, 100)}. Pass --origin ${printable(saved.origin, 100)} to sign it out.`);
180
+ const answer = await session.call({ method: "POST", path: "v1/logout", token: saved.token, json: {} }).catch(() => null);
181
+ // 401: the token was already expired or revoked, so there is nothing left to revoke
182
+ if (!answer || (answer.status !== 200 && answer.status !== 401))
183
+ throw Error(`Could not revoke the sign-in, so nothing was deleted. Try again, or revoke it at ${session.origin.origin}${CLI_PAGE} and delete ${credentialPath(seams.storage)}.`);
184
+ await deleteCredential(seams.storage);
185
+ log(`Signed out. The sign-in was revoked and ${credentialPath(seams.storage)} deleted.`);
186
+ }
187
+ async function me(session, token) {
188
+ const answer = await session.call({ method: "GET", path: "v1/me", token });
189
+ const body = answer.body;
190
+ if (answer.status !== 200 || !record(body) || !record(body.account) || !record(body.token))
191
+ throw refusal(answer, "Reading the sign-in");
192
+ return { account: printable(body.account.name, 64), device: printable(body.token.device, 64), expiresAt: when(body.token.expiresAt), id: printable(body.token.id, 16) };
193
+ }
194
+ async function whoami(context, flags) {
195
+ const session = start(context, flags), { token, source } = await session.token();
196
+ const who = await me(session, token);
197
+ context.log(`Signed in to ${session.origin.origin} as ${who.account} (${source === "env" ? TOKEN_ENV : who.device}). Expires ${who.expiresAt}. Sign-in ${who.id}.`);
198
+ }
199
+ /** The build as VibeStore's Submit tab takes it: the same checks as os pack, then a ZIP whose bytes depend only on the files. */
200
+ export async function packForSubmit(directory) {
201
+ const bundle = await readBuiltBundle(directory), manifest = bundle.manifest;
202
+ if (manifest.schemaVersion === 1)
203
+ throw Error("VibeStore accepts only schema version 2 and 3 manifests. See https://vibechain.com/os/docs#manifest.");
204
+ const files = {};
205
+ for (const name of Object.keys(bundle.files).sort(compareAssetNames))
206
+ files[name] = [bundle.files[name], { mtime: ZIP_TIME }];
207
+ const zip = zipSync(files, { level: 6, mtime: ZIP_TIME });
208
+ if (zip.length > APP_BUNDLE_LIMITS.archive)
209
+ throw Error(`The ZIP would be ${size(zip.length)}, over VibeStore's ${APP_BUNDLE_LIMITS.archive / MiB} MiB. ${SUBMIT_ERRORS["too-large"][1]}`);
210
+ return { manifest, zip, files: Object.keys(bundle.files).length, expanded: bundle.expandedBytes, digest: bundle.digest };
211
+ }
212
+ async function submit(context, flags) {
213
+ const session = start(context, flags), { seams, log } = context;
214
+ const { token } = await session.token();
215
+ const built = await packForSubmit(flags.positional[0]);
216
+ const who = await me(session, token);
217
+ const { manifest } = built;
218
+ log(`App: ${manifest.id} ${manifest.version} (${printable(manifest.name, 60)})`);
219
+ log(`Files: ${built.files}, ${size(built.expanded)} expanded, ${size(built.zip.length)} zipped`);
220
+ log(`Digest: ${built.digest} (version key ${built.digest.slice(0, 32)})`);
221
+ log(`Account: ${who.account} on ${session.origin.origin}`);
222
+ log("");
223
+ log(`${SUBMIT_PUBLICATION.title} ${SUBMIT_PUBLICATION.text}`);
224
+ log(`Read the ${SUBMIT_TERMS.label} before you submit: ${SUBMIT_TERMS.url}`);
225
+ log("");
226
+ if (!flags.yes) {
227
+ if (!seams.interactive)
228
+ throw Error("Nothing was submitted. Pass --yes to submit without a question (there is no terminal to ask in).");
229
+ const reply = (await seams.ask(`Submit ${manifest.id} ${manifest.version} for review? [y/N] `)).trim();
230
+ if (!/^y(?:es)?$/i.test(reply)) {
231
+ log("Nothing was submitted.");
232
+ return;
233
+ }
234
+ }
235
+ const answer = await session.call({ method: "POST", path: "v1/submit", token, zip: built.zip });
236
+ const body = answer.body;
237
+ if (answer.status === 200 && record(body) && record(body.submission)) {
238
+ const sub = body.submission, state = printable(sub.state, 20);
239
+ log(body.duplicate === true ? `This exact build of ${manifest.id} ${manifest.version} was already submitted. Its state: ${state}.` : `Submitted ${manifest.id} ${manifest.version}: ${state}.`);
240
+ log(`Follow its review with: os status ${manifest.id}`);
241
+ return;
242
+ }
243
+ const refused = record(body) && SUBMIT_CODES.includes(body.code) ? body : null;
244
+ if (!refused)
245
+ throw refusal(answer, "Submitting");
246
+ const code = refused.code, [meaning, fix] = SUBMIT_ERRORS[code], detail = printable(refused.detail, 300);
247
+ throw Error([`VibeStore refused the submission (${code}): ${messageOf(answer, meaning)}`, ...(detail ? [`Details: ${detail}`] : []), `What it means: ${meaning}`, `Fix: ${fix}`].join("\n"));
248
+ }
249
+ async function status(context, flags) {
250
+ const session = start(context, flags), { token } = await session.token();
251
+ const answer = await session.call({ method: "GET", path: "v1/submissions", token });
252
+ const body = answer.body;
253
+ if (answer.status !== 200 || !record(body) || !Array.isArray(body.submissions))
254
+ throw refusal(answer, "Reading your submissions");
255
+ const filter = flags.positional[0];
256
+ const rows = body.submissions.filter(record).filter(row => filter === undefined || row.appId === filter || row.versionKey === filter);
257
+ if (!rows.length) {
258
+ context.log(filter === undefined ? "Nothing submitted yet." : `No submissions for ${printable(filter, 60)}.`);
259
+ return;
260
+ }
261
+ for (const row of rows) {
262
+ const review = record(row.review) ? printable(row.review.note, 300) : "";
263
+ context.log(`${printable(row.appId, 60)} ${printable(row.version, 50)} ${printable(row.state, 20)}${row.live === true ? " live" : ""} submitted ${when(row.submittedAt)} ${printable(row.versionKey, 32)}`);
264
+ if (review)
265
+ context.log(` Reviewer: ${review}`);
266
+ }
267
+ }
268
+ /** Runs one of the sign-in and submission commands. Errors are thrown with the token masked. */
269
+ export async function runPublish(command, args, context) {
270
+ const flags = parseFlags(command, args);
271
+ try {
272
+ if (command === "login")
273
+ await login(context, flags);
274
+ else if (command === "logout")
275
+ await logout(context, flags);
276
+ else if (command === "whoami")
277
+ await whoami(context, flags);
278
+ else if (command === "submit")
279
+ await submit(context, flags);
280
+ else
281
+ await status(context, flags);
282
+ }
283
+ catch (error) {
284
+ const secret = context.seams.storage.env[TOKEN_ENV];
285
+ // the whole token and its random part (a server or proxy may echo either)
286
+ throw Error(redact(error instanceof Error ? error.message : String(error), secret ? [secret, secret.slice(9)] : []));
287
+ }
288
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * The CLI's sign-in plumbing (VibeStore's build contract, section 11): where the token lives, which host it may go to, how a
3
+ * request is made and what an error may print. The commands are in cli-publish.ts.
4
+ *
5
+ * The token is a bearer secret. It is read only from the credentials file or `VIBEMARKET_OS_TOKEN`, never from an argument;
6
+ * it is sent only in an Authorization header, only to the origin that issued it, never across a redirect; and every line
7
+ * this CLI prints about a request passes `redact`.
8
+ */
9
+ export declare const DEFAULT_ORIGIN = "https://vibechain.com";
10
+ export declare const TOKEN_ENV = "VIBEMARKET_OS_TOKEN";
11
+ /** The CLI token's only shape (vibemarket/steam/os-cli.ts `OS_CLI_TOKEN`; a website test binds the two). */
12
+ export declare const CLI_TOKEN: RegExp;
13
+ export declare const CLI_TOKEN_ID: RegExp;
14
+ export declare const DEVICE_CODE: RegExp;
15
+ export declare const USER_CODE: RegExp;
16
+ export declare const CLI_PAGE = "/os/cli";
17
+ export declare const API_PREFIX = "/api/os/cli/";
18
+ export { printable, redact } from "./redact.ts";
19
+ /** A device label as the backend accepts it (1 to 64 characters, no control or format characters). */
20
+ export declare function deviceLabel(hostname: string, platform: string): string;
21
+ export interface Origin {
22
+ origin: string;
23
+ development: boolean;
24
+ }
25
+ /** vibechain.com, or with `--origin` a loopback HTTP server for local development only. */
26
+ export declare function resolveOrigin(flag: string | undefined): Origin;
27
+ export interface Credential {
28
+ version: 1;
29
+ origin: string;
30
+ token: string;
31
+ tokenId: string;
32
+ account: string;
33
+ device: string;
34
+ expiresAt: string;
35
+ }
36
+ export interface Storage {
37
+ platform: NodeJS.Platform;
38
+ home: string;
39
+ env: Readonly<Record<string, string | undefined>>;
40
+ uid: number | undefined;
41
+ }
42
+ /** `$XDG_CONFIG_HOME/vibemarket-os` when it is absolute; else the platform's per-user config directory. Never the project. */
43
+ export declare function configDirectory(storage: Storage): string;
44
+ export declare const credentialPath: (storage: Storage) => string;
45
+ /** The saved sign-in, or null when there is none. Refuses a file anyone else could read, a link, or a malformed file. */
46
+ export declare function readCredential(storage: Storage): Promise<Credential | null>;
47
+ /** Saves the sign-in: the directory made 0700, the file written to a new name with O_EXCL and mode 0600, then renamed over. */
48
+ export declare function writeCredential(storage: Storage, credential: Credential): Promise<string>;
49
+ /** Deletes the saved sign-in; true when there was one. */
50
+ export declare function deleteCredential(storage: Storage): Promise<boolean>;
51
+ export type Fetch = (url: URL, init: RequestInit) => Promise<Response>;
52
+ export interface Answer {
53
+ status: number;
54
+ body: unknown;
55
+ retryAfter: number | null;
56
+ }
57
+ export interface Call {
58
+ method: "GET" | "POST";
59
+ path: string;
60
+ token?: string;
61
+ json?: unknown;
62
+ zip?: Uint8Array;
63
+ }
64
+ /**
65
+ * One request to `<origin>/api/os/cli/<path>`. Redirects are never followed (`redirect: "manual"`, and any 3xx is an error),
66
+ * so the Authorization header cannot reach another host. `verbose` lines name the method, URL and status only.
67
+ */
68
+ export declare function apiCall(fetcher: Fetch, origin: Origin, call: Call, verbose?: (line: string) => void, now?: () => number): Promise<Answer>;
69
+ /** The server's `message` from an error answer, as safe text, or the fallback. */
70
+ export declare function messageOf(answer: Answer, fallback: string): string;
71
+ /** What the commands need from the machine; tests pass their own. */
72
+ export interface Seams {
73
+ storage: Storage;
74
+ hostname: string;
75
+ /** a person can answer questions (stdin and stderr are terminals) */
76
+ interactive: boolean;
77
+ ask(question: string): Promise<string>;
78
+ /** opens a URL this CLI built from its pinned origin; never a URL from a server */
79
+ openBrowser(url: string): void;
80
+ sleep(ms: number): Promise<void>;
81
+ now(): number;
82
+ /** stderr */
83
+ warn(line: string): void;
84
+ }
85
+ /** The platform opener with a fixed argument list (no shell). */
86
+ export declare function openerCommand(platform: NodeJS.Platform, url: string): [string, string[]];
87
+ type Spawn = (command: string, args: readonly string[], options: {
88
+ stdio: "ignore";
89
+ detached: true;
90
+ shell: false;
91
+ }) => {
92
+ on(event: "error", listener: () => void): unknown;
93
+ unref(): void;
94
+ };
95
+ export interface Terminal {
96
+ stdin: NodeJS.ReadableStream & {
97
+ isTTY?: boolean;
98
+ };
99
+ stderr: NodeJS.WritableStream & {
100
+ isTTY?: boolean;
101
+ };
102
+ }
103
+ export declare function systemSeams(env: Readonly<Record<string, string | undefined>>, machine: {
104
+ platform: NodeJS.Platform;
105
+ home: string;
106
+ hostname: string;
107
+ uid: number | undefined;
108
+ }, terminal: Terminal, spawn?: Spawn): Seams;
@@ -0,0 +1,245 @@
1
+ import { spawn as spawnProcess } from "node:child_process";
2
+ import { randomBytes } from "node:crypto";
3
+ import { constants } from "node:fs";
4
+ import { lstat, mkdir, open, rename, unlink } from "node:fs/promises";
5
+ import path from "node:path";
6
+ import { createInterface } from "node:readline";
7
+ import { printable, redact } from "./redact.js";
8
+ /**
9
+ * The CLI's sign-in plumbing (VibeStore's build contract, section 11): where the token lives, which host it may go to, how a
10
+ * request is made and what an error may print. The commands are in cli-publish.ts.
11
+ *
12
+ * The token is a bearer secret. It is read only from the credentials file or `VIBEMARKET_OS_TOKEN`, never from an argument;
13
+ * it is sent only in an Authorization header, only to the origin that issued it, never across a redirect; and every line
14
+ * this CLI prints about a request passes `redact`.
15
+ */
16
+ export const DEFAULT_ORIGIN = "https://vibechain.com";
17
+ export const TOKEN_ENV = "VIBEMARKET_OS_TOKEN";
18
+ /** The CLI token's only shape (vibemarket/steam/os-cli.ts `OS_CLI_TOKEN`; a website test binds the two). */
19
+ export const CLI_TOKEN = /^vmos_cli_[A-Za-z0-9_-]{43}$/;
20
+ export const CLI_TOKEN_ID = /^[a-f0-9]{16}$/;
21
+ export const DEVICE_CODE = /^[A-Za-z0-9_-]{43}$/;
22
+ export const USER_CODE = /^[BCDFGHJKLMNPQRSTVWXZ]{4}-[BCDFGHJKLMNPQRSTVWXZ]{4}$/;
23
+ export const CLI_PAGE = "/os/cli";
24
+ export const API_PREFIX = "/api/os/cli/";
25
+ const CREDENTIALS = "credentials.json", CREDENTIALS_MAX = 4096, ANSWER_MAX = 1024 * 1024;
26
+ // ---------- what may be printed ----------
27
+ export { printable, redact } from "./redact.js";
28
+ /** A device label as the backend accepts it (1 to 64 characters, no control or format characters). */
29
+ export function deviceLabel(hostname, platform) {
30
+ // never empty: the platform in parentheses is always there
31
+ return printable(`${hostname.slice(0, 48)} (${platform})`).replace(/\s+/g, " ").trim().slice(0, 64);
32
+ }
33
+ /** vibechain.com, or with `--origin` a loopback HTTP server for local development only. */
34
+ export function resolveOrigin(flag) {
35
+ if (flag === undefined || flag === DEFAULT_ORIGIN)
36
+ return { origin: DEFAULT_ORIGIN, development: false };
37
+ let url = null;
38
+ try {
39
+ url = new URL(flag);
40
+ }
41
+ catch { /* refused below */ }
42
+ if (!url || url.protocol !== "http:" || !["127.0.0.1", "localhost"].includes(url.hostname) || !url.port || url.username || url.password
43
+ || url.pathname !== "/" || url.search || url.hash || flag.replace(/\/$/, "") !== url.origin)
44
+ throw Error("--origin accepts only http://127.0.0.1:<port> or http://localhost:<port>, for local development. Without it the CLI talks to https://vibechain.com.");
45
+ return { origin: url.origin, development: true };
46
+ }
47
+ /** `$XDG_CONFIG_HOME/vibemarket-os` when it is absolute; else the platform's per-user config directory. Never the project. */
48
+ export function configDirectory(storage) {
49
+ const { env, home, platform } = storage;
50
+ const xdg = env.XDG_CONFIG_HOME, appData = env.APPDATA;
51
+ if (xdg && path.isAbsolute(xdg))
52
+ return path.join(xdg, "vibemarket-os");
53
+ if (platform === "darwin")
54
+ return path.join(home, "Library", "Application Support", "vibemarket-os");
55
+ // node:path is path.win32 on Windows itself
56
+ if (platform === "win32")
57
+ return path.join(appData && path.win32.isAbsolute(appData) ? appData : path.join(home, "AppData", "Roaming"), "vibemarket-os");
58
+ return path.join(home, ".config", "vibemarket-os");
59
+ }
60
+ export const credentialPath = (storage) => path.join(configDirectory(storage), CREDENTIALS);
61
+ /** node:fs rejects with ErrnoException objects only. */
62
+ const code = (error) => error.code;
63
+ /** O_NOFOLLOW where the platform has it (Windows does not: undefined | 0 is 0). */
64
+ const NOFOLLOW = constants.O_NOFOLLOW | 0;
65
+ /**
66
+ * POSIX: the directory and file must be this user's, not symlinks, and closed to group and others. Windows has no such mode
67
+ * bits (Node reports 0o666); the file relies on the per-user ACL of %APPDATA%.
68
+ */
69
+ function guard(storage, stat, name, mode) {
70
+ if (storage.platform === "win32")
71
+ return;
72
+ if ((stat.mode & 0o077) !== 0)
73
+ throw Error(`${name} can be read by other users. Fix it with: chmod ${mode} '${name}' (or run os logout and os login again).`);
74
+ if (storage.uid !== undefined && stat.uid !== storage.uid)
75
+ throw Error(`${name} belongs to another user. Remove it and run os login again.`);
76
+ }
77
+ async function guardDirectory(storage, directory) {
78
+ let stat;
79
+ try {
80
+ stat = await lstat(directory);
81
+ }
82
+ catch (error) {
83
+ if (code(error) === "ENOENT")
84
+ return false;
85
+ throw error;
86
+ }
87
+ if (stat.isSymbolicLink() || !stat.isDirectory())
88
+ throw Error(`${directory} must be a directory, not a link or a file. Remove it and run os login again.`);
89
+ guard(storage, stat, directory, "700");
90
+ return true;
91
+ }
92
+ const record = (value) => !!value && typeof value === "object" && !Array.isArray(value);
93
+ /** The saved sign-in, or null when there is none. Refuses a file anyone else could read, a link, or a malformed file. */
94
+ export async function readCredential(storage) {
95
+ const directory = configDirectory(storage), file = credentialPath(storage);
96
+ if (!await guardDirectory(storage, directory))
97
+ return null;
98
+ let handle;
99
+ try {
100
+ handle = await open(file, constants.O_RDONLY | NOFOLLOW);
101
+ }
102
+ catch (error) {
103
+ if (code(error) === "ENOENT")
104
+ return null;
105
+ if (code(error) === "ELOOP")
106
+ throw Error(`${file} is a link. Remove it and run os login again.`);
107
+ throw error;
108
+ }
109
+ try {
110
+ const stat = await handle.stat();
111
+ if (!stat.isFile() || stat.size > CREDENTIALS_MAX)
112
+ throw Error(`${file} is not a saved sign-in. Remove it and run os login again.`);
113
+ guard(storage, stat, file, "600");
114
+ let value = null;
115
+ try {
116
+ value = JSON.parse(await handle.readFile("utf8"));
117
+ }
118
+ catch { /* refused below */ }
119
+ if (!record(value) || value.version !== 1 || typeof value.origin !== "string" || typeof value.token !== "string" || !CLI_TOKEN.test(value.token)
120
+ || typeof value.tokenId !== "string" || typeof value.account !== "string" || typeof value.device !== "string" || typeof value.expiresAt !== "string")
121
+ throw Error(`${file} is damaged. Run os logout, then os login.`);
122
+ return { version: 1, origin: value.origin, token: value.token, tokenId: value.tokenId, account: value.account, device: value.device, expiresAt: value.expiresAt };
123
+ }
124
+ finally {
125
+ await handle.close();
126
+ }
127
+ }
128
+ /** Saves the sign-in: the directory made 0700, the file written to a new name with O_EXCL and mode 0600, then renamed over. */
129
+ export async function writeCredential(storage, credential) {
130
+ const directory = configDirectory(storage), file = credentialPath(storage);
131
+ await mkdir(directory, { recursive: true, mode: 0o700 });
132
+ await guardDirectory(storage, directory);
133
+ const temporary = path.join(directory, `.credentials-${randomBytes(8).toString("hex")}.tmp`);
134
+ const handle = await open(temporary, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | NOFOLLOW, 0o600);
135
+ try {
136
+ try {
137
+ await handle.writeFile(`${JSON.stringify(credential)}\n`, "utf8");
138
+ await handle.sync();
139
+ }
140
+ finally {
141
+ await handle.close();
142
+ }
143
+ await rename(temporary, file);
144
+ }
145
+ catch (error) {
146
+ await unlink(temporary).catch(() => undefined);
147
+ throw error;
148
+ }
149
+ return file;
150
+ }
151
+ /** Deletes the saved sign-in; true when there was one. */
152
+ export async function deleteCredential(storage) {
153
+ try {
154
+ await unlink(credentialPath(storage));
155
+ return true;
156
+ }
157
+ catch (error) {
158
+ if (code(error) === "ENOENT")
159
+ return false;
160
+ throw error;
161
+ }
162
+ }
163
+ /**
164
+ * One request to `<origin>/api/os/cli/<path>`. Redirects are never followed (`redirect: "manual"`, and any 3xx is an error),
165
+ * so the Authorization header cannot reach another host. `verbose` lines name the method, URL and status only.
166
+ */
167
+ export async function apiCall(fetcher, origin, call, verbose, now = Date.now) {
168
+ const url = new URL(`${API_PREFIX}${call.path}`, origin.origin);
169
+ const headers = { Accept: "application/json" };
170
+ if (call.token)
171
+ headers.Authorization = `Bearer ${call.token}`;
172
+ let body;
173
+ if (call.zip) {
174
+ headers["Content-Type"] = "application/zip";
175
+ body = new Blob([call.zip]);
176
+ }
177
+ else if (call.json !== undefined) {
178
+ headers["Content-Type"] = "application/json";
179
+ body = JSON.stringify(call.json);
180
+ }
181
+ const started = now(), secrets = call.token ? [call.token, call.token.slice(9)] : [];
182
+ verbose?.(`→ ${call.method} ${url.href}${call.token ? " (Authorization: Bearer vmos_cli_[redacted])" : ""}`);
183
+ let response;
184
+ try {
185
+ response = await fetcher(url, { method: call.method, headers, body, redirect: "manual", cache: "no-store" });
186
+ }
187
+ catch (error) {
188
+ throw Error(redact(`Could not reach ${origin.origin}: ${error instanceof Error ? error.message : "network error"}.`, secrets));
189
+ }
190
+ verbose?.(`← ${response.status} (${now() - started} ms)`);
191
+ if ((response.status >= 300 && response.status < 400) || response.type === "opaqueredirect") {
192
+ await response.body?.cancel();
193
+ throw Error(`${origin.origin} answered with a redirect. The CLI does not follow redirects, so nothing was sent anywhere else.`);
194
+ }
195
+ const text = await readBounded(response);
196
+ let value = null;
197
+ try {
198
+ value = text ? JSON.parse(text) : null;
199
+ }
200
+ catch { /* not JSON: null */ }
201
+ const retry = Number(response.headers.get("retry-after"));
202
+ return { status: response.status, body: value, retryAfter: Number.isFinite(retry) && retry > 0 ? Math.min(retry, 300) : null };
203
+ }
204
+ async function readBounded(response) {
205
+ const bytes = new Uint8Array(await response.arrayBuffer());
206
+ return new TextDecoder().decode(bytes.byteLength > ANSWER_MAX ? bytes.subarray(0, 0) : bytes);
207
+ }
208
+ /** The server's `message` from an error answer, as safe text, or the fallback. */
209
+ export function messageOf(answer, fallback) {
210
+ const message = record(answer.body) ? printable(answer.body.message, 300) : "";
211
+ return message || fallback;
212
+ }
213
+ /** The platform opener with a fixed argument list (no shell). */
214
+ export function openerCommand(platform, url) {
215
+ if (platform === "darwin")
216
+ return ["open", [url]];
217
+ if (platform === "win32")
218
+ return ["rundll32", ["url.dll,FileProtocolHandler", url]];
219
+ return ["xdg-open", [url]];
220
+ }
221
+ export function systemSeams(env, machine, terminal, spawn = spawnProcess) {
222
+ return {
223
+ storage: { platform: machine.platform, home: machine.home, env, uid: machine.uid },
224
+ hostname: machine.hostname,
225
+ interactive: terminal.stdin.isTTY === true && terminal.stderr.isTTY === true,
226
+ ask: question => new Promise(resolve => {
227
+ const lines = createInterface({ input: terminal.stdin, output: terminal.stderr });
228
+ // resolve before close: closing emits "close", which answers "" to a question nobody answered
229
+ lines.question(question, answer => { resolve(answer); lines.close(); });
230
+ lines.once("close", () => resolve(""));
231
+ }),
232
+ openBrowser: url => {
233
+ const [command, args] = openerCommand(machine.platform, url);
234
+ try {
235
+ const child = spawn(command, args, { stdio: "ignore", detached: true, shell: false });
236
+ child.on("error", () => undefined);
237
+ child.unref();
238
+ }
239
+ catch { /* the URL is printed anyway */ }
240
+ },
241
+ sleep: ms => new Promise(resolve => { setTimeout(resolve, ms); }),
242
+ now: () => Date.now(),
243
+ warn: line => { terminal.stderr.write(`${line}\n`); },
244
+ };
245
+ }
package/dist/cli.d.ts CHANGED
@@ -1,3 +1,11 @@
1
+ import type { Seams } from "./cli-session.ts";
2
+ /** The facts about this machine and process the real seams need; `proc` is injectable for tests. */
3
+ export declare function machineOf(proc: Pick<NodeJS.Process, "platform" | "getuid">, home: string, host: string): {
4
+ platform: NodeJS.Platform;
5
+ home: string;
6
+ hostname: string;
7
+ uid: number | undefined;
8
+ };
1
9
  export interface CliSignals {
2
10
  once(signal: "SIGINT" | "SIGTERM", handler: () => void): unknown;
3
11
  off(signal: "SIGINT" | "SIGTERM", handler: () => void): unknown;
@@ -14,6 +22,8 @@ export interface CliRuntime {
14
22
  log(line: string): void;
15
23
  readonly signals: CliSignals;
16
24
  request(url: URL, init: RequestInit): Promise<Response>;
25
+ /** The machine the sign-in and submission commands use (cli-session.ts); the real one when absent. */
26
+ readonly seams?: Seams;
17
27
  }
18
28
  export declare function createCliRuntime(host?: CliProcess, log?: (line: string) => void, request?: typeof fetch): CliRuntime;
19
29
  /** Passive dispatcher: tests and other tools provide owned process boundaries. */