@vibechain/os 0.5.0 → 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.
package/AGENTS.md CHANGED
@@ -1,4 +1,4 @@
1
- # VibeStore app author contract — @vibechain/os 0.5.0
1
+ # VibeStore app author contract — @vibechain/os 0.5.1
2
2
 
3
3
  This is the contract for people and agents building apps for VibeStore, the app
4
4
  store inside VibeMarket OS. Read it with [README.md](README.md) (API, helpers and
@@ -18,7 +18,7 @@ declares in `network` (below).
18
18
  ## Start
19
19
 
20
20
  ```sh
21
- npx --yes @vibechain/os@0.5.0 init my-app # TypeScript + canvas; or --template three, or --template plain
21
+ npx --yes @vibechain/os@0.5.1 init my-app # TypeScript + canvas; or --template three, or --template plain
22
22
  cd my-app
23
23
  npm install
24
24
  npm run build
@@ -53,11 +53,15 @@ Every rejection is an `OsError` with a stable `code` (`unsupported`,
53
53
  takes one integer score from 0 to 1,000,000,000, once per open window; the host
54
54
  owns the results screen and the score grants nothing. Saves are coalesced (one
55
55
  write per 10 seconds) and kept on the server, except a guest's, which last only
56
- while the window is open. `os.pack(slug)` and `os.showPack(slug)` work for linked
57
- packs; `os.cards()` and `os.packs()` with `cards` declared. Pointer lock,
56
+ while the window is open. `os.pack(slug)`, `os.showPack(slug)`,
57
+ `os.showCard(slug, cardId)` and `os.open(link)` (app links `vmos://pack/<slug>`,
58
+ `vmos://card/<slug>/<cardId>` and `https://vibechain.com/os/pack/<slug>`) work
59
+ for any public pack, linked or not, on a click while the app is in front, at most
60
+ one per 10 seconds; buying happens only in VibeMarket's own window and the app
61
+ learns nothing from it. `os.cards()` and `os.packs()` need `cards` declared. Pointer lock,
58
62
  gamepads, audio, WebAssembly and `blob:` workers (`spawnWorker`) work; threads
59
63
  and `SharedArrayBuffer` do not. `os.fullscreen()` asks the host after a click.
60
- Optional helpers: `@vibechain/os/loop`, `@vibechain/os/canvas` and
64
+ The optional `os.onCapture?.(() => canvasOrDataUrl)` customises the picture the desktop camera takes of your app (by default the SDK sends the largest visible canvas, so canvas and WebGL games need nothing; apps built with an older SDK show a placeholder in desktop photos). Optional helpers: `@vibechain/os/loop`, `@vibechain/os/canvas` and
61
65
  `@vibechain/os/testing` (`createFakeOs`, an in-memory host for unit tests).
62
66
  `connectVibeMarketApp()` (0.4) still works and is deprecated.
63
67
 
package/README.md CHANGED
@@ -5,9 +5,9 @@ Build games, tools and desktop apps for VibeMarket OS. One `connect()` gives you
5
5
  ## Quickstart
6
6
 
7
7
  ```sh
8
- npx --yes @vibechain/os@0.5.0 init my-app # TypeScript, esbuild and a 2D canvas (the default)
9
- npx --yes @vibechain/os@0.5.0 init my-app --template three # TypeScript, esbuild and Three.js: a spinning vmOS card
10
- npx --yes @vibechain/os@0.5.0 init my-app --template plain # index.html + game.js, nothing to install
8
+ npx --yes @vibechain/os@0.5.1 init my-app # TypeScript, esbuild and a 2D canvas (the default)
9
+ npx --yes @vibechain/os@0.5.1 init my-app --template three # TypeScript, esbuild and Three.js: a spinning vmOS card
10
+ npx --yes @vibechain/os@0.5.1 init my-app --template plain # index.html + game.js, nothing to install
11
11
  ```
12
12
 
13
13
  For `canvas` and `three`: `cd my-app`, `npm install`, `npm run build`, `npm run dev`, and open the printed `http://127.0.0.1:PORT` address. `npm run check` (`os check`) lists every problem with the manifest and the build at once, and `npm run pack` writes `app.zip`. For `plain`: `npx @vibechain/os preview my-app`; the folder is already the app, so zip it to submit. Every template's `vibemarket.json` is a complete schema version 3 listing with placeholder text and pictures you must replace first (an unchanged starter is rejected at review).
@@ -15,7 +15,7 @@ For `canvas` and `three`: `cd my-app`, `npm install`, `npm run build`, `npm run
15
15
  To install from a downloaded SDK archive, supply its absolute path to npm and the initializer:
16
16
 
17
17
  ```sh
18
- npm exec --yes --package=/absolute/path/vibechain-os-0.5.0.tgz -- os init my-app /absolute/path/vibechain-os-0.5.0.tgz
18
+ npm exec --yes --package=/absolute/path/vibechain-os-0.5.1.tgz -- os init my-app /absolute/path/vibechain-os-0.5.1.tgz
19
19
  ```
20
20
 
21
21
  That 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`. The library is ESM-only (`import`, or dynamic `import()` from CommonJS); browsers without a bundler use `vibemarket-os.js` (below).
@@ -35,8 +35,10 @@ await os.save(save); // JSON, up to 1 MiB, coalesced
35
35
  const cards = await os.cards(); // the Card[] the manifest permits; os.cards("rooftop-rats") filters
36
36
  const off = os.onCards(next => {}); // the whole list again whenever it changes; returns unsubscribe
37
37
  const packs = await os.packs(); // PackSummary[]
38
- const pack = await os.pack("rooftop-rats"); // the full public card list
39
- await os.showPack("rooftop-rats"); // the host opens the pack; needs a click
38
+ const pack = await os.pack("born-to-vibe"); // any public pack's face: name, cover, cards with art
39
+ await os.showPack("born-to-vibe"); // VibeMarket opens the pack; needs a click
40
+ await os.showCard("born-to-vibe", "b1"); // ...or one card on its pack's page
41
+ await os.open("vmos://pack/born-to-vibe"); // ...or an app link (packLink, cardLink, parseVmosLink)
40
42
 
