@vibechain/os 0.0.0-stage → 0.1.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 (57) hide show
  1. package/AGENTS.md +217 -0
  2. package/LICENSE +21 -0
  3. package/README.md +59 -2
  4. package/SECURITY.md +35 -0
  5. package/dist/app-client.d.ts +4 -0
  6. package/dist/app-client.js +47 -0
  7. package/dist/app-host.d.ts +28 -0
  8. package/dist/app-host.js +196 -0
  9. package/dist/app-protocol.d.ts +62 -0
  10. package/dist/app-protocol.js +111 -0
  11. package/dist/app-runtime.d.ts +2 -0
  12. package/dist/app-runtime.js +11 -0
  13. package/dist/bin.d.ts +2 -0
  14. package/dist/bin.js +3 -0
  15. package/dist/bundle.d.ts +10 -0
  16. package/dist/bundle.js +82 -0
  17. package/dist/channel.d.ts +1 -0
  18. package/dist/channel.js +1 -0
  19. package/dist/cli.d.ts +21 -0
  20. package/dist/cli.js +90 -0
  21. package/dist/client.d.ts +4 -0
  22. package/dist/client.js +34 -0
  23. package/dist/index.d.ts +7 -0
  24. package/dist/index.js +4 -0
  25. package/dist/inventory.d.ts +12 -0
  26. package/dist/inventory.js +54 -0
  27. package/dist/manifest.d.ts +24 -0
  28. package/dist/manifest.js +32 -0
  29. package/dist/preview-parent.d.ts +1 -0
  30. package/dist/preview-parent.js +51 -0
  31. package/dist/preview-ui.js +1 -0
  32. package/dist/preview.d.ts +7 -0
  33. package/dist/preview.js +77 -0
  34. package/dist/scaffold.d.ts +4 -0
  35. package/dist/scaffold.js +64 -0
  36. package/dist/transport.d.ts +17 -0
  37. package/dist/transport.js +102 -0
  38. package/dist/types.d.ts +97 -0
  39. package/dist/types.js +1 -0
  40. package/examples/chonk-stack/card-slice.ts +17 -0
  41. package/examples/chonk-stack/cat3d.ts +57 -0
  42. package/examples/chonk-stack/game.css +174 -0
  43. package/examples/chonk-stack/index.html +32 -0
  44. package/examples/chonk-stack/main.ts +149 -0
  45. package/examples/chonk-stack/model.ts +40 -0
  46. package/examples/chonk-stack/renderer.ts +263 -0
  47. package/examples/chonk-stack/skins.ts +47 -0
  48. package/examples/chonk-stack/vibemarket.json +21 -0
  49. package/examples/collection-room/index.html +3 -0
  50. package/examples/collection-room/main.ts +31 -0
  51. package/examples/collection-room/vibemarket.json +12 -0
  52. package/examples/tsconfig.json +4 -0
  53. package/examples/vibexp-app/README.md +9 -0
  54. package/examples/vibexp-app/index.html +4 -0
  55. package/examples/vibexp-app/src/main.ts +22 -0
  56. package/examples/vibexp-app/vibemarket.json +1 -0
  57. package/package.json +54 -4
