@vibechain/os 0.4.0 → 0.5.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 (93) hide show
  1. package/AGENTS.md +139 -208
  2. package/README.md +131 -54
  3. package/SECURITY.md +45 -20
  4. package/dist/app-client.d.ts +4 -1
  5. package/dist/app-client.js +4 -1
  6. package/dist/app-host.d.ts +111 -9
  7. package/dist/app-host.js +339 -58
  8. package/dist/app-protocol.d.ts +2 -0
  9. package/dist/app-runtime.d.ts +18 -2
  10. package/dist/app-runtime.js +75 -11
  11. package/dist/app-wire.d.ts +194 -0
  12. package/dist/app-wire.js +253 -0
  13. package/dist/browser.d.ts +2 -0
  14. package/dist/browser.js +2 -0
  15. package/dist/bundle.js +6 -6
  16. package/dist/canvas.d.ts +2 -2
  17. package/dist/canvas.js +3 -1
  18. package/dist/check.d.ts +12 -0
  19. package/dist/check.js +167 -0
  20. package/dist/cli-publish.d.ts +24 -0
  21. package/dist/cli-publish.js +288 -0
  22. package/dist/cli-session.d.ts +108 -0
  23. package/dist/cli-session.js +245 -0
  24. package/dist/cli.d.ts +10 -0
  25. package/dist/cli.js +46 -10
  26. package/dist/index.d.ts +5 -0
  27. package/dist/index.js +3 -0
  28. package/dist/listing.d.ts +3 -3
  29. package/dist/listing.js +1 -1
  30. package/dist/loop.d.ts +18 -2
  31. package/dist/loop.js +13 -1
  32. package/dist/manifest.d.ts +90 -4
  33. package/dist/manifest.js +340 -5
  34. package/dist/os.d.ts +56 -0
  35. package/dist/os.js +354 -0
  36. package/dist/preview-parent.d.ts +36 -0
  37. package/dist/preview-parent.js +122 -11
  38. package/dist/preview-ui.js +1 -1
  39. package/dist/preview.js +25 -7
  40. package/dist/redact.d.ts +6 -0
  41. package/dist/redact.js +16 -0
  42. package/dist/runtime-policy.d.ts +20 -0
  43. package/dist/runtime-policy.js +45 -0
  44. package/dist/scaffold.d.ts +13 -2
  45. package/dist/scaffold.js +99 -29
  46. package/dist/submit-notice.d.ts +26 -0
  47. package/dist/submit-notice.js +34 -0
  48. package/dist/templates/plain/game.js +18 -0
  49. package/dist/testing.d.ts +63 -0
  50. package/dist/testing.js +157 -1
  51. package/dist/transport.d.ts +20 -0
  52. package/dist/transport.js +71 -19
  53. package/dist/vibemarket-os.js +1 -0
  54. package/dist/worker.d.ts +18 -0
  55. package/dist/worker.js +34 -0
  56. package/examples/paw-beat/README.md +20 -8
  57. package/examples/paw-beat/cat.ts +665 -89
  58. package/examples/paw-beat/game.ts +162 -28
  59. package/examples/paw-beat/index.html +114 -40
  60. package/examples/paw-beat/main.ts +264 -149
  61. package/examples/paw-beat/music.ts +314 -65
  62. package/examples/paw-beat/stage.ts +560 -0
  63. package/examples/paw-beat/store/icon.png +0 -0
  64. package/examples/paw-beat/store/screenshot-1.webp +0 -0
  65. package/examples/paw-beat/store/screenshot-2.webp +0 -0
  66. package/examples/paw-beat/vibemarket.json +2 -2
  67. package/examples/vibexp-app/README.md +20 -4
  68. package/examples/vibexp-app/index.html +3 -2
  69. package/examples/vibexp-app/plain/game.ts +20 -0
  70. package/examples/vibexp-app/plain/index.html +6 -0
  71. package/examples/vibexp-app/plain/vibemarket.json +17 -0
  72. package/examples/vibexp-app/src/main.ts +46 -31
  73. package/examples/vibexp-app/store/icon.png +0 -0
  74. package/examples/vibexp-app/store/screenshot-1.png +0 -0
  75. package/examples/vibexp-app/three/README.md +21 -0
  76. package/examples/vibexp-app/three/index.html +4 -0
  77. package/examples/vibexp-app/three/src/main.ts +45 -0
  78. package/examples/vibexp-app/three/vibemarket.json +19 -0
  79. package/examples/vibexp-app/vibemarket.json +27 -1
  80. package/package.json +8 -3
  81. package/examples/chonk-stack/card-slice.ts +0 -17
  82. package/examples/chonk-stack/cat3d.ts +0 -57
  83. package/examples/chonk-stack/game.css +0 -174
  84. package/examples/chonk-stack/index.html +0 -32
  85. package/examples/chonk-stack/main.ts +0 -149
  86. package/examples/chonk-stack/model.ts +0 -40
  87. package/examples/chonk-stack/renderer.ts +0 -263
  88. package/examples/chonk-stack/skins.ts +0 -47
  89. package/examples/chonk-stack/vibemarket.json +0 -21
  90. package/examples/collection-room/index.html +0 -3
  91. package/examples/collection-room/main.ts +0 -31
  92. package/examples/collection-room/vibemarket.json +0 -12
  93. package/examples/tsconfig.json +0 -4
