@vibechain/os 0.4.1 → 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 (79) hide show
  1. package/AGENTS.md +76 -48
  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 +95 -31
  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 +7 -7
  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/three/README.md +21 -0
  75. package/examples/vibexp-app/three/index.html +4 -0
  76. package/examples/vibexp-app/three/src/main.ts +45 -0
  77. package/examples/vibexp-app/three/vibemarket.json +19 -0
  78. package/examples/vibexp-app/vibemarket.json +17 -11
  79. package/package.json +6 -2
package/dist/app-host.js CHANGED
@@ -1,26 +1,70 @@
1
1
  import { CHANNEL } from "./channel.js";
2
2
  import { appRuntimeRefusal } from "./app-runtime.js";
3
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";
5
+ import { packSlug } from "./manifest.js";
6
+ /**
7
+ * An apps3 session's request: protocol 1 methods exactly as `parseAppEnvelope` admits them, `host.hello` before hello, and
8
+ * after hello every protocol 2 method within its request bound. Anything else throws (the session ends).
9
+ */
10
+ function envelope2(data, session, hello) {
11
+ if (!data || typeof data !== "object" || Array.isArray(data) || Object.getPrototypeOf(data) !== Object.prototype || Object.keys(data).length !== 3
12
+ || !("session" in data) || data.session !== session || !("id" in data) || typeof data.id !== "string" || !/^[A-Za-z0-9_-]{1,80}$/.test(data.id)
13
+ || !("request" in data) || !data.request || typeof data.request !== "object" || Array.isArray(data.request))
14
+ throw Error("Invalid app session request.");
15
+ const request = appRequest2(data.request);
16
+ const legacy = request !== null && !Object.hasOwn(APP_METHODS_2, request.method);
17
+ if (!request || (!hello && !legacy && request.method !== "host.hello"))
18
+ throw Error("This app has no permission for that method.");
19
+ if (utf8Bytes(JSON.stringify(data.request)) > methodRule(request.method).request)
20
+ throw Error("App request exceeds its bound.");
21
+ return { id: data.id, request };
22
+ }
23
+ /** A sliding window of recent times, at most `limit` of them within `windowMs`. */
24
+ function slidingWindow(limit, windowMs) {
25
+ let times = [];
26
+ return (now) => {
27
+ times = times.filter(time => now - time < windowMs);
28
+ if (times.length >= limit)
29
+ return false;
30
+ times.push(now);
31
+ return true;
32
+ };
33
+ }
34
+ const MESSAGE = {
35
+ states: "That is not available while the app is loading or behind another window.",
36
+ rate: "Too many requests of that kind; try again later.",
37
+ slug: "That is not a pack slug.",
38
+ after: "That page cursor is not valid.",
39
+ unavailable: "The host could not answer that now; try again.",
40
+ };
4
41
  /** A single installation/window owns only the JSON this same app host-accepted. */