package/AGENTS.md ADDED
@@ -0,0 +1,217 @@
1
+ # VibeMarket game author contract — SDK v1
2
+
3
+ **VibeMarket OS app authors:** start with [README.md](README.md) and
4
+ [SECURITY.md](SECURITY.md), the `os init` starter and
5
+ `connectVibeMarketApp()`. Use category `vibexp-app`, `permissions: []` and
6
+ `collectionId: null`. That browser-only app facade has readiness, lifecycle and
7
+ bounded app-owned checkpoints; it has no profile, inventory, Steam/native,
8
+ wallet, purchase or reward authority. The existing Market-game contract below
9
+ continues to apply to collection games using `connectGameSdk()`; do not infer
10
+ those permissions for an OS app. Public app publication remains disabled.
11
+
12
+ This is the contract internal developers and agents test before public release.
13
+ Build an ordinary static web game. Deliver a ZIP of **built output**, not source,
14
+ node_modules, a server, or an install script. React, vanilla TypeScript and canvas
15
+ renderers all work. Use relative asset paths (`base: './'` in Vite). No remote
16
+ scripts, fonts, APIs, workers or wallet libraries. Bundle your dependencies/assets.
17
+
18
+ ## Install and author
19
+
20
+ Install the published package in an independent game project:
21
+
22
+ ```sh
23
+ npm install @vibechain/os@0.1.0
24
+ ```
25
+
26
+ To use a reviewed local SDK tarball instead, build it in the host checkout:
27
+
28
+ ```sh
29
+ cd vibemarket/packages/os
30
+ yarn install --frozen-lockfile
31
+ yarn review
32
+ yarn build
33
+ yarn pack --filename /tmp/vibechain-os-0.1.0.tgz
34
+ ```
35
+
36
+ In an independent game project, install that tarball:
37
+
38
+ ```sh
39
+ npm install /tmp/vibechain-os-0.1.0.tgz
40
+ npm install --save-dev typescript esbuild
41
+ ```
42
+
43
+ The tarball contains `examples/collection-room`. Copy its three files into your
44
+ project to start. Build `main.ts` with
45
+ `npx esbuild main.ts --bundle --format=esm --target=es2022 --outfile=dist/game.js`,
46
+ and copy `index.html` and `vibemarket.json` into `dist/`. Type-check your game with
47
+ strict TypeScript. Do not import VibeMarket host files or depend on a repo alias.
48
+
49
+ ```ts
50
+ import { connectGameSdk } from '@vibechain/os';
51
+ const sdk = await connectGameSdk();
52
+ await sdk.ready(); // Call when the first usable frame is mounted, within 30 seconds.
53
+ const profile = await sdk.profile.get(); // null for guests; no wallet address
54
+ const packs = await sdk.catalog.list(); // only this game's approved collection
55
+ const inventory = await sdk.inventory.get(); // pages of <=100 cards
56
+ const stop = sdk.inventory.onChanged(() => { /* re-fetch inventory */ });
57
+ // On teardown: stop(); sdk.destroy();
58
+ ```
59
+
60
+ For a complete reactive collection, use `watchInventory(sdk, { onChange,
61
+ onError, maxPages: 20 })` from the same package. It reads all pages atomically,
62
+ coalesces overlapping change events, discards interrupted snapshots, rejects
63
+ non-advancing cursors, and stops emitting after `observer.destroy()`. The
64
+ default bound is 20 pages / 2,000 cards; `maxPages` supports 1–100. Exceeding
65
+ the bound calls `onError`, rather than presenting a partial collection as
66
+ complete. Revoke cosmetic entitlements on error; retry with `observer.refresh()`.
67
+ This helper adds no host permission and does not poll the chain by itself.
68
+
69
+ `examples/chonk-stack` is a complete game using this contract: vanilla
70
+ TypeScript and Three.js, with all geometry and textures generated locally.
71
+ Copy the folder into your game project, install the SDK tarball, run
72
+ `npm install three@0.175.0` and `npm install --save-dev @types/three@0.175.0`, then run
73
+ `npx esbuild main.ts --bundle --minify --target=es2022 --outfile=dist/game.js`.
74
+ Copy `index.html` and `vibemarket.json` into `dist/`; esbuild emits `game.css`.
75
+ Use a unique manifest ID/version before packaging. Its After Hours collection
76
+ is intentionally fixed in `skins.ts` and the manifest; change both for a new
77
+ collection. The package is usable under the normal opaque-origin sandbox.
78
+ The game pauses on blur, tab hiding, collection access, and opening the shop.
79
+ Scores are session-only; cosmetics never alter timing, speed, or rewards.
80
+
81
+ `profile.get`, `catalog.list`, `inventory.get`, `packs.buy`, `packs.sell`,
82
+ `packs.open`, `cards.reveal`, `cards.sell` and `cards.collect` each require an
83
+ explicit manifest permission. `ready()` and `showShop()` are always available.
84
+ The SDK has no provider, arbitrary signing, chain RPC, wallet/session object,
85
+ private key, balances, recipient override or transaction calldata escape hatch.
86
+ `playerId` is session-local, not a durable account ID. Guest inventories are empty.
87
+
88
+ Pack actions take `(packId, quantity = 1)` (integer 1–10); card actions take
89
+ `cardId`. Calls return `{completed: true}` after the existing host driver
90
+ completes. Handle cancellation/errors and re-read inventory. On timeout check
91
+ inventory before retrying: a submitted transaction may still complete. The host
92
+ revalidates account, ownership and price after the user reviews the action.
93
+ Never auto-buy on game load. Only request spending following a clear player
94
+ interaction. Calling `showShop()` opens the trusted host rail/mobile drawer.
95
+
96
+ Collecting a non-Classic card permanently forfeits its cashout; Classic KEEP is a
97
+ local preference and remains sellable. Collection skins should use rarity/foil
98
+ or bundled artwork. Metadata image URLs are returned as data, but arbitrary
99
+ remote images are blocked in the runtime; the host rail renders collection art.
100
+
101
+ ## Bundle and manifest
102
+
103
+ ZIP root must contain `vibemarket.json` and the declared HTML entry. All manifest
104
+ fields are required; unknown fields fail validation. Example:
105
+
106
+ ```json
107
+ {
108
+ "schemaVersion": 1,
109
+ "sdkVersion": 1,
110
+ "id": "my-cat-game",
111
+ "version": "1.0.0-test.1",
112
+ "name": "My Cat Game",
113
+ "tagline": "Collect a cat. Take it for a spin.",
114
+ "category": "Collect · customize · play",
115
+ "entry": "index.html",
116
+ "permissions": ["profile.get", "catalog.list", "inventory.get", "packs.buy", "packs.open", "cards.reveal", "cards.collect"],
117
+ "collectionId": "REPLACE_WITH_A_REAL_MARKET_COLLECTION_ID"
118
+ }
119
+ ```
120
+
121
+ Use `collectionId: null` for unbound free play; omit trading permissions in that
122
+ case. This release binds **one collection** per version. Get its exact ID from
123
+ the market catalog/developer collection selector; do not invent one. All game
124
+ and rail access is filtered to that collection. A missing/retired collection
125
+ shows an unavailable state; it does not silently bind another one. The local
126
+ operator approves the declared collection and permissions when publishing.
127
+ Changing either requires a new version. Public developer ownership approval is
128
+ not implemented in the local adapter.
129
+
130
+ Supported assets: HTML, JS/MJS, CSS, JSON, PNG/JPEG/WebP/GIF/AVIF/SVG/ICO, WOFF/
131
+ WOFF2/TTF/OTF, MP3/OGG/WAV, MP4/WebM, WASM/BIN/TXT. Max 20 MiB compressed,
132
+ 64 MiB expanded, 16 MiB/file, 256 ZIP entries. No symlinks, encrypted files,
133
+ traversal, duplicate/case-colliding names, absolute paths or hidden paths.
134
+ Use ASCII filenames and normal subdirectories. WASM must run without threads;
135
+ workers/SharedArrayBuffer and arbitrary network access are unavailable.
136
+
137
+ ```sh
138
+ npx vibemarket-game pack dist my-cat-game.zip
139
+ ```
140
+
141
+ ## Local test → publish → rollback
142
+
143
+ Run the host from its verified checkout using its existing local stack. Use
144
+ `http://127.0.0.1:<port>/market/games?manage=1` (localhost also works). In the host's
145
+ `vibechain/` directory run `yarn games:publisher-token`; paste that local operator
146
+ credential into Developer Studio. Do not commit/share this token. Upload the ZIP,
147
+ inspect permissions and collection, preview, then select **Publish to dev**.
148
+ Uploading never publishes automatically. Draft links are unlisted bearer links;
149
+ anyone with the link on the same computer can preview. They are not multi-user
150
+ private previews or authenticated sharing links.
151
+
152
+ CLI uses exactly the same endpoints:
153
+
154
+ ```sh
155
+ export VIBEMARKET_PUBLISH_URL=http://127.0.0.1:8888
156
+ # Set VIBEMARKET_PUBLISH_TOKEN to the local operator credential without logging it.
157
+ npx vibemarket-game upload my-cat-game.zip
158
+ npx vibemarket-game list
159
+ npx vibemarket-game publish my-cat-game 1.0.0-test.1 1
160
+ # Last argument = latest registry revision returned by list/upload; never guess.
161
+ npx vibemarket-game rollback my-cat-game 1.0.0-test.1 3
162
+ ```
163
+
164
+ The upload response contains a preview URL. Test guest play, loading, SDK reads,
165
+ permission errors, bound inventory, cancellation and mobile drawer. Wallet tests
166
+ must use an explicitly selected disposable/test chain or a user-authorized real
167
+ transaction; do not spend real funds just to test publication. Then increment the
168
+ manifest version for changes, rebuild and upload again. A byte-identical repeat
169
+ is idempotent; changing bytes under an existing version returns 409. Publish and
170
+ rollback atomically select a retained immutable version. An already open game
171
+ stays pinned to its version until reopened. Old previews remain available.
172
+
173
+ The library lists only active versions. Drafts and previous versions remain in
174
+ Studio. Local quota is 40 games / 100 total versions; there is no delete UI.
175
+ Registry/assets persist in ignored `vibechain/.game-publisher/`. Back up this
176
+ folder to retain local uploads; losing it loses the local registry. A crash can
177
+ leave `.lock`: confirm no publisher request is running before removing that lock.
178
+
179
+ ## Runtime and future public adapter
180
+
181
+ Host wallet and HUD stay in VibeMarket. Uploaded HTML/JS runs at
182
+ `http://games.localhost:<port>/game-assets/...`, in an `allow-scripts` sandbox with
183
+ an opaque origin and a private MessagePort SDK session. HTTP CSP also sandboxes
184
+ a directly opened game URL. Do not add `allow-same-origin`, parent DOM access,
185
+ injected wallet scripts, popup navigation or top-level navigation. Fetch is
186
+ limited to this immutable bundle's assets. The runtime host denies all market
187
+ pages and APIs. The existing Next server must listen on that loopback address;
188
+ a server bound only to 127.0.0.1 cannot serve the second address.
189
+
190
+ Local desktop browser/device emulation works; physical-phone/LAN previews need
191
+ a separately configured isolated runtime host and are not supported yet.
192
+ All publisher APIs and uploaded runtimes return 404 outside development. This is
193
+ not a public upload service. To enable public publishing, replace the local
194
+ adapter with authenticated developer/collection approval, object storage/CDN on
195
+ a separate registrable domain, transactional version registry, quotas, malware
196
+ review and revocation. Keep this bundle, version and SDK contract unchanged.
197
+
198
+ ### Player links
199
+
200
+ Published games open at `/market/games/<manifest.id>`. Upload returns a draft
201
+ URL at that same path with `?preview=<version-key>`; keep the key to reopen that
202
+ exact version. Do not generate `?play=<id>` URLs. Existing query-style links
203
+ redirect for compatibility.
204
+
205
+ ### Cosmetic entitlements (Chonk reference)
206
+
207
+ Read `inventory.get()` and offer equip controls only for cards whose `state` is
208
+ `collected`. A revealed/sealed card is not an equipped collectible. Subscribe to
209
+ `inventory.onChanged` and revalidate every displayed page; revoke a skin when
210
+ its ownership disappears. Render names as text. Never derive race odds, payouts,
211
+ or ownership from local storage. Chonk After Hours maps the five rarity indices
212
+ to five matching model palettes; foil changes no race advantage.
213
+
214
+ Ship wardrobe thumbnails inside your bundle. The Chonk packaging command copies
215
+ its five product images and rewrites their paths, so it works under the same
216
+ no-external-network policy as every uploaded game. The host records development
217
+ views and successful SDK boots separately; games cannot assign counter values.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Beb, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,60 @@
1
- # Temporary Holding Version
1
+ # @vibechain/os
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Build a VibeMarket OS app with TypeScript, without cloning the monorepo or obtaining company secrets. The existing Market game client and development publisher remain compatible. **The OS app host is browser-only development software; production third-party app publishing remains disabled.** Installing this package does not grant a listing, native access or economic authority.
4
+
5
+ ## Make an app without the monorepo
6
+
7
+ ```sh
8
+ npx --yes @vibechain/os@0.1.0 init my-app
9
+ cd my-app
10
+ npm install
11
+ npm run build
12
+ npm run dev
13
+ ```
14
+
15
+ Open the printed `http://127.0.0.1:PORT` address. Stamp Club is a complete starter: add stamps, minimize and restore, then close/reset. Host-accepted state survives suspension in the same open window. Reset clears it. Rebuild and restart the immutable preview after changes. `npm run pack` creates `app.zip` for the existing **development** publisher.
16
+
17
+ The starter pins the installed SDK version and installs its own TypeScript and esbuild. It has no monorepo aliases or credentials. To use a reviewed archive instead of the registry, supply its real absolute path both to npm and the initializer:
18
+
19
+ ```sh
20
+ npm exec --yes --package=/absolute/path/vibechain-os-0.1.0.tgz -- os init my-app /absolute/path/vibechain-os-0.1.0.tgz
21
+ ```
22
+
23
+ That explicit fallback keeps a `file:` archive dependency; retain the archive for later reinstalls. Use a supported Node.js release: `^22.23.4`, `^24.22.1` or `^26.12.1`.
24
+
25
+ The library is ESM-only: use TypeScript/JavaScript `import`, or dynamic `import()` from CommonJS. There is no synchronous CommonJS `require()` build. Package validation checks the declared ESM and bundler resolution modes.
26
+
27
+ ## App API
28
+
29
+ ```ts
30
+ import { connectVibeMarketApp } from "@vibechain/os";
31
+
32
+ const app = await connectVibeMarketApp();
33
+ const previous = await app.checkpoint.read(); // null on first open
34
+ await app.checkpoint.write({ stamps: 1 }); // await host acknowledgement
35
+ app.lifecycle.onChanged(({ active, width, height }) => {
36
+ // Adapt rendering to the host surface. Untrusted frames are removed on suspension.
37
+ });
38
+ await app.ready(); // remove the host's loading state after initial render
39
+ window.addEventListener("pagehide", () => app.destroy(), { once: true });
40
+ ```
41
+
42
+ Checkpoint is a base app capability, separate from Market permissions. It accepts only the same app's bounded JSON: ≤32 KiB UTF-8, depth8, ≤2,048 nodes, ≤64 keys/object, ≤256 items/array and ≤8KiB/string. State lives in trusted host memory, scoped to the open installation/version/identity/window; it is cleared on close, revoke, package/identity change or the controller's absolute 15-minute expiry. Suspension does not extend that lifetime. There is no arbitrary namespace, disk storage, account data or browser-restart guarantee. `write()` resolves after acknowledgement; an accepted snapshot can be restored even if that acknowledgement was interrupted.
43
+
44
+ Manifest: use schema/sdkVersion1, `permissions: []` and `collectionId: null`. App methods are deliberately limited to readiness and checkpoint reads/writes. Raw requests for profile, inventory, rewards, purchases, Steam, native IPC or wallet operations terminate this app session. Existing Market games continue using `connectGameSdk()` with their existing permissions and host transaction review.
45
+
46
+ ## Maintainer workflow
47
+
48
+ ```sh
49
+ yarn install --frozen-lockfile
50
+ yarn review
51
+ yarn build
52
+ yarn check:package
53
+ yarn release:preview --version 0.1.0
54
+ ```
55
+
56
+ `yarn build` emits JavaScript/declarations plus one bundled preview host UI. Production publishing still requires a separate reviewed service and explicit activation. The existing local upload/publish/rollback commands retain their operator-token and loopback gates. Read [SECURITY.md](SECURITY.md) before integrating any untrusted app.
57
+
58
+ ## License
59
+
60
+ This package, including its bundled examples, is licensed under [MIT](LICENSE), copyright 2026 Beb, Inc. This license applies only to `@vibechain/os`; it does not relicense VibeMarket OS host code, the monorepo, other SDK packages or third-party dependencies. Their own terms continue to apply.
package/SECURITY.md ADDED
@@ -0,0 +1,35 @@
1
+ # VibeMarket OS app security and resource contract
2
+
3
+ This is a bounded local browser development adapter, not a certification that arbitrary web code is safe. It grants no host identity or economy access. Native support and public app publication remain disabled.
4
+
5
+ ## Boundary
6
+
7
+ - App code executes in a distinct host's iframe, `sandbox="allow-scripts"`, without `allow-same-origin`, top navigation, popups, forms or downloads. Runtime HTTP CSP also carries `sandbox allow-scripts`, including direct visits. The host checks its browser/native policy before creating a frame. Never inject third-party JavaScript into the desktop React realm or a privileged native webview.
8
+ - Admission binds the exact iframe WindowProxy, opaque origin `null`, one unpredictable 128-bit URL challenge, then a private MessagePort with a fresh 128-bit session. `null` is not an identity by itself. Bootstrap is ≤256-byte JSON and ≤32 messages from that child; unrelated windows receive no port. The global listener is removed after connection.
9
+ - The additive app codec uses bounded JSON on the existing channel/envelope/port transport. Legacy Market messages stay unchanged. Wrong session, replayed IDs, unknown methods, invalid schemas, malformed/oversized messages and quota exhaustion close the port. No implicit Market permissions are inherited.
10
+ - Close, navigation, minimize, app focus loss, hidden document, identity or package change revoke the active generation. Minimize/focus loss preserves only the same app's host-accepted bounded checkpoint. Restore creates a fresh iframe, challenge and session. Host focus uses desktop policy, not the browser `blur` event caused by focusing the child itself.
11
+ - The app receives no host authentication, wallet address, profile, inventory, Steam ticket, native handle, money or arbitrary HTTP relay. Checkpoint contains only its own supplied JSON; it is parsed, never merged into host objects. An app must not ask people to enter secrets inside its UI.
12
+
13
+ ## Enforced accepted-work limits
14
+
15
+ | Boundary | Limit |
16
+ |---|---:|
17
+ | App checkpoint | 32KiB UTF-8; depth8; 2,048nodes; 64keys/object; 256items/array; 8KiB/string |
18
+ | Request / response | 34KiB UTF-8 JSON each, cheap character cap before encoding/parsing |
19
+ | In-flight requests | 4 per active generation |
20
+ | Request rate | 10 per fixed one-second host interval; exhaustion terminates |
21
+ | Cumulative requests / IDs | 5,000 per open app controller, including suspended generations |
22
+ | Absolute controller lifetime / readiness | 15minutes across suspension and remounts /15seconds |
23
+ | App-side request wait | 10seconds |
24
+ | Built bundle | Existing256 total entries, 16MiB/file, 64MiB expanded; ZIP20MiB |
25
+ | First Desk adapter | One open third-party app controller and at most one untrusted iframe |
26
+
27
+ The local preview snapshots admitted files once using bounded no-follow file-handle reads, then serves only that immutable in-memory map and exact fixed host assets. It has no URL proxy, arbitrary filesystem route, write route or credential. Local filesystem authoring is not the public upload trust boundary; the existing ZIP validator remains responsible for untrusted uploads. The preview requires `127.0.0.1` for the parent and a different `localhost` runtime host, validates Host headers, never auto-opens a browser, and closes owned connections on shutdown.
28
+
29
+ ## What these controls cannot promise
30
+
31
+ The browser allocates structured-clone data before host validation. Message byte limits bound accepted host processing, not that prior allocation. An iframe has no portable hard CPU, memory, GPU, event-queue or network quota. A hostile app can still stall or exhaust a browser before removal. Cooperative lifecycle events do not enforce resource fairness; physical iframe removal limits continued execution after suspension but is not an OS process kill certificate.
32
+
33
+ CSP restricts fetches, assets, workers and embedding, but does not universally prevent a sandboxed app navigating its own frame to an external URL. Navigation revokes the session after load; a request may already have occurred. Do not describe this as a network firewall or supply secrets that require one. Known native bridge markers and embedded user agents are denied; their absence does not certify unknown webviews. Actual native IPC provenance tests are required before native admission.
34
+
35
+ Public activation requires a separately controlled registrable runtime domain, immutable pinned package and asset digests, publisher authentication/review, explicit permissions, revocation/kill switch, atomic update/rollback, network/abuse budgets, account/install scope and adversarial tests. Scores/checkpoints are untrusted client claims. Rewards, inventory grants and payments require separate server-authoritative, replay-safe, idempotent and capped verification; they are not implemented by this app API.
@@ -0,0 +1,4 @@
1
+ import { type VibeMarketAppSdk } from "./app-protocol.ts";
2
+ /** No profile, inventory, wallet, native, economy or arbitrary storage methods. */
3
+ export declare function connectVibeMarketApp(signal?: AbortSignal): Promise<VibeMarketAppSdk>;
4
+ export declare function createAppPortSdk(port: MessagePort, session: string): VibeMarketAppSdk;
@@ -0,0 +1,47 @@
1
+ import { APP_FRAGMENT, APP_LIMITS, appNonce, checkpointValue, lifecycleValue } from "./app-protocol.js";
2
+ import { connectHostPort, createRpcTransport } from "./transport.js";
3
+ /** No profile, inventory, wallet, native, economy or arbitrary storage methods. */
4
+ export async function connectVibeMarketApp(signal) {
5
+ const challenge = new URLSearchParams(window.location.hash.slice(1)).get(APP_FRAGMENT);
6
+ if (!appNonce(challenge))
7
+ throw Error("Open this app in VibeMarket OS or the SDK preview.");
8
+ const connection = await connectHostPort(signal, challenge);
9
+ if (!appNonce(connection.session)) {
10
+ connection.port.close();
11
+ throw Error("Invalid app session.");
12
+ }
13
+ return createAppPortSdk(connection.port, connection.session);
14
+ }
15
+ export function createAppPortSdk(port, session) {
16
+ if (!appNonce(session))
17
+ throw Error("Invalid app session.");
18
+ let state = Object.freeze({ active: true, width: 0, height: 0 });
19
+ const listeners = new Set();
20
+ const transport = createRpcTransport(port, {
21
+ session, timeoutMs: APP_LIMITS.requestTimeoutMs, maxPending: APP_LIMITS.inFlight, jsonBytes: APP_LIMITS.responseBytes,
22
+ onEvent(value) {
23
+ if (value.event !== "app.lifecycle")
24
+ return;
25
+ try {
26
+ state = lifecycleValue(value.state);
27
+ }
28
+ catch {
29
+ return;
30
+ }
31
+ for (const listener of [...listeners])
32
+ listener(state);
33
+ },
34
+ });
35
+ const complete = (result) => { if (!("completed" in result) || result.completed !== true)
36
+ throw Error("Invalid app acknowledgement."); };
37
+ return Object.freeze({
38
+ async ready() { complete(await transport.request({ method: "ui.ready" })); },
39
+ checkpoint: Object.freeze({
40
+ async read() { const result = await transport.request({ method: "app.checkpoint.get" }); if (!("checkpoint" in result))
41
+ throw Error("Invalid app checkpoint response."); return checkpointValue(result.checkpoint); },
42
+ async write(value) { complete(await transport.request({ method: "app.checkpoint.set", value: checkpointValue(value) })); },
43
+ }),
44
+ lifecycle: Object.freeze({ current: () => state, onChanged(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; } }),
45
+ destroy() { listeners.clear(); transport.destroy(); },
46
+ });
47
+ }
@@ -0,0 +1,28 @@
1
+ import { type AppLifecycle } from "./app-protocol.ts";
2
+ export interface AppSession {
3
+ lifecycle(value: AppLifecycle): void;
4
+ close(): void;
5
+ }
6
+ export interface AppController {
7
+ attach(port: MessagePort, session: string, options: {
8
+ current: () => boolean;
9
+ ready: () => void;
10
+ fault: (message: string) => void;
11
+ }): AppSession;
12
+ suspend(): void;
13
+ dispose(): void;
14
+ }
15
+ /** A single installation/window owns only the JSON this same app host-accepted. */
16
+ export declare function createAppController(clock?: () => number): AppController;
17
+ export interface AppFrameOptions {
18
+ controller: AppController;
19
+ challenge: string;
20
+ current: () => boolean;
21
+ ready: () => void;
22
+ fault: (message: string) => void;
23
+ }
24
+ /** Caller supplies the already-validated immutable URL, including this generation's fragment. */
25
+ export declare function mountAppFrame(frame: HTMLIFrameElement, options: AppFrameOptions): {
26
+ resize(width: number, height: number): void;
27
+ dispose(): void;
28
+ };
@@ -0,0 +1,196 @@
1
+ import { CHANNEL } from "./channel.js";
2
+ import { appRuntimeRefusal } from "./app-runtime.js";
3
+ import { APP_FRAGMENT, APP_LIMITS, appJson, appNonce, checkpointJson, createAppNonce, lifecycleValue, parseAppEnvelope, parseAppJson } from "./app-protocol.js";
4
+ /** A single installation/window owns only the JSON this same app host-accepted. */
5
+ export function createAppController(clock = () => performance.now()) {
6
+ let checkpoint = "null", disposed = false, active;
7
+ const startedAt = clock();
8
+ if (!Number.isFinite(startedAt))
9
+ throw Error("App clock is invalid.");
10
+ let lastClock = startedAt, intervalAt = startedAt, requests = 0, total = 0;
11
+ let terminalReason, activeFault;
12
+ const terminate = (reason) => {
13
+ if (disposed || terminalReason)
14
+ return;
15
+ terminalReason = reason;
16
+ clearTimeout(expiry);
17
+ checkpoint = "null";
18
+ const fault = activeFault;
19
+ active?.close();
20
+ fault?.(reason);
21
+ };
22
+ const expiry = setTimeout(() => terminate("App session expired. Reopen the app."), APP_LIMITS.sessionMs);
23
+ const readTime = () => {
24
+ let now;
25
+ try {
26
+ now = clock();
27
+ }
28
+ catch {
29
+ terminate("App clock changed. Reopen the app.");
30
+ return undefined;
31
+ }
32
+ if (!Number.isFinite(now) || now < lastClock) {
33
+ terminate("App clock changed. Reopen the app.");
34
+ return undefined;
35
+ }
36
+ lastClock = now;
37
+ if (now - startedAt >= APP_LIMITS.sessionMs) {
38
+ terminate("App session expired. Reopen the app.");
39
+ return undefined;
40
+ }
41
+ return now;
42
+ };
43
+ return {
44
+ attach(port, session, options) {
45
+ if (disposed || terminalReason || !appNonce(session)) {
46
+ port.close();
47
+ throw Error(terminalReason ?? "App controller is closed.");
48
+ }
49
+ if (readTime() === undefined) {
50
+ port.close();
51
+ throw Error(terminalReason);
52
+ }
53
+ active?.close();
54
+ let stopped = false, inFlight = 0;
55
+ const seen = new Set();
56
+ const close = () => { if (stopped)
57
+ return; stopped = true; port.onmessage = null; port.onmessageerror = null; port.close(); if (active === handle) {
58
+ active = undefined;
59
+ activeFault = undefined;
60
+ } };
61
+ const refuse = (reason) => { if (stopped)
62
+ return; close(); options.fault(reason); };
63
+ const current = () => !stopped && !disposed && options.current();
64
+ const handle = {
65
+ lifecycle(value) { if (current())
66
+ port.postMessage(appJson({ session, event: "app.lifecycle", state: lifecycleValue(value) }, APP_LIMITS.responseBytes)); },
67
+ close,
68
+ };
69
+ active = handle;
70
+ activeFault = options.fault;
71
+ port.onmessage = (event) => {
72
+ if (!current()) {
73
+ close();
74
+ return;
75
+ }
76
+ const now = readTime();
77
+ if (now === undefined)
78
+ return;
79
+ if (now - intervalAt >= 1000) {
80
+ intervalAt = now;
81
+ requests = 0;
82
+ }
83
+ if (++requests > APP_LIMITS.requestsPerSecond || ++total > APP_LIMITS.lifetimeRequests || inFlight >= APP_LIMITS.inFlight) {
84
+ refuse("App request limit exceeded.");
85
+ return;
86
+ }
87
+ let message;
88
+ try {
89
+ message = parseAppEnvelope(parseAppJson(event.data, APP_LIMITS.requestBytes), session);
90
+ }
91
+ catch {
92
+ refuse("Invalid or unpermitted app request.");
93
+ return;
94
+ }
95
+ if (seen.has(message.id)) {
96
+ refuse("App request was replayed.");
97
+ return;
98
+ }
99
+ seen.add(message.id);
100
+ inFlight++;
101
+ void Promise.resolve().then(() => {
102
+ if (!current())
103
+ return;
104
+ let result;
105
+ switch (message.request.method) {
106
+ case "ui.ready":
107
+ options.ready();
108
+ result = { completed: true };
109
+ break;
110
+ case "app.checkpoint.get":
111
+ result = { checkpoint: JSON.parse(checkpoint) };
112
+ break;
113
+ case "app.checkpoint.set":
114
+ checkpoint = checkpointJson(message.request.value);
115
+ result = { completed: true };
116
+ break;
117
+ }
118
+ const response = { session, id: message.id, result };
119
+ if (current())
120
+ port.postMessage(appJson(response, APP_LIMITS.responseBytes));
121
+ }).catch(() => { if (!stopped)
122
+ refuse("App request could not complete."); }).finally(() => { inFlight--; });
123
+ };
124
+ port.onmessageerror = () => refuse("App message could not be decoded.");
125
+ port.start();
126
+ return handle;
127
+ },
128
+ suspend() { active?.close(); },
129
+ dispose() { if (disposed)
130
+ return; disposed = true; clearTimeout(expiry); active?.close(); checkpoint = "null"; },
131
+ };
132
+ }
133
+ /** Caller supplies the already-validated immutable URL, including this generation's fragment. */
134
+ export function mountAppFrame(frame, options) {
135
+ const refusal = appRuntimeRefusal(window);
136
+ if (refusal)
137
+ throw Error(refusal);
138
+ if (!appNonce(options.challenge) || new URL(frame.src).hash !== `#${APP_FRAGMENT}=${options.challenge}`)
139
+ throw Error("Invalid app frame challenge.");
140
+ let ended = false, loaded = false, connected = false, bootstrapMessages = 0, session;
141
+ let bounds = lifecycleValue({ active: true, width: 0, height: 0 });
142
+ const dispose = () => { if (ended)
143
+ return; ended = true; clearTimeout(timeout); frame.removeEventListener("load", load); window.removeEventListener("message", connect); session?.close(); };
144
+ const fault = (message) => { if (ended)
145
+ return; dispose(); options.fault(message); };
146
+ const load = () => { if (loaded)
147
+ fault("App navigation ended this session.");
148
+ else
149
+ loaded = true; };
150
+ const connect = (event) => {
151
+ if (ended || connected || !options.current() || event.source !== frame.contentWindow)
152
+ return;
153
+ if (++bootstrapMessages > 32) {
154
+ fault("App connection limit exceeded.");
155
+ return;
156
+ }
157
+ if (!loaded || event.origin !== "null")
158
+ return;
159
+ let value;
160
+ try {
161
+ value = parseAppJson(event.data, 256);
162
+ }
163
+ catch {
164
+ fault("Invalid app connection message.");
165
+ return;
166
+ }
167
+ if (!value || typeof value !== "object" || Array.isArray(value)
168
+ || !("channel" in value) || value.channel !== CHANNEL || !("type" in value) || value.type !== "connect"
169
+ || !("challenge" in value) || value.challenge !== options.challenge || Object.keys(value).length !== 3)
170
+ return;
171
+ connected = true;
172
+ window.removeEventListener("message", connect);
173
+ const ports = new MessageChannel(), nonce = createAppNonce();
174
+ try {
175
+ session = options.controller.attach(ports.port1, nonce, { current: options.current,
176
+ ready() { clearTimeout(timeout); options.ready(); }, fault });
177
+ // Opaque frames require wildcard targetOrigin; the exact WindowProxy/challenge bind this transfer.
178
+ if (!frame.contentWindow)
179
+ throw Error("App frame is unavailable.");
180
+ frame.contentWindow.postMessage({ channel: CHANNEL, challenge: options.challenge, session: nonce }, "*", [ports.port2]);
181
+ session.lifecycle(bounds);
182
+ }
183
+ catch {
184
+ ports.port1.close();
185
+ ports.port2.close();
186
+ fault("App connection could not complete.");
187
+ }
188
+ };
189
+ const timeout = setTimeout(() => fault("App took too long to become ready."), 15_000);
190
+ frame.addEventListener("load", load);
191
+ window.addEventListener("message", connect);
192
+ return {
193
+ resize(width, height) { bounds = lifecycleValue({ active: true, width: Math.min(4096, Math.max(0, Math.floor(width))), height: Math.min(4096, Math.max(0, Math.floor(height))) }); session?.lifecycle(bounds); },
194
+ dispose,
195
+ };
196
+ }