package/dist/canvas.js CHANGED
@@ -1,10 +1,12 @@
1
+ import { lifecycleSource } from "./loop.js";
1
2
  /**
2
3
  * Keep a canvas backing store matched to the host surface, with the pixel ratio capped
3
4
  * so a high-density display cannot multiply the fill cost. The canvas is resized (and so
4
5
  * cleared) only when the computed size actually changes. Style the canvas to fill the
5
6
  * app; this sets only its `width` and `height`.
6
7
  */
7
- export function fitCanvas(app, canvas, options = {}, view = window) {
8
+ export function fitCanvas(source, canvas, options = {}, view = window) {
9
+ const app = lifecycleSource(source);
8
10
  const maxRatio = options.maxPixelRatio ?? 2, maxPixels = options.maxPixels ?? 3840 * 2160;
9
11
  if (!Number.isFinite(maxRatio) || maxRatio < 1 || maxRatio > 4)
10
12
  throw Error("maxPixelRatio must be from 1 to 4.");
@@ -0,0 +1,12 @@
1
+ import { APP_BUNDLE_LIMITS } from "./manifest.ts";
2
+ type BundleLimits = {
3
+ readonly [K in keyof typeof APP_BUNDLE_LIMITS]: number;
4
+ };
5
+ export interface CheckReport {
6
+ problems: string[];
7
+ notices: string[];
8
+ bundle: string | null;
9
+ }
10
+ /** `limits` is the store's; a test passes smaller ones. */
11
+ export declare function checkApp(directory: string, limits?: BundleLimits): Promise<CheckReport>;
12
+ export {};
package/dist/check.js ADDED
@@ -0,0 +1,167 @@
1
+ /**
2
+ * `os check [dir]`: every problem with an app's manifest and built folder, one per line, before a submission finds the
3
+ * first. The checks are the server's (VM_OS_APPS_3.md section 11.6): the manifest rules and network origins
4
+ * (`checkManifest`), the listing images, the bundle limits, paths and file types and SVG. Nothing is written.
5
+ */
6
+ import { lstat, opendir } from "node:fs/promises";
7
+ import path from "node:path";
8
+ import { zipSync } from "fflate";
9
+ import { assetType, compareAssetNames, readBoundedAsset } from "./bundle.js";
10
+ import { imageKind, pngSize } from "./listing.js";
11
+ import { APP_BUNDLE_LIMITS, APP_STORE_LIMITS, assetPath, checkManifest, manifestNotices, manifestProblemText, parseManifest } from "./manifest.js";
12
+ const KiB = 1024, MiB = 1024 * 1024;
13
+ const size = (bytes) => bytes >= MiB ? `${(bytes / MiB).toFixed(1)} MiB` : `${Math.ceil(bytes / KiB)} KiB`;
14
+ const missing = (error) => error !== null && typeof error === "object" && "code" in error && error.code === "ENOENT";
15
+ /** Where the built app is: `<dir>/dist` when it exists, else `<dir>` itself (a plain app, or `os check dist`). */
16
+ async function bundleRoot(directory) {
17
+ const dist = path.join(directory, "dist");
18
+ try {
19
+ if ((await lstat(dist)).isDirectory())
20
+ return dist;
21
+ }
22
+ catch (error) {
23
+ if (!missing(error))
24
+ throw error;
25
+ }
26
+ return directory;
27
+ }
28
+ /** The files of a built folder within the bundle limits, and a problem for each file or limit it breaks. */
29
+ async function readFolder(root, problems, limits) {
30
+ const files = new Map(), folded = new Set();
31
+ let entries = 0, expanded = 0, counted = false, over = false;
32
+ const walk = async (relative) => {
33
+ const names = [];
34
+ for await (const entry of await opendir(path.join(root, relative)))
35
+ names.push(entry.name);
36
+ for (const name of names.sort(compareAssetNames)) {
37
+ const file = relative ? `${relative}/${name}` : name;
38
+ if (++entries > limits.files) {
39
+ if (!counted)
40
+ problems.push(`${file}: the bundle has more than ${limits.files.toLocaleString("en-US")} files and folders; remove unused files.`);
41
+ counted = true;
42
+ continue;
43
+ }
44
+ if (!assetPath(file)) {
45
+ problems.push(`${file}: use only ASCII letters, digits, _, - and . in file names, not starting with a dot.`);
46
+ continue;
47
+ }
48
+ if (folded.has(file.toLowerCase())) {
49
+ problems.push(`${file}: another file differs from it only by letter case; rename one.`);
50
+ continue;
51
+ }
52
+ folded.add(file.toLowerCase());
53
+ const stat = await lstat(path.join(root, file));
54
+ if (stat.isSymbolicLink()) {
55
+ problems.push(`${file}: is a symlink; copy the file in instead.`);
56
+ continue;
57
+ }
58
+ if (stat.isDirectory()) {
59
+ await walk(file);
60
+ continue;
61
+ }
62
+ const type = assetType(file);
63
+ if (!stat.isFile() || !type) {
64
+ problems.push(`${file}: VibeStore does not serve this file type; see the file types in the docs.`);
65
+ continue;
66
+ }
67
+ if (type.startsWith("image/svg")) {
68
+ problems.push(`${file}: SVG can carry script and is refused; convert it to PNG or WebP.`);
69
+ continue;
70
+ }
71
+ if (stat.size > limits.file) {
72
+ problems.push(`${file}: is ${size(stat.size)}; a file may be at most ${limits.file / MiB} MiB (stream larger assets from a declared server).`);
73
+ continue;
74
+ }
75
+ if ((expanded += stat.size) > limits.expanded) {
76
+ if (!over)
77
+ problems.push(`${file}: the bundle passes ${limits.expanded / MiB} MiB expanded here; remove or compress files.`);
78
+ over = true;
79
+ continue;
80
+ }
81
+ files.set(file, await readBoundedAsset(path.join(root, file), stat.size));
82
+ }
83
+ };
84
+ await walk("");
85
+ return files;
86
+ }
87
+ /** The listing images, every problem with each. */
88
+ function listingProblems(icon, screenshots, files) {
89
+ const problems = [], limits = APP_STORE_LIMITS, bytes = files.get(icon);
90
+ if (!bytes)
91
+ problems.push(`store.icon: ${icon} is not in the built folder; copy it in (os assets copies the listed store images).`);
92
+ else {
93
+ const dimensions = pngSize(bytes);
94
+ if (!dimensions)
95
+ problems.push(`store.icon: ${icon} is not a PNG file.`);
96
+ else if (dimensions.width !== limits.iconSize || dimensions.height !== limits.iconSize)
97
+ problems.push(`store.icon: ${icon} is ${dimensions.width} x ${dimensions.height}; it must be exactly ${limits.iconSize} x ${limits.iconSize} pixels.`);
98
+ if (bytes.byteLength > limits.iconBytes)
99
+ problems.push(`store.icon: ${icon} is ${size(bytes.byteLength)}; it must be at most ${limits.iconBytes / KiB} KiB.`);
100
+ }
101
+ screenshots.forEach((shot, index) => {
102
+ const image = files.get(shot), where = `store.screenshots[${index}]`;
103
+ if (!image) {
104
+ problems.push(`${where}: ${shot} is not in the built folder; copy it in.`);
105
+ return;
106
+ }
107
+ const expected = { png: "png", jpg: "jpeg", jpeg: "jpeg", webp: "webp" }[shot.slice(shot.lastIndexOf(".") + 1)];
108
+ if (imageKind(image) !== expected)
109
+ problems.push(`${where}: ${shot} is not a ${expected} image; its contents must match its extension.`);
110
+ if (image.byteLength > limits.screenshotBytes)
111
+ problems.push(`${where}: ${shot} is ${size(image.byteLength)}; a screenshot may be at most ${limits.screenshotBytes / MiB} MiB.`);
112
+ });
113
+ return problems;
114
+ }
115
+ /** Reads `vibemarket.json` text, or a problem. */
116
+ async function manifestAt(file, label) {
117
+ let bytes;
118
+ try {
119
+ bytes = await readBoundedAsset(file, 16 * KiB);
120
+ }
121
+ catch (error) {
122
+ if (missing(error))
123
+ return null;
124
+ return { problem: `${label}: must be a file of at most 16 KiB.` };
125
+ }
126
+ try {
127
+ return { value: JSON.parse(new TextDecoder().decode(bytes)) };
128
+ }
129
+ catch (error) {
130
+ return { problem: `${label}: is not valid JSON (${error.message}).` };
131
+ }
132
+ }
133
+ /** `limits` is the store's; a test passes smaller ones. */
134
+ export async function checkApp(directory, limits = APP_BUNDLE_LIMITS) {
135
+ const problems = [], notices = [];
136
+ const project = path.resolve(directory), root = await bundleRoot(project), separate = root !== project;
137
+ const source = await manifestAt(path.join(project, "vibemarket.json"), "vibemarket.json");
138
+ const built = separate ? await manifestAt(path.join(root, "vibemarket.json"), "dist/vibemarket.json") : source;
139
+ const manifest = source ?? built;
140
+ if (!manifest)
141
+ return { problems: ["vibemarket.json: is missing; create it at the root of the app (os init writes one)."], notices, bundle: null };
142
+ if ("problem" in manifest)
143
+ return { problems: [manifest.problem], notices, bundle: null };
144
+ const listed = (list) => list.map(manifestProblemText);
145
+ problems.push(...listed(checkManifest(manifest.value)));
146
+ notices.push(...listed(manifestNotices(manifest.value)));
147
+ if (separate && source && built && "value" in source && "value" in built && JSON.stringify(source.value) !== JSON.stringify(built.value))
148
+ problems.push("dist/vibemarket.json: differs from vibemarket.json; build again (os assets copies it).");
149
+ if (separate && !built)
150
+ problems.push("dist/vibemarket.json: is missing; build again (os assets copies it).");
151
+ const files = await readFolder(root, problems, limits);
152
+ if (problems.length)
153
+ return { problems, notices, bundle: root };
154
+ const parsed = parseManifest(manifest.value);
155
+ if (!files.has(parsed.entry))
156
+ problems.push(`entry: ${parsed.entry} is not in the built folder.`);
157
+ if (parsed.schemaVersion !== 1)
158
+ problems.push(...listingProblems(parsed.store.icon, parsed.store.screenshots, files));
159
+ else
160
+ notices.push("schemaVersion: 1 has no store listing and cannot be submitted to VibeStore; use 3.");
161
+ if (!problems.length) {
162
+ const zip = zipSync(Object.fromEntries([...files].map(([name, bytes]) => [name, bytes])), { level: 6 });
163
+ if (zip.length > limits.archive)
164
+ problems.push(`bundle: the ZIP would be ${size(zip.length)}, over ${limits.archive / MiB} MiB; remove files or stream large assets from a declared server.`);
165
+ }
166
+ return { problems, notices, bundle: root };
167
+ }
@@ -0,0 +1,24 @@
1
+ import { type Fetch, type Seams } from "./cli-session.ts";
2
+ /**
3
+ * `os login`, `os logout`, `os whoami`, `os submit` and `os status` (VibeStore's build contract, section 11). Sign-in is a
4
+ * browser device grant: the CLI prints a code and the page's address, the person approves it on vibechain.com/os/cli while
5
+ * signed in with Steam, and the CLI receives a token that can only submit apps to review and read their own submissions.
6
+ */
7
+ export declare const PUBLISH_COMMANDS: readonly ["login", "logout", "whoami", "submit", "status"];
8
+ export type PublishCommand = typeof PUBLISH_COMMANDS[number];
9
+ export declare const PUBLISH_USAGE: string;
10
+ export interface PublishContext {
11
+ log(line: string): void;
12
+ request: Fetch;
13
+ seams: Seams;
14
+ }
15
+ /** 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. */
16
+ export declare function packForSubmit(directory: string): Promise<{
17
+ manifest: import("./manifest.ts").AppManifestV2 | import("./manifest.ts").AppManifestV3;
18
+ zip: Uint8Array<ArrayBuffer>;
19
+ files: number;
20
+ expanded: number;
21
+ digest: string;
22
+ }>;
23
+ /** Runs one of the sign-in and submission commands. Errors are thrown with the token masked. */
24
+ export declare function runPublish(command: PublishCommand, args: readonly string[], context: PublishContext): Promise<void>;
@@ -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;