41
43
  const me = await os.player(); // { guest: false, handle, username?, name, picture, token?, expiresAt? } or { guest: true }
42
44
  await os.finish({ score: 42 }); // one integer score, 0 to 1,000,000,000
@@ -57,14 +59,16 @@ os.close(); // release the port
57
59
  | `invalid` | A bad argument: not JSON, a bad pack slug, a number out of range. |
58
60
  | `too-large` | A save over 1 MiB, or over the player's 8 MiB across all apps. |
59
61
  | `rate-limited` | Too often; try later. |
60
- | `needs-click` | `showPack` or `fullscreen` without a fresh click in the app. |
62
+ | `needs-click` | `showPack`, `showCard`, `open` or `fullscreen` without a fresh click in the app. |
61
63
  | `unavailable` | The host or server could not answer now; retry. |
62
64
  | `timeout` | No answer in 10 seconds. |
63
65
  | `closed` | The session ended: the window closed, the app was revoked, or a limit. |
64
66
 
65
67
  **Saves.** `os.save(value)` stores one JSON value per player per app on VibeMarket's servers: at most 1 MiB as UTF-8 JSON, nested at most 64 deep, finite numbers only. It survives closing the window, other devices and reinstalling; a save not written for 365 days is deleted, and the player can delete it from the app's VibeStore page. Calls made sooner than the host accepts (one write in flight, at most one every 10 seconds) replace the pending value, and every caller's promise resolves with the write that carries it, so call it as often as you like. Saves are accepted while the window is behind another one: `os.onPause(() => os.save(state))` is the place to save. Two devices playing at once overwrite each other (last write wins). A guest's save lives only while the window is open (`os.guest`).
66
68
 