5
- export function createAppController(clock = () => performance.now()) {
42
+ export function createAppController(clock = () => performance.now(), options = {}) {
43
+ const services = options.services, apps3 = services !== undefined;
6
44
  let checkpoint = "null", disposed = false, active;
7
45
  let completion, completionNotified = false;
8
46
  const startedAt = clock();
9
47
  if (!Number.isFinite(startedAt))
10
48
  throw Error("App clock is invalid.");
11
- let lastClock = startedAt, intervalAt = startedAt, requests = 0, total = 0;
49
+ let lastClock = startedAt, intervalAt = startedAt, requests = 0, total = 0, lastActivity = startedAt;
12
50
  let terminalReason, activeFault;
51
+ let idleTimer, idleNotified = false;
52
+ let cards;
53
+ const perMinute = slidingWindow(APP_SESSION_LIMITS.requestsPerMinute, 60_000);
54
+ const lifetimeMs = apps3 ? APP_SESSION_LIMITS.sessionMs : APP_LIMITS.sessionMs, lifetimeRequests = apps3 ? APP_SESSION_LIMITS.lifetimeRequests : APP_LIMITS.lifetimeRequests;
55
+ const expired = apps3 ? "App session reached its 4-hour limit. Reopen the app to keep playing." : "App session expired. Reopen the app.";
13
56
  const terminate = (reason) => {
14
57
  if (disposed || terminalReason)
15
58
  return;
16
59
  terminalReason = reason;
17
60
  clearTimeout(expiry);
61
+ clearTimeout(idleTimer);
18
62
  checkpoint = "null";
19
63
  const fault = activeFault;
20
64
  active?.close();
21
65
  fault?.(reason);
22
66
  };
23
- const expiry = setTimeout(() => terminate("App session expired. Reopen the app."), APP_LIMITS.sessionMs);
67
+ const expiry = setTimeout(() => terminate(expired), lifetimeMs);
24
68
  const readTime = () => {
25
69
  let now;
26
70
  try {
@@ -35,14 +79,39 @@ export function createAppController(clock = () => performance.now()) {
35
79
  return undefined;
36
80
  }
37
81
  lastClock = now;
38
- if (now - startedAt >= APP_LIMITS.sessionMs) {
39
- terminate("App session expired. Reopen the app.");
82
+ if (now - startedAt >= lifetimeMs) {
83
+ terminate(expired);
40
84
  return undefined;
41
85
  }
42
86
  return now;
43
87
  };
44
- return {
45
- attach(port, session, options) {
88
+ // apps3 only: the idle prompt after 15 minutes without activity (re-armed by any activity, never extending the 4 hours)
89
+ const armIdle = (delay) => {
90
+ clearTimeout(idleTimer);
91
+ idleTimer = setTimeout(() => {
92
+ const now = readTime();
93
+ if (now === undefined)
94
+ return;
95
+ const quiet = now - lastActivity;
96
+ if (quiet < APP_SESSION_LIMITS.idleMs) {
97
+ armIdle(APP_SESSION_LIMITS.idleMs - quiet);
98
+ return;
99
+ }
100
+ if (!idleNotified) {
101
+ idleNotified = true;
102
+ options.idle?.();
103
+ }
104
+ }, delay);
105
+ };
106
+ const touch = (now) => { lastActivity = now; if (idleNotified) {
107
+ idleNotified = false;
108
+ armIdle(APP_SESSION_LIMITS.idleMs);
109
+ } };
110
+ if (apps3)
111
+ armIdle(APP_SESSION_LIMITS.idleMs);
112
+ const controller = {
113
+ protocol: apps3 ? 2 : 1,
114
+ attach(port, session, attachOptions) {
46
115
  if (disposed || terminalReason || !appNonce(session)) {
47
116
  port.close();
48
117
  throw Error(terminalReason ?? "App controller is closed.");
@@ -52,23 +121,129 @@ export function createAppController(clock = () => performance.now()) {
52
121
  throw Error(terminalReason);
53
122
  }
54
123
  active?.close();
55
- let stopped = false, inFlight = 0;
124
+ let stopped = false, inFlight = 0, hello = false, ready = false, lastId = 0, saving = false, watching = false;
125
+ let baseline;
56
126
  const seen = new Set();
57
- const close = () => { if (stopped)
58
- return; stopped = true; port.onmessage = null; port.onmessageerror = null; port.close(); if (active === handle) {
59
- active = undefined;
60
- activeFault = undefined;
61
- } };
127
+ const soft = new Map();
128
+ const close = () => {
129
+ if (stopped)
130
+ return;
131
+ stopped = true;
132
+ port.onmessage = null;
133
+ port.onmessageerror = null;
134
+ port.close();
135
+ if (active === handle) {
136
+ active = undefined;
137
+ activeFault = undefined;
138
+ cards = undefined;
139
+ }
140
+ };
62
141
  const refuse = (reason) => { if (stopped)
63
- return; close(); options.fault(reason); };
64
- const current = () => !stopped && !disposed && options.current();
142
+ return; close(); attachOptions.fault(reason); };
143
+ const current = () => !stopped && !disposed && attachOptions.current();
144
+ const foreground = attachOptions.foreground ?? (() => true);
145
+ const send = (value, bytes) => { if (current())
146
+ port.postMessage(appJson(value, bytes)); };
65
147
  const handle = {
66
148
  lifecycle(value) { if (current())
67
149
  port.postMessage(appJson({ session, event: "app.lifecycle", state: lifecycleValue(value) }, APP_LIMITS.responseBytes)); },
68
150
  close,
69
151
  };
70
152
  active = handle;
71
- activeFault = options.fault;
153
+ activeFault = attachOptions.fault;
154
+ // A watching app is told what changed since the list it last read whole (or the last event), or to read again.
155
+ if (services)
156
+ cards = async () => {
157
+ if (!watching || !baseline || !current())
158
+ return;
159
+ const next = await services.cards();
160
+ if (!current() || !watching || !baseline || !cardsRevision(next.revision) || next.revision === baseline.revision)
161
+ return;
162
+ const fresh = new Map(next.cards.map(card => { const checked = wireCard(card); return [checked.id, checked]; }));
163
+ const changed = [...fresh.values()].filter(card => JSON.stringify(baseline.cards.get(card.id)) !== JSON.stringify(card));
164
+ const removed = [...baseline.cards.keys()].filter(id => !fresh.has(id));
165
+ let event = { changed, removed, revision: next.revision };
166
+ if (utf8Bytes(JSON.stringify(event)) > APP_SESSION_LIMITS.cardsEventBytes)
167
+ event = { reset: true, revision: next.revision };
168
+ baseline = { revision: next.revision, cards: fresh };
169
+ send({ session, event: "app.cards", state: event }, APP_SESSION_LIMITS.cardsEventBytes + 1024);
170
+ };
171
+ /** One protocol 2 answer. A thrown AppHostError is a soft refusal; anything else from the services is `unavailable`. */
172
+ const answer2 = async (services, request) => {
173
+ const check = (value, valid) => { try {
174
+ return valid(value);
175
+ }
176
+ catch {
177
+ throw new AppHostError("unavailable", MESSAGE.unavailable);
178
+ } };
179
+ switch (request.method) {
180
+ case "host.hello": return { protocol: 2, guest: services.guest, features: [...APP_FEATURES_2], root: entryRoot(services.entry) };
181
+ case "ui.progress":
182
+ // ignored once the app is ready
183
+ if (!ready) {
184
+ if (request.value < 0 || request.value > 1)
185
+ throw new AppHostError("invalid", "Progress is a number from 0 to 1.");
186
+ attachOptions.progress?.(request.value);
187
+ }
188
+ return { completed: true };
189
+ case "app.save.get": {
190
+ const stored = await services.saveGet();
191
+ 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)
192
+ throw Error(); return value; }) };
193
+ }
194
+ case "app.save.set": {
195
+ const text = saveJson(request.value);
196
+ if (saving)
197
+ throw new AppHostError("rate-limited", "A save is already being written.");
198
+ saving = true;
199
+ try {
200
+ const { savedAt } = await services.saveSet(text);
201
+ return { savedAt: check(savedAt, value => { if (typeof value !== "string" || value.length > 30)
202
+ throw Error(); return value; }) };
203
+ }
204
+ finally {
205
+ saving = false;
206
+ }
207
+ }
208
+ case "cards.list": {
209
+ if (request.pack !== undefined && !packSlug(request.pack))
210
+ throw new AppHostError("invalid", MESSAGE.slug);
211
+ const start = request.after === undefined ? 0 : /^(?:0|[1-9]\d{0,5})$/.test(request.after) ? Number(request.after) : -1;
212
+ if (start < 0)
213
+ throw new AppHostError("invalid", MESSAGE.after);
214
+ const all = await services.cards();
215
+ const listed = check(all, value => { if (!cardsRevision(value.revision) || !Array.isArray(value.cards))
216
+ throw Error(); return value.cards.map(wireCard); });
217
+ if (request.pack === undefined && start === 0)
218
+ baseline = { revision: all.revision, cards: new Map(listed.map(card => [card.id, card])) };
219
+ const chosen = request.pack === undefined ? listed : listed.filter(card => card.pack === request.pack);
220
+ const end = start + APP_SESSION_LIMITS.cardsPage;
221
+ return { cards: chosen.slice(start, end), after: end < chosen.length ? String(end) : null, revision: all.revision };
222
+ }
223
+ case "cards.packs": return { packs: check(await services.packs(), value => { if (!Array.isArray(value) || value.length > 200)
224
+ throw Error(); return value.map(wirePackSummary); }) };
225
+ case "cards.pack":
226
+ if (!packSlug(request.pack))
227
+ throw new AppHostError("invalid", MESSAGE.slug);
228
+ return { pack: check(await services.pack(request.pack), value => { const pack = wirePack(value); if (pack.id !== request.pack)
229
+ throw Error(); return pack; }) };
230
+ case "cards.watch":
231
+ watching = request.on;
232
+ return { completed: true };
233
+ case "pack.show":
234
+ if (!packSlug(request.pack))
235
+ throw new AppHostError("invalid", MESSAGE.slug);
236
+ await services.showPack(request.pack);
237
+ return { shown: true };
238
+ case "player.get": return check(await services.player(), wirePlayer);
239
+ case "display.maximize":
240
+ await services.maximize(request.on);
241
+ return { completed: true };
242
+ case "display.fullscreen":
243
+ await services.fullscreen(request.on);
244
+ return { completed: true };
245
+ }
246
+ };
72
247
  port.onmessage = (event) => {
73
248
  if (!current()) {
74
249
  close();
@@ -81,78 +256,159 @@ export function createAppController(clock = () => performance.now()) {
81
256
  intervalAt = now;
82
257
  requests = 0;
83
258
  }
84
- if (++requests > APP_LIMITS.requestsPerSecond || ++total > APP_LIMITS.lifetimeRequests || inFlight >= APP_LIMITS.inFlight) {
259
+ if (++requests > APP_LIMITS.requestsPerSecond || ++total > lifetimeRequests || inFlight >= (hello ? APP_SESSION_LIMITS.inFlight : APP_LIMITS.inFlight)
260
+ || (apps3 && !perMinute(now))) {
85
261
  refuse("App request limit exceeded.");
86
262
  return;
87
263
  }
88
- let message;
264
+ let id, request;
89
265
  try {
90
- message = parseAppEnvelope(parseAppJson(event.data, APP_LIMITS.requestBytes), session);
266
+ if (!apps3)
267
+ ({ id, request } = parseAppEnvelope(parseAppJson(event.data, APP_LIMITS.requestBytes), session));
268
+ else
269
+ ({ id, request } = envelope2(parseAppJson(event.data, hello ? APP_SESSION_LIMITS.messageBytes : APP_LIMITS.requestBytes), session, hello));
91
270
  }
92
271
  catch {
93
272
  refuse("Invalid or unpermitted app request.");
94
273
  return;
95
274
  }
96
- if (seen.has(message.id)) {
97
- refuse("App request was replayed.");
98
- return;
275
+ if (apps3) {
276
+ // every client this package has shipped numbers its requests 1, 2, 3, ... per session
277
+ if (!/^[1-9]\d{0,15}$/.test(id) || Number(id) <= lastId) {
278
+ refuse("App request was replayed.");
279
+ return;
280
+ }
281
+ lastId = Number(id);
282
+ }
283
+ else {
284
+ if (seen.has(id)) {
285
+ refuse("App request was replayed.");
286
+ return;
287
+ }
288
+ seen.add(id);
289
+ }
290
+ if (request.method === "host.hello") {
291
+ if (hello) {
292
+ refuse("App said hello twice.");
293
+ return;
294
+ }
295
+ hello = true;
99
296
  }
100
- seen.add(message.id);
101
297
  inFlight++;
298
+ if (apps3)
299
+ touch(now);
300
+ const method = request.method;
301
+ const legacy = method === "ui.ready" || method === "game.finish" || method === "app.checkpoint.get" || method === "app.checkpoint.set";
302
+ // protocol 1 answers synchronously in the first microtask, exactly as before; protocol 2 returns its promise
102
303
  void Promise.resolve().then(() => {
103
304
  if (!current())
104
305
  return;
105
- let result;
106
- switch (message.request.method) {
107
- case "ui.ready":
108
- options.ready();
109
- result = { completed: true };
110
- break;
111
- case "game.finish":
112
- if (completion && completion.score !== message.request.score)
113
- throw Error("This game has already finished.");
114
- completion ??= Object.freeze({ score: message.request.score });
115
- result = { completed: true };
116
- break;
117
- case "app.checkpoint.get":
118
- result = { checkpoint: JSON.parse(checkpoint) };
119
- break;
120
- case "app.checkpoint.set":
121
- checkpoint = checkpointJson(message.request.value);
122
- result = { completed: true };
123
- break;
124
- }
125
- const response = { session, id: message.id, result };
126
- if (current()) {
127
- port.postMessage(appJson(response, APP_LIMITS.responseBytes));
128
- if (message.request.method === "game.finish" && completion && !completionNotified && current()) {
129
- completionNotified = true;
130
- options.finish?.(completion);
306
+ // backgrounded: a write is withheld exactly as a suspended app's would be lost (see AppAttachOptions)
307
+ if (!foreground() && (method === "game.finish" || method === "app.checkpoint.set"))
308
+ return;
309
+ if (legacy) {
310
+ let result;
311
+ switch (request.method) {
312
+ case "ui.ready":
313
+ ready = true;
314
+ attachOptions.ready();
315
+ result = { completed: true };
316
+ break;
317
+ case "game.finish":
318
+ if (completion && completion.score !== request.score) {
319
+ // an apps3 host answers a changed score as a policy refusal; protocol 1 hosts end the session as before
320
+ if (!apps3)
321
+ throw Error("This game has already finished.");
322
+ send({ session, id, error: "This game has already finished.", code: "invalid" }, APP_LIMITS.responseBytes);
323
+ return;
324
+ }
325
+ completion ??= Object.freeze({ score: request.score });
326
+ result = { completed: true };
327
+ break;
328
+ case "app.checkpoint.get":
329
+ result = { checkpoint: JSON.parse(checkpoint) };
330
+ break;
331
+ default:
332
+ checkpoint = checkpointJson(request.value);
333
+ result = { completed: true };
334
+ break;
335
+ }
336
+ if (current()) {
337
+ port.postMessage(appJson({ session, id, result }, APP_LIMITS.responseBytes));
338
+ if (method === "game.finish" && completion && !completionNotified && current()) {
339
+ completionNotified = true;
340
+ attachOptions.finish?.(completion);
341
+ }
131
342
  }
343
+ return;
132
344
  }
345
+ return reply2(id, request, method, now);
133
346
  }).catch(() => { if (!stopped)
134
347
  refuse("App request could not complete."); }).finally(() => { inFlight--; });
135
348
  };
349
+ const reply2 = async (id, request, method, now) => {
350
+ const rule = methodRule(method);
351
+ let reply;
352
+ try {
353
+ const state = !ready ? "L" : foreground() ? "F" : "B";
354
+ if (!rule.states.includes(state))
355
+ throw new AppHostError("not-permitted", MESSAGE.states);
356
+ // leaving fullscreen is always allowed (section 9.2)
357
+ if (rule.rate && !(request.method === "display.fullscreen" && !request.on)) {
358
+ let limiter = soft.get(method);
359
+ if (!limiter) {
360
+ limiter = slidingWindow(rule.rate[0], rule.rate[1]);
361
+ soft.set(method, limiter);
362
+ }
363
+ if (!limiter(now))
364
+ throw new AppHostError("rate-limited", MESSAGE.rate);
365
+ }
366
+ const result = await answer2(services, request);
367
+ if (utf8Bytes(JSON.stringify(result)) > rule.response)
368
+ throw new AppHostError("unavailable", "The answer is larger than this request may return.");
369
+ reply = { session, id, result };
370
+ }
371
+ catch (error) {
372
+ const code = error instanceof AppHostError ? error.code : "unavailable";
373
+ reply = { session, id, error: error instanceof AppHostError ? error.message.slice(0, 300) : MESSAGE.unavailable, code };
374
+ }
375
+ send(reply, APP_SESSION_LIMITS.messageBytes);
376
+ };
136
377
  port.onmessageerror = () => refuse("App message could not be decoded.");
137
378
  port.start();
138
379
  return handle;
139
380
  },
140
381
  suspend() { active?.close(); },
141
382
  dispose() { if (disposed)
142
- return; disposed = true; clearTimeout(expiry); active?.close(); checkpoint = "null"; },
383
+ return; disposed = true; clearTimeout(expiry); clearTimeout(idleTimer); active?.close(); checkpoint = "null"; },
143
384
  };
385
+ if (apps3) {
386
+ controller.activity = () => { const now = readTime(); if (now !== undefined)
387
+ touch(now); };
388
+ controller.cardsChanged = async () => { try {
389
+ await cards?.();
390
+ }
391
+ catch { /* the next change or read answers again */ } };
392
+ }
393
+ return controller;
144
394
  }
145
- /** Caller supplies the already-validated immutable URL, including this generation's fragment. */
395
+ /**
396
+ * Caller supplies the already-validated immutable URL, including this generation's fragment. With a protocol 2
397
+ * controller the transfer advertises `protocol: 2`, and readiness is `ready()` within 15 s, or `progress()` at least
398
+ * every 15 s and `ready()` within 120 s.
399
+ */
146
400
  export function mountAppFrame(frame, options) {
147
401
  const refusal = appRuntimeRefusal(window);
148
402
  if (refusal)
149
403
  throw Error(refusal);
150
404
  if (!appNonce(options.challenge) || new URL(frame.src).hash !== `#${APP_FRAGMENT}=${options.challenge}`)
151
405
  throw Error("Invalid app frame challenge.");
152
- let ended = false, loaded = false, connected = false, bootstrapMessages = 0, session;
406
+ const protocol2 = options.controller.protocol === 2;
407
+ let ended = false, loaded = false, connected = false, bootstrapMessages = 0, session, readied = false;
153
408
  let bounds = lifecycleValue({ active: true, width: 0, height: 0 });
409
+ const slow = () => fault("App took too long to become ready.");
154
410
  const dispose = () => { if (ended)
155
- return; ended = true; clearTimeout(timeout); frame.removeEventListener("load", load); window.removeEventListener("message", connect); session?.close(); };
411
+ return; ended = true; clearTimeout(timeout); clearTimeout(ceiling); frame.removeEventListener("load", load); window.removeEventListener("message", connect); session?.close(); };
156
412
  const fault = (message) => { if (ended)
157
413
  return; dispose(); options.fault(message); };
158
414
  const load = () => { if (loaded)
@@ -184,12 +440,19 @@ export function mountAppFrame(frame, options) {
184
440
  window.removeEventListener("message", connect);
185
441
  const ports = new MessageChannel(), nonce = createAppNonce();
186
442
  try {
187
- session = options.controller.attach(ports.port1, nonce, { current: options.current,
188
- ready() { clearTimeout(timeout); options.ready(); }, finish: options.finish, fault });
443
+ session = options.controller.attach(ports.port1, nonce, { current: options.current, foreground: options.foreground,
444
+ ready() { readied = true; clearTimeout(timeout); clearTimeout(ceiling); options.ready(); }, finish: options.finish, fault,
445
+ progress(fraction) {
446
+ if (readied || ended)
447
+ return;
448
+ clearTimeout(timeout);
449
+ timeout = setTimeout(slow, APP_SESSION_LIMITS.readyMs);
450
+ options.progress?.(fraction);
451
+ } });
189
452
  // Opaque frames require wildcard targetOrigin; the exact WindowProxy/challenge bind this transfer.
190
453
  if (!frame.contentWindow)
191
454
  throw Error("App frame is unavailable.");
192
- frame.contentWindow.postMessage({ channel: CHANNEL, challenge: options.challenge, session: nonce }, "*", [ports.port2]);
455
+ frame.contentWindow.postMessage({ channel: CHANNEL, challenge: options.challenge, session: nonce, ...(protocol2 ? { protocol: 2 } : {}) }, "*", [ports.port2]);
193
456
  session.lifecycle(bounds);
194
457
  }
195
458
  catch {
@@ -198,11 +461,29 @@ export function mountAppFrame(frame, options) {
198
461
  fault("App connection could not complete.");
199
462
  }
200
463
  };
201
- const timeout = setTimeout(() => fault("App took too long to become ready."), 15_000);
464
+ let timeout = setTimeout(slow, APP_SESSION_LIMITS.readyMs);
465
+ const ceiling = protocol2 ? setTimeout(slow, APP_SESSION_LIMITS.progressReadyMs) : undefined;
202
466
  frame.addEventListener("load", load);
203
467
  window.addEventListener("message", connect);
204
468
  return {
205
- 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); },
469
+ resize(width, height) { bounds = lifecycleValue({ active: bounds.active, width: Math.min(4096, Math.max(0, Math.floor(width))), height: Math.min(4096, Math.max(0, Math.floor(height))) }); session?.lifecycle(bounds); },
470
+ setActive(active) { if (active === bounds.active)
471
+ return; bounds = lifecycleValue({ ...bounds, active }); session?.lifecycle(bounds); },
206
472
  dispose,
207
473
  };
208
474
  }
475
+ /**
476
+ * The backend's card read as an app sees it, for an apps3 host's services: rarity numbers named, ids joined, and art as the
477
+ * path after the version prefix only where the backend has servable art and the card id can be a path segment.
478
+ */
479
+ export function appCardsView(reply) {
480
+ const rarities = ["common", "rare", "epic", "legendary", "mythic"];
481
+ return {
482
+ packs: reply.packs.map(pack => wirePackSummary({ id: pack.slug, name: pack.name, creator: pack.creator, art: pack.cover ? coverArtPath(pack.slug) : null, held: pack.held, total: pack.total })),
483
+ cards: reply.cards.map(card => wireCard({
484
+ id: `${card.pack}/${card.card}`, pack: card.pack, name: card.name, rarity: rarities[card.rarity] ?? "common", count: card.count,
485
+ art: card.art && CARD_ID.test(card.card) ? cardArtPath(card.pack, card.card) : null,
486
+ })),
487
+ revision: reply.revision,
488
+ };
489
+ }
@@ -39,11 +39,13 @@ export interface AppLifecycle {
39
39
  width: number;
40
40
  height: number;
41
41
  }
42
+ /** @deprecated The 0.4 app API. Use `connect()` and its `Os`; `checkpoint` (32 KiB, the open window only) is replaced by `load()` and `save()`. */
42
43
  export interface VibeMarketAppSdk {
43
44
  game: {
44
45
  finish(input: GameFinishInput): Promise<void>;
45
46
  };
46
47
  ready(): Promise<void>;
48
+ /** @deprecated Use `os.load()` and `os.save()` from `connect()`. */
47
49
  checkpoint: {
48
50
  read(): Promise<AppValue>;
49
51
  write(value: AppValue): Promise<void>;
@@ -1,2 +1,18 @@
1
- /** Admission policy for browser hosts; marker absence is not native certification. */
2
- export declare function appRuntimeRefusal(host: Window): string | null;
1
+ export declare const UNSUPPORTED_HOST_REFUSAL = "Third-party apps are available only on vibechain.com and in the local browser developer preview.";
2
+ export declare const FRAMED_HOST_REFUSAL = "Third-party apps require a top-level browser host.";
3
+ export declare const NATIVE_SHELL_REFUSAL = "Third-party apps are disabled in native shells until their IPC isolation is verified.";
4
+ export type ShippedClientPlatform = "windows" | "macos" | "linux";
5
+ /**
6
+ * Shipped VibeMarket Steam client builds admitted by platform, held by the website. Those builds carry no version, no
7
+ * custom user agent and no `appFrames` key, so the platform their webview's default user agent names is all that tells
8
+ * them apart. A 1 means the owner admitted that platform on the evidence recorded beside the entry: either a person ran
9
+ * the frame probe (vibechain/components/os-apps/frame-probe) inside the shipped client and every row came back
10
+ * unreachable, or the automated frame harness (vibemarket-desktop/docs/FRAME-HARNESS.md: the shipped build's own
11
+ * configuration and pinned framework on that platform's webview, with a native-side log) found that no command body ran
12
+ * because of a frame. Flipping an entry is a reviewed change to this table and its pinned test, never configuration.
13
+ */
14
+ export declare const SHIPPED_CLIENT_FRAMES: Readonly<Record<ShippedClientPlatform, 0 | 1>>;
15
+ /** The platform a webview's default user agent names, or null when it is not exactly one of them (unknown refuses). */
16
+ export declare function webviewPlatform(userAgent: string): ShippedClientPlatform | null;
17
+ /** Admission policy for browser hosts; marker absence is not native certification. `frames` is for tests only. */
18
+ export declare function appRuntimeRefusal(host: Window, frames?: Readonly<Record<ShippedClientPlatform, 0 | 1>>): string | null;
@@ -1,19 +1,83 @@
1
1
  const LOCAL_HOSTS = ["127.0.0.1", "localhost"];
2
2
  const PRODUCTION_HOSTS = ["vibechain.com", "www.vibechain.com"];
3
+ /** Bridge markers the VibeMarket Steam client always carries: its own page marker and the Tauri IPC internals. */
4
+ const STEAM_CLIENT_MARKERS = ["__VM_STEAM__", "__TAURI_INTERNALS__"];
5
+ /** Every other known native bridge marker, refused even in a Steam client that claims app frames. */
6
+ const OTHER_NATIVE_MARKERS = ["__TAURI__", "vibeNative", "ReactNativeWebView"];
7
+ const EMBEDDED_AGENT = /\b(Tauri|Electron|VibeSteam|VibeMarketDesktop|wv)\b/i;
8
+ export const UNSUPPORTED_HOST_REFUSAL = "Third-party apps are available only on vibechain.com and in the local browser developer preview.";
9
+ export const FRAMED_HOST_REFUSAL = "Third-party apps require a top-level browser host.";
10
+ export const NATIVE_SHELL_REFUSAL = "Third-party apps are disabled in native shells until their IPC isolation is verified.";
3
11
  /** The local developer preview over http on any port, or the VibeMarket OS website over https on its default port. */
4
- function admittedHost({ protocol, hostname, port }) {
12
+ function hostKind({ protocol, hostname, port }) {
5
13
  if (protocol === "http:")
6
- return LOCAL_HOSTS.includes(hostname);
7
- return protocol === "https:" && PRODUCTION_HOSTS.includes(hostname) && port === "";
14
+ return LOCAL_HOSTS.includes(hostname) ? "local" : null;
15
+ return protocol === "https:" && PRODUCTION_HOSTS.includes(hostname) && port === "" ? "production" : null;
8
16
  }
9
- /** Admission policy for browser hosts; marker absence is not native certification. */
10
- export function appRuntimeRefusal(host) {
11
- if (!admittedHost(host.location))
12
- return "Third-party apps are available only on vibechain.com and in the local browser developer preview.";
17
+ /** An own data property's value, read once from its descriptor: an accessor or inherited property reads as absent and no getter runs. */
18
+ function ownValue(target, key) {
19
+ const descriptor = Object.getOwnPropertyDescriptor(target, key);
20
+ return descriptor && "value" in descriptor ? descriptor.value : undefined;
21
+ }
22
+ /**
23
+ * Shipped VibeMarket Steam client builds admitted by platform, held by the website. Those builds carry no version, no
24
+ * custom user agent and no `appFrames` key, so the platform their webview's default user agent names is all that tells
25
+ * them apart. A 1 means the owner admitted that platform on the evidence recorded beside the entry: either a person ran
26
+ * the frame probe (vibechain/components/os-apps/frame-probe) inside the shipped client and every row came back
27
+ * unreachable, or the automated frame harness (vibemarket-desktop/docs/FRAME-HARNESS.md: the shipped build's own
28
+ * configuration and pinned framework on that platform's webview, with a native-side log) found that no command body ran
29
+ * because of a frame. Flipping an entry is a reviewed change to this table and its pinned test, never configuration.
30
+ */
31
+ export const SHIPPED_CLIENT_FRAMES = Object.freeze({
32
+ // 2026-11-23, owner decision on the automated harness run in GitHub Actions (run 45240306277), shipped configuration
33
+ // (BuildID 26695918) and guarded tree both NOT REACHED: vibemarket-desktop/docs/frame-probe-results/ci-2026-11-23.md.
34
+ // Not the players' binary and not their own webview runtime; no person has run the probe in the shipped client.
35
+ windows: 1, // WebView2 157.0.4341.46 on windows-latest
36
+ macos: 1, // WebKit 21624.5.1.11.3 on macos-latest, and 22625.2.8.11.9 on the owner's Mac
37
+ linux: 1, // WebKitGTK 2.52.6 on ubuntu-latest (not the Steam Runtime, not a Steam Deck)
38
+ });
39
+ /**
40
+ * The default user agent each platform's webview presents, matched whole: WebView2 (Edge's agent, Windows NT), WKWebView
41
+ * (Macintosh, no Version/Safari tokens, unlike Safari itself) and WebKitGTK (X11; Linux). Anything else, including every
42
+ * real browser on Windows and macOS and any agent with an extra token, is no platform.
43
+ */
44
+ const WEBVIEW_AGENTS = [
45
+ ["windows", /^Mozilla\/5\.0 \(Windows NT \d+\.\d+; Win64; x64\) AppleWebKit\/537\.36 \(KHTML, like Gecko\) Chrome\/\d+(?:\.\d+){3} Safari\/537\.36 Edg\/\d+(?:\.\d+){3}$/],
46
+ ["macos", /^Mozilla\/5\.0 \(Macintosh; Intel Mac OS X \d+(?:_\d+){1,2}\) AppleWebKit\/\d+(?:\.\d+){0,3} \(KHTML, like Gecko\)$/],
47
+ ["linux", /^Mozilla\/5\.0 \(X11; Linux (?:x86_64|aarch64)\) AppleWebKit\/\d+(?:\.\d+){0,3} \(KHTML, like Gecko\)(?: Version\/\d+(?:\.\d+){0,3} Safari\/\d+(?:\.\d+){0,3})?$/],
48
+ ];
49
+ /** The platform a webview's default user agent names, or null when it is not exactly one of them (unknown refuses). */
50
+ export function webviewPlatform(userAgent) {
51
+ return WEBVIEW_AGENTS.find(([, agent]) => agent.test(userAgent))?.[0] ?? null;
52
+ }
53
+ /**
54
+ * Whether the Steam client's own markers stand admitted. `window.__VM_STEAM__` must be an own data property holding a plain
55
+ * object (frozen or not). Then either the page claims the app-frame guard, an own data property `appFrames` that is exactly
56
+ * the number 1 (a claim, not proof of the guard), or the webview's default user agent names a platform whose shipped
57
+ * client the website's table admits.
58
+ */
59
+ function steamClientAdmitted(host, userAgent, frames) {
60
+ const marker = ownValue(host, "__VM_STEAM__");
61
+ if (typeof marker !== "object" || marker === null)
62
+ return false;
63
+ const prototype = Object.getPrototypeOf(marker);
64
+ if (prototype !== Object.prototype && prototype !== null)
65
+ return false;
66
+ if (ownValue(marker, "appFrames") === 1)
67
+ return true;
68
+ const platform = webviewPlatform(userAgent);
69
+ return platform !== null && frames[platform] === 1;
70
+ }
71
+ /** Admission policy for browser hosts; marker absence is not native certification. `frames` is for tests only. */
72
+ export function appRuntimeRefusal(host, frames = SHIPPED_CLIENT_FRAMES) {
73
+ const kind = hostKind(host.location);
74
+ if (kind === null)
75
+ return UNSUPPORTED_HOST_REFUSAL;
13
76
  if (host.top !== host.self)
14
- return "Third-party apps require a top-level browser host.";
15
- if (["__VM_STEAM__", "__TAURI_INTERNALS__", "__TAURI__", "vibeNative", "ReactNativeWebView"].some(key => key in host)
16
- || /\b(Tauri|Electron|VibeSteam|VibeMarketDesktop|wv)\b/i.test(host.navigator.userAgent))
17
- return "Third-party apps are disabled in native shells until their IPC isolation is verified.";
77
+ return FRAMED_HOST_REFUSAL;
78
+ const userAgent = host.navigator.userAgent;
79
+ const markers = kind === "production" && steamClientAdmitted(host, userAgent, frames) ? OTHER_NATIVE_MARKERS : [...STEAM_CLIENT_MARKERS, ...OTHER_NATIVE_MARKERS];
80
+ if (markers.some(key => key in host) || EMBEDDED_AGENT.test(userAgent))
81
+ return NATIVE_SHELL_REFUSAL;
18
82
  return null;
19
83
  }