67
- **Cards and packs.** A manifest may link up to 3 vmOS packs by slug (the last part of `vibechain.com/os/pack/<slug>`), in `packs`. Linking someone else's pack takes effect once its creator approves the request your submission sends; your own packs are linked at once. With `packs` alone, `os.pack(slug)` returns the public card list (cards the player does not hold included, to draw them locked), `os.showPack(slug)` opens the pack in the market window, and the listing shows "Uses cards from". `"cards": "linked"` adds `os.cards()` and `os.packs()` for the player's holdings in those packs; `"cards": "all"` for every vmOS pack they hold. There is no prompt: the listing says what the app can see. An app never sees Nuggets, prices, Steam IDs or balances. Card art URLs are under your app's own address and send `Access-Control-Allow-Origin: *`: Three.js's `TextureLoader` uses them as WebGL textures as is; an `<img>` you create needs `img.crossOrigin = "anonymous"` before `src`. The [docs](https://vibechain.com/os/docs#sdk-05-card-game) show a card game skeleton (a deck builder) on these calls.
69
+ **Cards and packs.** A manifest may link up to 3 vmOS packs by slug (the last part of `vibechain.com/os/pack/<slug>`), in `packs`. Linking someone else's pack takes effect once its creator approves the request your submission sends; your own packs are linked at once. With `packs` alone, the listing shows "Uses cards from" and VibeMarket shows your game on the pack's page. `"cards": "linked"` adds `os.cards()` and `os.packs()` for the player's holdings in those packs; `"cards": "all"` for every vmOS pack they hold. There is no prompt: the listing says what the app can see. An app never sees Nuggets, prices, Steam IDs or balances. Card art URLs are under your app's own address and send `Access-Control-Allow-Origin: *`: Three.js's `TextureLoader` uses them as WebGL textures as is; an `<img>` you create needs `img.crossOrigin = "anonymous"` before `src`. The [docs](https://vibechain.com/os/docs#sdk-05-card-game) show a card game skeleton (a deck builder) on these calls.
70
+
71
+ **Showing any pack, and app links (0.5.1).** Any app can show and advertise any public vmOS pack, linked or not, with nothing in the manifest. `os.pack(slug)` returns its public face, what the pack's public page shows: name, creator, cover art and every card with its name, rarity and art (art URLs work as described above), never what the player holds. `os.showPack(slug)` opens the pack in VibeMarket inside vmOS, and `os.showCard(slug, cardId)` opens one card on its pack's page. An app link is one string you can put in your own content or get from your server: `vmos://pack/<slug>`, `vmos://card/<slug>/<cardId>`, or a pack's public page `https://vibechain.com/os/pack/<slug>` (or `www.`); `os.open(link)` opens it. `packLink(slug)` and `cardLink(slug, cardId)` write links and `parseVmosLink(text)` reads one (`{ kind: "pack", pack }`, `{ kind: "card", pack, card }` or `null`); the grammar is exact (lowercase scheme and host, no query, fragment, port or percent-encoding, at most 200 characters), and anything else answers `invalid` without reaching the host. `open` never navigates your frame: the SDK sends the host only the parsed pack or card. All three need the app ready and in front (`not-permitted`) and a fresh click in it (`needs-click`), share one budget of one per 10 seconds (`rate-limited`), and answer `invalid` for a pack that does not exist or was taken down or a card not in it. Buying and opening happen only in VibeMarket's own window, and your app learns nothing about what the player does there; it sees new holdings only through `os.cards()` and `onCards`, as the manifest permits. On a 0.5.0 host `showCard` and card links answer `unsupported`. The [docs](https://vibechain.com/os/docs#sdk-05-link-out) have the full rules and examples.
68
72
 
69
73
  **Network and the player.** A manifest may declare up to 8 servers in `network`: exact `https://` or `wss://` origins (a DNS name, no path, no IP addresses, no local or wildcard-DNS names). The app may then `fetch`, `WebSocket` and `EventSource` them, and load images, audio, video and fonts from the `https://` ones; never scripts, styles or workers. Your servers must answer the frame's `Origin: null` with `Access-Control-Allow-Origin: *` (or `null`) for `fetch` and for images used as textures. Version remote URLs and send a long `Cache-Control`: the app has no IndexedDB, Cache Storage or service worker. Every server you declare sees the player's IP address; the listing says "Connects to" and "Loads content from" your hosts, and what your server sends after review is still bound by the listing rules (no third-party advertising or analytics, no payments, no sign-in prompts).
70
74
 
@@ -74,11 +78,13 @@ os.close(); // release the port
74
78
 
75
79
  **Older hosts.** On a host older than 0.5, `ready`, `finish`, the lifecycle, `load` and `save` work (saves use the window-only 32 KiB checkpoint, and a larger one answers `too-large`); the rest answers `unsupported` and `progress` does nothing.
76
80
 
81
+ **Desktop photos.** The desktop camera cannot see inside a sandboxed app window, so it asks the app for its current frame (`app.capture`). `connect()` and `connectVibeMarketApp()` answer by default with the largest visible `<canvas>` on the page, taken on the next animation frame, scaled to at most 1280 pixels on its longest side and encoded as WebP (JPEG if WebP is unavailable) under 1,000,000 characters; a WebGL game needs no changes. An app that draws with the DOM, or wants a custom picture, registers `const off = os.onCapture?.(() => canvasOrDataUrl)` (optional; the 0.4 client has `sdk.onCapture` too): return an `HTMLCanvasElement`, a PNG/JPEG/WebP data URL, `null`, or a promise of one; the latest handler wins and the host waits about 1.2 seconds. Failures are silent. An app built with an older SDK shows a placeholder in desktop photos until it is rebuilt against this SDK.
82
+
77
83
  **Legacy API.** `connectVibeMarketApp()` and its `checkpoint` (0.4) keep working and keep their types, and are deprecated: `connect()` does the same and more on every host.
78
84
 
79
85
  ## Apps without a bundler
80
86
 
81
- `vibemarket-os.js` (in `dist/` of the package, copied by `os init --template plain`) defines one global, `VibemarketOS`, with `connect` and `OsError`. **Load it and your game from files: inline `<script>` code does not run**, because the runtime's policy allows scripts only from your app's own files.
87
+ `vibemarket-os.js` (in `dist/` of the package, copied by `os init --template plain`) defines one global, `VibemarketOS`, with `connect`, `OsError` and the link helpers `packLink`, `cardLink` and `parseVmosLink`. **Load it and your game from files: inline `<script>` code does not run**, because the runtime's policy allows scripts only from your app's own files.
82
88
 
83
89
  ```html
84
90
  <script src="vibemarket-os.js"></script>
@@ -123,11 +129,11 @@ const host = createFakeOs({ save: { best: 3 }, cards: myCards, packs: [myPack],
123
129
  const game = await startGame(host.os); // your code, given the os instead of connecting
124
130
  host.setCards(afterAPull); // onCards listeners hear about it
125
131
  host.setLifecycle({ active: false }); // as if the window was minimized
126
- host.click(); await game.openShop(); // showPack and fullscreen need a click
132
+ host.click(); await game.openShop(); // showPack, showCard, open and fullscreen need a click
127
133
  expect(host.save).toEqual({ best: 7 }); expect(host.finished).toEqual({ score: 7 });
128
134
  ```
129
135
 
130
- It applies the real save limits, slug checks, card access levels, single-shot score, click rule and error codes, and `protocol: 1` behaves like an older host. It has no time limits, rate limits or save coalescing, so still run the preview before you ship. `createFakeApp` is the same for the legacy `connectVibeMarketApp()` API.
136
+ It applies the real save limits, slug checks, card access levels, single-shot score, click rule, link grammar and error codes, and `protocol: 1` behaves like an older host. `packs` lists every public pack it knows (any of them works with `pack`, `showPack`, `showCard` and `open`), and `shownPacks` and `shownCards` record what the game asked to show. It has no time limits, rate limits or save coalescing, so still run the preview before you ship. `createFakeApp` is the same for the legacy `connectVibeMarketApp()` API.
131
137
 
132
138
  ### Complete examples
133
139
 
@@ -218,11 +224,16 @@ pnpm install --frozen-lockfile
218
224
  pnpm review
219
225
  pnpm build
220
226
  pnpm check:package
221
- pnpm release:preview --version 0.5.0
227
+ pnpm release:preview --version 0.5.1
222
228
  ```
223
229
 
224
230
  `pnpm build` emits JavaScript/declarations, the bundled preview host UI, `dist/vibemarket-os.js` (the no-bundler IIFE) and `dist/templates/plain/game.js` (built from `examples/vibexp-app/plain/game.ts`, so the repository holds no authored JavaScript). Only `examples/paw-beat` and `examples/vibexp-app` (with its `plain` and `three` templates) are published; `examples/card-game` and `examples/verify-player.ts` are type-checked and tested here and shown on the docs site. The store images of both examples are generated by scripts in `tools/` (not published), which drive headless, muted Chromium through Playwright. Read [SECURITY.md](SECURITY.md) before integrating any untrusted app.
225
231
 
232
+ ## Changes in 0.5.1 (since 0.5.0)
233
+
234
+ - **New, optional: desktop photos.** The host may send `app.capture` and the SDK answers with a new `app.frame` request carrying the app's picture (by default its largest visible canvas). `Os.onCapture` and `VibeMarketAppSdk.onCapture` are new optional hooks to supply your own picture. Nothing existing was renamed or removed, and no app needs a code change: an app built with an older SDK, or one that sends nothing, is shown as its icon and name in desktop photos.
235
+ - **New: link out to any pack or card.** `os.pack` and `os.showPack` work for any public pack, linked or not; `os.showCard(slug, cardId)` and `os.open(link)` are new, with the pure helpers `packLink`, `cardLink` and `parseVmosLink` (also on the no-bundler `VibemarketOS` global). One new protocol message, `card.show`, advertised as the hello feature `"card.show"`; on a host without it `showCard` and card links answer `unsupported`.
236
+
226
237
  ## License
227
238
 
228
239
  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, other Vibechain software, other SDK packages or third-party dependencies. Their own terms continue to apply.
package/SECURITY.md CHANGED
@@ -55,7 +55,7 @@ A host that supplies protocol 2 services (an apps3 host: the desk with its `apps
55
55
  | Schema version 3 manifest | | at most 3 linked packs, 8 declared origins |
56
56
  | First Desk adapter | One open third-party app controller and at most one untrusted iframe | same |
57
57
 
58
- Policy outcomes (a missing permission, the app loading or behind another window, a soft rate, a missing click, a quota, an unavailable server) are answered with one of nine stable codes and keep the session. Protocol violations (malformed or unknown messages, schema errors, a second hello, a lower or repeated id, a request over its method's bound, the hard limits above) end it. `pack.show` and entering `display.fullscreen` act only while the app is ready and in front; the host additionally checks fresh user activation on its own page and answers `needs-click`. Leaving fullscreen is always allowed.
58
+ Policy outcomes (a missing permission, the app loading or behind another window, a soft rate, a missing click, a quota, an unavailable server) are answered with one of nine stable codes and keep the session. Protocol violations (malformed or unknown messages, schema errors, a second hello, a lower or repeated id, a request over its method's bound, the hard limits above) end it. `pack.show`, `card.show` and entering `display.fullscreen` act only while the app is ready and in front; the host additionally checks fresh user activation on its own page and answers `needs-click`. Leaving fullscreen is always allowed.
59
59
 
60
60
  The local preview snapshots admitted files once using bounded no-follow file-handle reads, then serves only that immutable in-memory map, exact fixed host assets and stand-in card art (the bundle's own listing icon, under the version prefix). It is an apps3 host with stand-in services: six fake cards per linked pack, a save in the parent page's own browser storage, and an unsigned placeholder player token for apps that declare `network`; its runtime responses carry the production policy from `appRuntimeCsp`, with the preview's asset prefix and parent. 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.
61
61
 
@@ -65,6 +65,8 @@ The browser allocates structured-clone data before host validation. Message byte
65
65
 
66
66
  The runtime policy (`appRuntimeCsp`, `@vibechain/os/policy`) limits scripts, styles and workers' first scripts to the version's own files, and every fetch, image, media and font to those files plus, for a version whose manifest declares `network`, its declared origins: every origin in `connect-src`, the `https://` ones also in `img-src`, `media-src` and `font-src`, and never in `script-src`, `style-src`, `worker-src`, `child-src`, `frame-src` or `object-src`. Declared origins are re-validated (`networkOrigin`: https or wss, a public DNS name, no IP address in any form, no local, reserved or wildcard-DNS name, no Vibechain domain) and a list that is not normalized throws rather than produce a partial policy. What it cannot stop: text fetched from a declared server run in a `blob:` worker (`worker-src blob:` stays, for engines and decoders), `WebAssembly.instantiate` on fetched bytes, fetched CSS put into a `<style>` element, an interpreter in the bundle running server-sent programs, and server data driving behaviour. So "the reviewed code is the code that runs" holds for the files VibeStore hosts and is listing policy for everything else: an app whose behaviour changes after review because its server says so breaches the listing rules and is removed by revocation; it is not confined. A declared name can also resolve to a private address; Chromium's Private Network Access narrows that in one engine only. Every declared server sees the player's IP address. Network apps may not embed third-party advertising or analytics SDKs (review rule, owner decision 2026-11-23). WebRTC is not governed by CSP: an app can open peer connections in every measured engine, so the listing allows WebRTC only for play between players signalled through declared servers. A sandboxed app can also navigate its own frame to an external URL; navigation revokes the session after load, but a request may already have occurred. Do not describe any of this as a network firewall or supply secrets that require one. Known native bridge markers and embedded user agents are denied, except the Steam client's own two markers when it claims app frames (see Host admission); their absence does not certify unknown webviews, and that claim does not certify the client. Native IPC provenance tests on each platform remain the client's gate before a build sets the flag.
67
67
 
68
+ **Showing packs and cards (0.5.1).** Any app may show any public pack (one that exists and is not taken down), linked or not: `cards.pack` answers the pack's public face, exactly what its public page shows (name, creator, cover, card names, rarities and art under the app's own prefix) and never holdings, which come only from `cards.list` as the manifest declares. `pack.show` and `card.show` ask the host to open the pack or one card in VibeMarket's market window. `os.open(link)` accepts only the exact app-link grammar (`vmos://pack/<slug>`, `vmos://card/<slug>/<cardId>`, `https://vibechain.com/os/pack/<slug>` or `www.`, at most 200 characters, no percent-encoding, query, fragment, port, user or other host), parses it in the SDK and sends only the parsed slug and card id; neither the SDK nor the host navigates to the string. The host acts only while the app is ready and in front and on fresh user activation on its own page (`needs-click`), at most once per 10 seconds across both methods (`rate-limited`), and answers `invalid` for an unknown or taken-down pack or a card not in it. The market window's Buy and Open controls are the host's own and ignore clicks for 500 ms after it opens, and the app is never told whether anything was bought or opened, so showing a pack tells it nothing new about the player and grants it nothing.
69
+
68
70
  **Player identity.** An app learns the player's public identity and nothing private: the handle, @name, display name and picture their public profile already shows. The token is a 5-minute Ed25519 JWT (`sub` = the handle, plus `username`, `name`, `guest: false`, `aud` = the app id) signed by the backend only, for apps that declare `network`, so their servers can trust who is playing instead of a handle the client claims; guests get none; public keys are at `https://vibechain.com/.well-known/vmos-app-keys.json`. It is a statement for the app's own server, not a credential: no vibechain.com route accepts it. A server that does not check `aud` would accept another app's tokens; the verification sample in the docs (https://vibechain.com/os/docs#sdk-05-verify) checks it. Within its 5 minutes a token can be replayed; servers that need one-time use keep `jti`.
69
71
 
70
72
  **Owner decisions applied (2026-11-23).** An app is told who is playing (its public identity; no anonymous ids), and `cards: "all"` reads every vmOS pack the player holds with no consent prompt: the listing discloses both. Fullscreen goes through the host: the app's window, with a host-drawn strip naming the app and offering Report and Exit, enters the browser's full screen; the frame never gets the Fullscreen API (`fullscreen=()` stays in the runtime's Permissions-Policy) and Escape always leaves. Saves are kept on uninstall and revocation, deleted after 365 days without a write, on the player's request and with the account. Network apps carry no third-party advertising or analytics SDKs (a review rule).
@@ -1,5 +1,6 @@
1
- import { APP_FRAGMENT, APP_LIMITS, appNonce, checkpointValue, lifecycleValue } from "./app-protocol.js";
1
+ import { APP_FRAGMENT, APP_LIMITS, appNonce, checkpointValue, lifecycleValue, FRAME_MESSAGE_BYTES } from "./app-protocol.js";
2
2
  import { connectHostPort, createRpcTransport } from "./transport.js";
3
+ import { createCapturer } from "./capture.js";
3
4
  import { gameFinishInput } from "./completion.js";
4
5
  /**
5
6
  * The 0.4 app API: readiness, lifecycle, the window-only checkpoint and one score.
@@ -22,8 +23,12 @@ export function createAppPortSdk(port, session) {
22
23
  let state = Object.freeze({ active: true, width: 0, height: 0 });
23
24
  const listeners = new Set();
24
25
  const transport = createRpcTransport(port, {
25
- session, timeoutMs: APP_LIMITS.requestTimeoutMs, maxPending: APP_LIMITS.inFlight, jsonBytes: APP_LIMITS.responseBytes,
26
+ session, timeoutMs: APP_LIMITS.requestTimeoutMs, maxPending: APP_LIMITS.inFlight, jsonBytes: APP_LIMITS.responseBytes, outBytes: FRAME_MESSAGE_BYTES,
26
27
  onEvent(value) {
28
+ if (value.event === "app.capture") {
29
+ capturer.event(value.id);
30
+ return;
31
+ }
27
32
  if (value.event !== "app.lifecycle")
28
33
  return;
29
34
  try {
@@ -36,6 +41,8 @@ export function createAppPortSdk(port, session) {
36
41
  listener(state);
37
42
  },
38
43
  });
44
+ const capturer = createCapturer((id, image) => { transport.request({ method: "app.frame", id, image }).catch(() => { }); }, () => destroyed);
45
+ let destroyed = false;
39
46
  const complete = (result) => { if (!("completed" in result) || result.completed !== true)
40
47
  throw Error("Invalid app acknowledgement."); };
41
48
  return Object.freeze({
@@ -47,6 +54,7 @@ export function createAppPortSdk(port, session) {
47
54
  async write(value) { complete(await transport.request({ method: "app.checkpoint.set", value: checkpointValue(value) })); },
48
55
  }),
49
56
  lifecycle: Object.freeze({ current: () => state, onChanged(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; } }),
50
- destroy() { listeners.clear(); transport.destroy(); },
57
+ onCapture(handler) { return capturer.on(handler); },
58
+ destroy() { destroyed = true; capturer.clear(); listeners.clear(); transport.destroy(); },
51
59
  });
52
60
  }
@@ -4,6 +4,12 @@ import { type Player, type WireCard, type WirePack, type WirePackSummary } from
4
4
  export interface AppSession {
5
5
  lifecycle(value: AppLifecycle): void;
6
6
  close(): void;
7
+ /**
8
+ * Ask a protocol 2 app for its current frame (`app.capture` / `app.frame`): a PNG, JPEG or WebP data URL, or null when
9
+ * there is none (protocol 1, no hello yet, the app has no picture, the timeout, the session ended, a newer capture took
10
+ * over). One capture is pending at a time. Never rejects.
11
+ */
12
+ capture(timeoutMs?: number): Promise<string | null>;
7
13
  }
8
14
  /**
9
15
  * `current`: this generation is the live one (its frame is mounted for this app and the page is shown). `foreground`: its
@@ -50,10 +56,15 @@ export interface AppHostServices {
50
56
  }>;
51
57
  /** the permitted packs with what the player holds of each */
52
58
  packs(): Promise<WirePackSummary[]>;
53
- /** one pack's public card list, for a pack the app may read */
59
+ /** the public face of any public pack (exists, not taken down): never holdings; throw `invalid` for an unknown or taken-down pack */
54
60
  pack(slug: string): Promise<WirePack>;
55
- /** open the market window on a pack (check activation and permission) */
61
+ /** open the market window on any public pack; throw `needs-click` without a fresh activation, `invalid` for an unknown or taken-down pack */
56
62
  showPack(slug: string): Promise<void>;
63
+ /**
64
+ * open that card in its pack's page (0.5.1); the same rules as `showPack`, and `invalid` for a card not in the pack. Without it
65
+ * the host does not offer `card.show`, and a 0.5.1 client answers `os.showCard` with `unsupported` itself.
66
+ */
67
+ showCard?(slug: string, card: string): Promise<void>;
57
68
  /** the player's public identity (`picture` as a path after the version prefix), or `{ guest: true }`; `token` and `expiresAt` only for an app that declares `network` */
58
69
  player(): Promise<Player>;
59
70
  maximize(on: boolean): Promise<void>;
@@ -95,6 +106,8 @@ export interface MountedAppFrame {
95
106
  resize(width: number, height: number): void;
96
107
  setActive(active: boolean): void;
97
108
  dispose(): void;
109
+ /** the app's current frame as a data URL (see `AppSession.capture`), or null; also null when there is no session or it ended */
110
+ capture(timeoutMs?: number): Promise<string | null>;
98
111
  }
99
112
  /**
100
113
  * Caller supplies the already-validated immutable URL, including this generation's fragment. With a protocol 2
package/dist/app-host.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { CHANNEL } from "./channel.js";
2
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
- import { APP_FEATURES_2, APP_METHODS_2, APP_SESSION_LIMITS, CARD_ID, cardArtPath, coverArtPath, AppHostError, appRequest2, cardsRevision, entryRoot, methodRule, saveJson, saveValue, utf8Bytes, wireCard, wirePack, wirePackSummary, wirePlayer, } from "./app-wire.js";
3
+ import { APP_FRAGMENT, APP_LIMITS, FRAME_MESSAGE_BYTES, appJson, appNonce, checkpointJson, createAppNonce, lifecycleValue, parseAppEnvelope, parseAppJson } from "./app-protocol.js";
4
+ import { APP_FEATURES_2, APP_METHODS_2, APP_SESSION_LIMITS, CARD_ID, cardArtPath, coverArtPath, AppHostError, appRequest2, cardsRevision, frameImage, entryRoot, methodRule, saveJson, saveValue, utf8Bytes, wireCard, wirePack, wirePackSummary, wirePlayer, } from "./app-wire.js";
5
5
  import { packSlug } from "./manifest.js";
6
6
  /**
7
7
  * An apps3 session's request: protocol 1 methods exactly as `parseAppEnvelope` admits them, `host.hello` before hello, and
@@ -14,7 +14,8 @@ function envelope2(data, session, hello) {
14
14
  throw Error("Invalid app session request.");
15
15
  const request = appRequest2(data.request);
16
16
  const legacy = request !== null && !Object.hasOwn(APP_METHODS_2, request.method);
17
- if (!request || (!hello && !legacy && request.method !== "host.hello"))
17
+ // app.frame is also admitted before hello: a 0.4 client never says hello and still answers the desktop camera
18
+ if (!request || (!hello && !legacy && request.method !== "host.hello" && request.method !== "app.frame"))
18
19
  throw Error("This app has no permission for that method.");
19
20
  if (utf8Bytes(JSON.stringify(data.request)) > methodRule(request.method).request)
20
21
  throw Error("App request exceeds its bound.");
@@ -125,7 +126,13 @@ export function createAppController(clock = () => performance.now(), options = {
125
126
  let baseline;
126
127
  const seen = new Set();
127
128
  const soft = new Map();
129
+ let captureSeq = 0, capturing;
130
+ const endCapture = (image) => { const waiting = capturing; capturing = undefined; if (waiting) {
131
+ clearTimeout(waiting.timer);
132
+ waiting.resolve(image);
133
+ } };
128
134
  const close = () => {
135
+ endCapture(null);
129
136
  if (stopped)
130
137
  return;
131
138
  stopped = true;
@@ -148,6 +155,22 @@ export function createAppController(clock = () => performance.now(), options = {
148
155
  lifecycle(value) { if (current())
149
156
  port.postMessage(appJson({ session, event: "app.lifecycle", state: lifecycleValue(value) }, APP_LIMITS.responseBytes)); },
150
157
  close,
158
+ capture(timeoutMs = APP_SESSION_LIMITS.captureMs) {
159
+ endCapture(null);
160
+ if (!current())
161
+ return Promise.resolve(null);
162
+ const id = String(++captureSeq), wait = typeof timeoutMs === "number" && Number.isFinite(timeoutMs) ? Math.max(0, timeoutMs) : APP_SESSION_LIMITS.captureMs;
163
+ return new Promise(resolve => {
164
+ capturing = { id, resolve, timer: setTimeout(() => { if (capturing?.id === id)
165
+ endCapture(null); }, wait) };
166
+ try {
167
+ send({ session, event: "app.capture", id }, 256);
168
+ }
169
+ catch {
170
+ endCapture(null);
171
+ }
172
+ });
173
+ },
151
174
  };
152
175
  active = handle;
153
176
  activeFault = attachOptions.fault;
@@ -168,6 +191,18 @@ export function createAppController(clock = () => performance.now(), options = {
168
191
  baseline = { revision: next.revision, cards: fresh };
169
192
  send({ session, event: "app.cards", state: event }, APP_SESSION_LIMITS.cardsEventBytes + 1024);
170
193
  };
194
+ /** The answer to an `app.frame` on any protocol: ignore a late id, refuse a bad picture softly, else hand it to the pending capture. */
195
+ const frameAnswer = (request) => {
196
+ const pending = capturing?.id === request.id;
197
+ if (request.image !== null && !frameImage(request.image)) {
198
+ if (pending)
199
+ endCapture(null);
200
+ throw new AppHostError("invalid", "That is not a PNG, JPEG or WebP data URL of at most 1,000,000 characters.");
201
+ }
202
+ if (pending)
203
+ endCapture(request.image);
204
+ return { completed: true };
205
+ };
171
206
  /** One protocol 2 answer. A thrown AppHostError is a soft refusal; anything else from the services is `unavailable`. */
172
207
  const answer2 = async (services, request) => {
173
208
  const check = (value, valid) => { try {
@@ -177,7 +212,7 @@ export function createAppController(clock = () => performance.now(), options = {
177
212
  throw new AppHostError("unavailable", MESSAGE.unavailable);
178
213
  } };
179
214
  switch (request.method) {
180
- case "host.hello": return { protocol: 2, guest: services.guest, features: [...APP_FEATURES_2], root: entryRoot(services.entry) };
215
+ case "host.hello": return { protocol: 2, guest: services.guest, features: [...APP_FEATURES_2, ...(services.showCard ? ["card.show"] : [])], root: entryRoot(services.entry) };
181
216
  case "ui.progress":
182
217
  // ignored once the app is ready
183
218
  if (!ready) {
@@ -186,6 +221,7 @@ export function createAppController(clock = () => performance.now(), options = {
186
221
  attachOptions.progress?.(request.value);
187
222
  }
188
223
  return { completed: true };
224
+ case "app.frame": return frameAnswer(request);
189
225
  case "app.save.get": {
190
226
  const stored = await services.saveGet();
191
227
  return { value: stored.value === null ? null : check(stored.value, saveValue), savedAt: stored.savedAt === null ? null : check(stored.savedAt, value => { if (typeof value !== "string" || value.length > 30)
@@ -235,6 +271,13 @@ export function createAppController(clock = () => performance.now(), options = {
235
271
  throw new AppHostError("invalid", MESSAGE.slug);
236
272
  await services.showPack(request.pack);
237
273
  return { shown: true };
274
+ case "card.show":
275
+ if (!services.showCard)
276
+ throw new AppHostError("unsupported", "This host cannot show a card.");
277
+ if (!packSlug(request.pack) || !CARD_ID.test(request.card))
278
+ throw new AppHostError("invalid", "That is not a pack slug and a card id.");
279
+ await services.showCard(request.pack, request.card);
280
+ return { shown: true };
238
281
  case "player.get": return check(await services.player(), wirePlayer);
239
282
  case "display.maximize":
240
283
  await services.maximize(request.on);
@@ -264,9 +307,9 @@ export function createAppController(clock = () => performance.now(), options = {
264
307
  let id, request;
265
308
  try {
266
309
  if (!apps3)
267
- ({ id, request } = parseAppEnvelope(parseAppJson(event.data, APP_LIMITS.requestBytes), session));
310
+ ({ id, request } = parseAppEnvelope(parseAppJson(event.data, FRAME_MESSAGE_BYTES), session));
268
311
  else
269
- ({ id, request } = envelope2(parseAppJson(event.data, hello ? APP_SESSION_LIMITS.messageBytes : APP_LIMITS.requestBytes), session, hello));
312
+ ({ id, request } = envelope2(parseAppJson(event.data, APP_SESSION_LIMITS.messageBytes), session, hello));
270
313
  }
271
314
  catch {
272
315
  refuse("Invalid or unpermitted app request.");
@@ -306,6 +349,18 @@ export function createAppController(clock = () => performance.now(), options = {
306
349
  // backgrounded: a write is withheld exactly as a suspended app's would be lost (see AppAttachOptions)
307
350
  if (!foreground() && (method === "game.finish" || method === "app.checkpoint.set"))
308
351
  return;
352
+ if (request.method === "app.frame" && !apps3) {
353
+ try {
354
+ const result = frameAnswer(request);
355
+ if (current())
356
+ port.postMessage(appJson({ session, id, result }, APP_LIMITS.responseBytes));
357
+ }
358
+ catch (error) {
359
+ if (current())
360
+ port.postMessage(appJson({ session, id, error: error.message, code: "invalid" }, APP_LIMITS.responseBytes));
361
+ }
362
+ return;
363
+ }
309
364
  if (legacy) {
310
365
  let result;
311
366
  switch (request.method) {
@@ -355,10 +410,11 @@ export function createAppController(clock = () => performance.now(), options = {
355
410
  throw new AppHostError("not-permitted", MESSAGE.states);
356
411
  // leaving fullscreen is always allowed (section 9.2)
357
412
  if (rule.rate && !(request.method === "display.fullscreen" && !request.on)) {
358
- let limiter = soft.get(method);
413
+ const key = rule.bucket ?? method;
414
+ let limiter = soft.get(key);
359
415
  if (!limiter) {
360
416
  limiter = slidingWindow(rule.rate[0], rule.rate[1]);
361
- soft.set(method, limiter);
417
+ soft.set(key, limiter);
362
418
  }
363
419
  if (!limiter(now))
364
420
  throw new AppHostError("rate-limited", MESSAGE.rate);
@@ -470,6 +526,7 @@ export function mountAppFrame(frame, options) {
470
526
  setActive(active) { if (active === bounds.active)
471
527
  return; bounds = lifecycleValue({ ...bounds, active }); session?.lifecycle(bounds); },
472
528
  dispose,
529
+ capture(timeoutMs) { return ended || !session ? Promise.resolve(null) : session.capture(timeoutMs); },
473
530
  };
474
531
  }
475
532
  /**
@@ -18,6 +18,18 @@ export declare const APP_LIMITS: Readonly<{
18
18
  sessionMs: number;
19
19
  requestTimeoutMs: 10000;
20
20
  }>;
21
+ /** A captured frame (`app.frame`) is a PNG, JPEG or WebP data URL of at most this many characters; its message may be this much larger than a protocol 1 request. */
22
+ export declare const FRAME_CHARS = 1000000;
23
+ export declare const FRAME_MESSAGE_BYTES: number;
24
+ /** A capture id: the host counts 1, 2, 3 ... per session. */
25
+ export declare const captureId: (value: unknown) => value is string;
26
+ export declare const frameImage: (value: unknown) => value is string;
27
+ /** The desktop camera's answer. Allowed on protocol 1 sessions too; `image` is checked by the host (a bad one is a soft `invalid`). */
28
+ export type AppFrameRequest = {
29
+ method: "app.frame";
30
+ id: string;
31
+ image: string | null;
32
+ };
21
33
  export type AppValue = null | boolean | number | string | AppValue[] | {
22
34
  [key: string]: AppValue;
23
35
  };
@@ -54,6 +66,8 @@ export interface VibeMarketAppSdk {
54
66
  current(): Readonly<AppLifecycle>;
55
67
  onChanged(listener: (state: Readonly<AppLifecycle>) => void): () => void;
56
68
  };
69
+ /** The desktop camera asks for a picture: by default the largest canvas is sent; register a handler (canvas, data URL or null) to draw your own. Latest wins; returns unsubscribe. */
70
+ onCapture?(handler: () => HTMLCanvasElement | string | null | Promise<HTMLCanvasElement | string | null>): () => void;
57
71
  destroy(): void;
58
72
  }
59
73
  export declare function appNonce(value: unknown): value is string;
@@ -65,6 +79,6 @@ export declare function checkpointJson(input: unknown): string;
65
79
  export declare function checkpointValue(input: unknown): AppValue;
66
80
  export declare function parseAppEnvelope(input: unknown, session: string): {
67
81
  id: string;
68
- request: AppRequest;
82
+ request: AppRequest | AppFrameRequest;
69
83
  };
70
84
  export declare function lifecycleValue(input: unknown): Readonly<AppLifecycle>;
@@ -10,6 +10,12 @@ export const APP_LIMITS = Object.freeze({
10
10
  requestsPerSecond: 10, inFlight: 4, lifetimeRequests: 5000,
11
11
  sessionMs: 15 * 60 * 1000, requestTimeoutMs: 10_000,
12
12
  });
13
+ /** A captured frame (`app.frame`) is a PNG, JPEG or WebP data URL of at most this many characters; its message may be this much larger than a protocol 1 request. */
14
+ export const FRAME_CHARS = 1_000_000;
15
+ export const FRAME_MESSAGE_BYTES = 1_100_000 + 1024;
16
+ /** A capture id: the host counts 1, 2, 3 ... per session. */
17
+ export const captureId = (value) => typeof value === "string" && /^[1-9]\d{0,15}$/.test(value);
18
+ export const frameImage = (value) => typeof value === "string" && value.length <= FRAME_CHARS && /^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+=*$/.test(value);
13
19
  export function appNonce(value) { return typeof value === "string" && /^[a-f0-9]{32}$/.test(value); }
14
20
  export function createAppNonce() {
15
21
  return [...crypto.getRandomValues(new Uint8Array(16))].map(value => value.toString(16).padStart(2, "0")).join("");
@@ -97,6 +103,12 @@ export function parseAppEnvelope(input, session) {
97
103
  || typeof input.id !== "string" || input.id.length > 80 || !/^[A-Za-z0-9_-]{1,80}$/.test(input.id) || !plain(input.request))
98
104
  throw Error("Invalid app session request.");
99
105
  const request = input.request;
106
+ if (request.method === "app.frame") {
107
+ if (!exact(request, ["method", "id", "image"]) || !captureId(request.id) || (request.image !== null && typeof request.image !== "string"))
108
+ throw Error("Invalid app frame.");
109
+ return { id: input.id, request: { method: "app.frame", id: request.id, image: request.image } };
110
+ }
111
+ appJson(input, APP_LIMITS.requestBytes); // every other request keeps its 34 KiB bound
100
112
  if (request.method === "game.finish" && exact(request, ["method", "score"]))
101
113
  return { id: input.id, request: { method: "game.finish", ...gameFinishInput({ score: request.score }) } };
102
114
  if ((request.method === "ui.ready" || request.method === "app.checkpoint.get") && exact(request, ["method"]))
@@ -1,4 +1,4 @@
1
- import { type AppRequest, type AppValue } from "./app-protocol.ts";
1
+ import { captureId, frameImage, type AppRequest, type AppValue } from "./app-protocol.ts";
2
2
  /** The nine stable error codes (section 11.3). Messages may change; codes never do. */
3
3
  export declare const OS_ERROR_CODES: readonly ["unsupported", "not-permitted", "invalid", "too-large", "rate-limited", "needs-click", "unavailable", "timeout", "closed"];
4
4
  export type OsErrorCode = typeof OS_ERROR_CODES[number];
@@ -25,6 +25,9 @@ export declare const APP_SESSION_LIMITS: Readonly<{
25
25
  saveIntervalMs: 10000;
26
26
  /** the largest protocol 2 message: a save plus its envelope */
27
27
  messageBytes: number;
28
+ /** a captured frame (`app.frame`): the data URL's length in characters, and how long the host waits for it by default */
29
+ frameChars: 1000000;
30
+ captureMs: 1200;
28
31
  cardsPage: 500;
29
32
  cardsEventBytes: number;
30
33
  /** the client's own pacing, below the host's hard limits (see transport.ts) */
@@ -115,6 +118,10 @@ export type AppRequest2 = AppRequest | {
115
118
  } | {
116
119
  method: "ui.progress";
117
120
  value: number;
121
+ } | {
122
+ method: "app.frame";
123
+ id: string;
124
+ image: string | null;
118
125
  } | {
119
126
  method: "app.save.get" | "cards.packs" | "player.get";
120
127
  } | {
@@ -127,6 +134,10 @@ export type AppRequest2 = AppRequest | {
127
134
  } | {
128
135
  method: "cards.pack" | "pack.show";
129
136
  pack: string;
137
+ } | {
138
+ method: "card.show";
139
+ pack: string;
140
+ card: string;
130
141
  } | {
131
142
  method: "display.maximize" | "display.fullscreen" | "cards.watch";
132
143
  on: boolean;
@@ -134,10 +145,12 @@ export type AppRequest2 = AppRequest | {
134
145
  export type AppMethod2 = AppRequest2["method"];
135
146
  /** L loading (before ready), F ready and in front, B behind another window (the grace). */
136
147
  type States = "LFB" | "L" | "F";
148
+ /** `bucket` names a soft rate shared by several methods (pack.show and card.show: one per 10 s together). */
137
149
  interface MethodRule {
138
150
  request: number;
139
151
  response: number;
140
152
  rate?: readonly [count: number, windowMs: number];
153
+ bucket?: string;
141
154
  states: States;
142
155
  }
143
156
  /**
@@ -146,9 +159,17 @@ interface MethodRule {
146
159
  * is this package's addition to the contract's table: it is how the host learns the app has an `onCards` listener.
147
160
  */
148
161
  export declare const APP_METHODS_2: Readonly<Record<Exclude<AppMethod2, AppRequest["method"]>, MethodRule>>;
149
- /** Protocol 2 features a hello answers with: the methods beyond protocol 1. */
162
+ /**
163
+ * Protocol 2 features a hello answers with: the methods beyond protocol 1. `card.show` (0.5.1) is listed only by a host whose
164
+ * services can show a card; a 0.5.0 host never lists it, and a client never sends a method its host did not list.
165
+ */
150
166
  export declare const APP_FEATURES_2: readonly string[];
151
167
  export declare const utf8Bytes: (text: string) => number;
168
+ /** Every rejection of the app API. Branch on `code`; `message` is a plain sentence that may change. */
169
+ export declare class OsError extends Error {
170
+ readonly code: OsErrorCode;
171
+ constructor(code: OsErrorCode, message: string);
172
+ }
152
173
  /** An error with one of the nine codes, raised by the host's services or the controller and answered without ending the session. */
153
174
  export declare class AppHostError extends Error {
154
175
  readonly code: OsErrorCode;
@@ -184,6 +205,7 @@ export declare function wireCardsEvent(value: unknown): AppCardsEvent;
184
205
  export declare function wireHello(value: unknown): AppHello;
185
206
  /** The version prefix relative to the entry document: `./` for `index.html`, `../` for `app/index.html`. */
186
207
  export declare const entryRoot: (entry: string) => string;
208
+ export { captureId, frameImage };
187
209
  /**
188
210
  * A protocol 2 request, structurally checked (a violation ends the session). Values a well-behaved client could still get
189
211
  * wrong (a bad slug, a save over the limit) are left for the controller to answer `invalid` or `too-large`.
@@ -191,4 +213,3 @@ export declare const entryRoot: (entry: string) => string;
191
213
  export declare function appRequest2(request: Record<string, unknown>): AppRequest2 | null;
192
214
  /** The protocol 1 bound of a method of protocol 1, the table's bound otherwise. */
193
215
  export declare function methodRule(method: AppMethod2): MethodRule;
194
- export {};