@kehto/paja 0.24.4 → 0.25.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.
@@ -5408,8 +5408,8 @@ function handleMediaMessage(context, windowId, msg) {
5408
5408
  hooks.sendToNapplet(windowId, {
5409
5409
  type: "media.session.create.result",
5410
5410
  id: m.id ?? "",
5411
- sessionId: m.sessionId ?? "",
5412
- owner: m.owner
5411
+ owner: m.owner,
5412
+ error: "media service unavailable"
5413
5413
  });
5414
5414
  }
5415
5415
  }
@@ -5844,11 +5844,15 @@ function createRuntime(hooks) {
5844
5844
  });
5845
5845
  let incRuntime = null;
5846
5846
  const aclState = createAclState(hooks.aclPersistence, "permissive", (mutation) => {
5847
- if (mutation.type === "revoke" && mutation.capability !== "relay:read") return;
5848
5847
  for (const entry of sessionRegistry2.getAllEntries()) {
5849
5848
  if (entry.dTag === mutation.dTag && entry.aggregateHash === mutation.aggregateHash) {
5850
- revokeRelaySubscriptions({ hooks, serviceRegistry, subscriptions }, entry.windowId);
5851
- incRuntime?.revokeWindow(entry.windowId);
5849
+ for (const service of Object.values(serviceRegistry)) {
5850
+ service.onCapabilityRevoked?.(entry.windowId, mutation.type === "block" ? null : mutation.capability);
5851
+ }
5852
+ if (mutation.type === "block" || mutation.capability === "relay:read") {
5853
+ revokeRelaySubscriptions({ hooks, serviceRegistry, subscriptions }, entry.windowId);
5854
+ incRuntime?.revokeWindow(entry.windowId);
5855
+ }
5852
5856
  }
5853
5857
  }
5854
5858
  });
@@ -8270,7 +8274,30 @@ function createKeysService(options = {}) {
8270
8274
  }
8271
8275
  };
8272
8276
  }
8273
- var SILENT_AUDIO_DATA_URL = "data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YQAAAAA=";
8277
+ function validMediaCommand(command, actions) {
8278
+ if (!actions.includes(command.action)) return false;
8279
+ if (command.action !== "seek" && command.action !== "volume") return true;
8280
+ return typeof command.value === "number" && Number.isFinite(command.value) && command.value >= 0 && (command.action !== "volume" || command.value <= 1);
8281
+ }
8282
+ function silentAudioDataUrl() {
8283
+ const samples = 4e3;
8284
+ const bytes = new Uint8Array(44 + samples * 2);
8285
+ const view = new DataView(bytes.buffer);
8286
+ bytes.set(new TextEncoder().encode("RIFF"), 0);
8287
+ view.setUint32(4, bytes.length - 8, true);
8288
+ bytes.set(new TextEncoder().encode("WAVEfmt "), 8);
8289
+ view.setUint32(16, 16, true);
8290
+ view.setUint16(20, 1, true);
8291
+ view.setUint16(22, 1, true);
8292
+ view.setUint32(24, samples, true);
8293
+ view.setUint32(28, samples * 2, true);
8294
+ view.setUint16(32, 2, true);
8295
+ view.setUint16(34, 16, true);
8296
+ bytes.set(new TextEncoder().encode("data"), 36);
8297
+ view.setUint32(40, samples * 2, true);
8298
+ return `data:audio/wav;base64,${btoa(String.fromCharCode(...bytes))}`;
8299
+ }
8300
+ var SILENT_AUDIO_DATA_URL = silentAudioDataUrl();
8274
8301
  var DEFAULT_MEDIA_ACTIONS = ["play", "pause", "next", "prev", "seek"];
8275
8302
  var ACTION_MATRIX = [
8276
8303
  ["play", "play"],
@@ -8284,7 +8311,7 @@ function createBrowserMediaBridge(opts = {}) {
8284
8311
  const doc = opts.documentTarget !== void 0 ? opts.documentTarget : typeof document !== "undefined" ? document : null;
8285
8312
  let silentAudioEl = null;
8286
8313
  let activeSessionId = null;
8287
- let sessionsActive = 0;
8314
+ const sessionsActive = /* @__PURE__ */ new Set();
8288
8315
  const actionCallbacks = /* @__PURE__ */ new Set();
8289
8316
  function primeSilentAudio() {
8290
8317
  if (silentAudioEl || !doc) return;
@@ -8320,13 +8347,16 @@ function createBrowserMediaBridge(opts = {}) {
8320
8347
  }
8321
8348
  continue;
8322
8349
  }
8323
- ms.setActionHandler(domAction, (details) => {
8324
- if (!activeSessionId) return;
8325
- const value = napAction === "seek" && typeof details?.seekTime === "number" ? details.seekTime : void 0;
8326
- for (const cb of actionCallbacks) {
8327
- cb(activeSessionId, napAction, value);
8328
- }
8329
- });
8350
+ try {
8351
+ ms.setActionHandler(domAction, (details) => {
8352
+ if (!activeSessionId) return;
8353
+ const value = napAction === "seek" && typeof details?.seekTime === "number" ? details.seekTime : void 0;
8354
+ for (const cb of actionCallbacks) {
8355
+ cb(activeSessionId, napAction, value);
8356
+ }
8357
+ });
8358
+ } catch {
8359
+ }
8330
8360
  }
8331
8361
  }
8332
8362
  function writeMetadata(metadata) {
@@ -8378,256 +8408,239 @@ function createBrowserMediaBridge(opts = {}) {
8378
8408
  }
8379
8409
  return;
8380
8410
  }
8381
- if (sessionsActive === 0) {
8382
- primeSilentAudio();
8383
- sessionsActive = 1;
8384
- }
8411
+ if (sessionsActive.size === 0) primeSilentAudio();
8412
+ sessionsActive.add(sessionId);
8385
8413
  applyActionHandlers(actions ?? DEFAULT_MEDIA_ACTIONS);
8386
8414
  },
8387
- destroySession(_sessionId) {
8388
- sessionsActive = Math.max(0, sessionsActive - 1);
8389
- if (sessionsActive === 0) teardownSilentAudio();
8415
+ destroySession(sessionId) {
8416
+ sessionsActive.delete(sessionId);
8417
+ if (sessionsActive.size === 0) teardownSilentAudio();
8390
8418
  }
8391
8419
  };
8392
8420
  }
8393
- var MEDIA_SERVICE_VERSION = "1.1.0";
8394
- function createMediaServiceState(options, bridge) {
8395
- return {
8396
- bridge,
8397
- options,
8398
- sessionRegistry: /* @__PURE__ */ new Map(),
8399
- windowSessions: /* @__PURE__ */ new Map(),
8400
- sendHandles: /* @__PURE__ */ new Map(),
8401
- activeSessionId: null,
8402
- touchCounter: 0,
8403
- sessionCounter: 0
8404
- };
8405
- }
8406
- function setActive(state, sessionId, actions) {
8407
- state.activeSessionId = sessionId;
8408
- state.bridge.setActiveSession?.(sessionId, actions);
8409
- if (!sessionId) return;
8410
- const entry = state.sessionRegistry.get(sessionId);
8411
- if (!entry) return;
8412
- if (entry.metadata) state.bridge.setMetadata(sessionId, entry.metadata);
8413
- if (entry.state) state.bridge.setPlaybackState(sessionId, entry.state.status);
8414
- }
8415
- function promoteNextActiveOrClear(state) {
8416
- if (state.sessionRegistry.size === 0) {
8417
- setActive(state, null);
8418
- return;
8419
- }
8420
- let latest = null;
8421
- for (const entry of state.sessionRegistry.values()) {
8422
- if (!latest || entry.lastTouched > latest.lastTouched) latest = entry;
8423
- }
8424
- setActive(state, latest ? latest.sessionId : null, latest?.actions);
8425
- }
8426
- function sendMediaCommand(state, sessionId, action, value) {
8427
- const entry = state.sessionRegistry.get(sessionId);
8428
- if (!entry) return;
8429
- const send = state.sendHandles.get(entry.windowId);
8430
- if (!send) return;
8431
- const payload = {
8432
- type: "media.command",
8433
- sessionId,
8434
- action,
8435
- ...typeof value === "number" ? { value } : {}
8436
- };
8437
- send(payload);
8438
- }
8439
- function registerWindowSession(state, windowId, sessionId) {
8440
- if (!state.windowSessions.has(windowId)) state.windowSessions.set(windowId, /* @__PURE__ */ new Set());
8441
- state.windowSessions.get(windowId).add(sessionId);
8442
- }
8443
- function sendSessionCreateResult(send, id, fields) {
8444
- send({
8445
- type: "media.session.create.result",
8446
- id: id ?? "",
8447
- ...fields
8448
- });
8449
- }
8450
- function isMediaPlaybackOwner(value) {
8451
- return value === "shell" || value === "napplet";
8452
- }
8453
- function hasSourceRef(source) {
8454
- if (!source) return false;
8455
- if (typeof source.url === "string" && source.url.length > 0) return true;
8456
- if (typeof source.blossomHash === "string" && source.blossomHash.length > 0) return true;
8457
- if (source.nostr) {
8458
- return Boolean(source.nostr.eventId || source.nostr.address);
8459
- }
8460
- return false;
8461
- }
8462
- function canonicalizeSessionId(state, windowId, preferredSessionId) {
8463
- const trimmed = typeof preferredSessionId === "string" ? preferredSessionId.trim() : "";
8464
- const hint2 = trimmed || `session-${++state.sessionCounter}`;
8465
- if (!state.sessionRegistry.has(hint2)) return hint2;
8466
- let next;
8467
- do {
8468
- next = `${windowId}:${hint2}:${++state.sessionCounter}`;
8469
- } while (state.sessionRegistry.has(next));
8470
- return next;
8471
- }
8472
- function handleSessionCreate(state, windowId, message2, send) {
8473
- if (!isMediaPlaybackOwner(message2.owner)) {
8474
- sendSessionCreateResult(send, message2.id, { error: "missing owner" });
8475
- return;
8476
- }
8477
- if (message2.owner === "shell") {
8478
- if (!hasSourceRef(message2.source)) {
8479
- sendSessionCreateResult(send, message2.id, { owner: "shell", error: "missing source" });
8480
- return;
8481
- }
8482
- sendSessionCreateResult(send, message2.id, { owner: "shell", error: "unsupported owner mode" });
8483
- return;
8484
- }
8485
- state.sendHandles.set(windowId, send);
8486
- const sessionId = canonicalizeSessionId(state, windowId, message2.sessionId);
8487
- const entry = {
8488
- sessionId,
8489
- windowId,
8490
- owner: message2.owner,
8491
- source: message2.source,
8492
- metadata: message2.metadata,
8493
- state: void 0,
8494
- actions: message2.capabilities ?? DEFAULT_MEDIA_ACTIONS,
8495
- lastTouched: ++state.touchCounter
8496
- };
8497
- state.sessionRegistry.set(sessionId, entry);
8498
- registerWindowSession(state, windowId, sessionId);
8499
- setActive(state, sessionId, entry.actions);
8500
- state.options.onSessionCreate?.(windowId, sessionId, message2.metadata);
8501
- sendSessionCreateResult(send, message2.id, { sessionId, owner: message2.owner });
8502
- }
8503
- function handleSessionUpdate(state, windowId, message2) {
8504
- const entry = state.sessionRegistry.get(message2.sessionId);
8505
- if (entry) {
8506
- entry.metadata = { ...entry.metadata, ...message2.metadata };
8507
- entry.lastTouched = ++state.touchCounter;
8508
- if (entry.owner === "napplet" && message2.sessionId === state.activeSessionId && entry.metadata) {
8509
- state.bridge.setMetadata(message2.sessionId, entry.metadata);
8510
- }
8421
+ var MEDIA_SERVICE_VERSION = "1.2.0";
8422
+ var MediaRegistry = class {
8423
+ constructor(options, bridge) {
8424
+ this.options = options;
8425
+ this.bridge = bridge;
8511
8426
  }
8512
- state.options.onSessionUpdate?.(windowId, message2.sessionId, message2.metadata);
8513
- }
8514
- function handleSessionDestroy(state, windowId, message2) {
8515
- const entry = state.sessionRegistry.get(message2.sessionId);
8516
- if (entry) {
8517
- state.sessionRegistry.delete(message2.sessionId);
8518
- const set = state.windowSessions.get(entry.windowId);
8519
- if (set) {
8520
- set.delete(message2.sessionId);
8521
- if (set.size === 0) state.windowSessions.delete(entry.windowId);
8522
- }
8523
- state.bridge.destroySession?.(message2.sessionId);
8524
- if (message2.sessionId === state.activeSessionId) promoteNextActiveOrClear(state);
8525
- }
8526
- state.options.onSessionDestroy?.(windowId, message2.sessionId);
8527
- }
8528
- function handleMediaState(state, windowId, message2) {
8529
- const entry = state.sessionRegistry.get(message2.sessionId);
8530
- if (entry?.owner === "napplet") {
8531
- entry.state = {
8532
- status: message2.status,
8533
- position: message2.position,
8534
- duration: message2.duration,
8535
- volume: message2.volume
8427
+ options;
8428
+ bridge;
8429
+ sessions = /* @__PURE__ */ new Map();
8430
+ pending = /* @__PURE__ */ new Map();
8431
+ // Kept until endpoint teardown: retired identifiers must never be reused.
8432
+ used = /* @__PURE__ */ new Map();
8433
+ listeners = /* @__PURE__ */ new Set();
8434
+ active = null;
8435
+ counter = 0;
8436
+ destroyed = false;
8437
+ snapshots() {
8438
+ return [...this.sessions.values()].map(({ send: _send, playback: _playback, ...snapshot }) => structuredClone(snapshot));
8439
+ }
8440
+ changed() {
8441
+ for (const listener of this.listeners) listener(this.snapshots());
8442
+ }
8443
+ activate(sessionId) {
8444
+ this.active = sessionId;
8445
+ const entry = sessionId ? this.sessions.get(sessionId) : void 0;
8446
+ this.bridge.setActiveSession?.(sessionId, entry?.actions);
8447
+ if (entry?.metadata) {
8448
+ const { artwork: _artwork, ...metadata } = entry.metadata;
8449
+ this.bridge.setMetadata(entry.sessionId, metadata);
8450
+ }
8451
+ if (entry?.state) this.bridge.setPlaybackState(entry.sessionId, entry.state.status);
8452
+ }
8453
+ canonicalId(windowId, hint2) {
8454
+ const ids = this.used.get(windowId) ?? /* @__PURE__ */ new Set();
8455
+ this.used.set(windowId, ids);
8456
+ let value = typeof hint2 === "string" && hint2.trim() ? hint2.trim() : `media-${++this.counter}`;
8457
+ while ([...this.used.values()].some((used) => used.has(value))) value = `media-${++this.counter}`;
8458
+ ids.add(value);
8459
+ return value;
8460
+ }
8461
+ retire(sessionId, reason = "destroyed", notify2 = true) {
8462
+ const entry = this.sessions.get(sessionId);
8463
+ if (!entry) return;
8464
+ this.sessions.delete(sessionId);
8465
+ entry.playback?.destroy();
8466
+ this.bridge.destroySession?.(sessionId);
8467
+ if (this.active === sessionId) this.activate([...this.sessions.keys()].at(-1) ?? null);
8468
+ if (notify2) entry.send({ type: "media.session.ended", sessionId, reason });
8469
+ this.options.onSessionDestroy?.(entry.windowId, sessionId);
8470
+ this.changed();
8471
+ }
8472
+ command(sessionId, command) {
8473
+ const entry = this.sessions.get(sessionId);
8474
+ if (!entry || !validMediaCommand(command, entry.actions)) return;
8475
+ const safeCommand = { ...command, reason: "user" };
8476
+ if (entry.playback) entry.playback.command(safeCommand);
8477
+ else entry.send({ ...safeCommand, type: "media.command", sessionId });
8478
+ }
8479
+ publishState(entry, state, actions) {
8480
+ if (this.sessions.get(entry.sessionId) !== entry) return;
8481
+ const capabilitiesChanged = JSON.stringify(entry.actions) !== JSON.stringify(actions);
8482
+ entry.state = state;
8483
+ entry.actions = [...actions];
8484
+ if (state.status === "playing" || this.active === entry.sessionId) this.activate(entry.sessionId);
8485
+ if (entry.owner === "shell") {
8486
+ entry.send({ ...state, type: "media.state", sessionId: entry.sessionId });
8487
+ if (capabilitiesChanged) this.sendCapabilities(entry);
8488
+ }
8489
+ this.options.onState?.(entry.windowId, entry.sessionId, state);
8490
+ this.changed();
8491
+ }
8492
+ sendCapabilities(entry) {
8493
+ const { sessionId } = entry;
8494
+ if (this.sessions.get(sessionId) !== entry) return;
8495
+ if (entry.owner === "shell") entry.send({ type: "media.capabilities", sessionId, actions: [...entry.actions] });
8496
+ if (this.sessions.get(sessionId) !== entry) return;
8497
+ entry.send({ type: "media.controls", sessionId, controls: [...entry.actions] });
8498
+ }
8499
+ create(windowId, msg, send) {
8500
+ const fail2 = (error) => send({ type: "media.session.create.result", id: msg.id ?? "", ...msg.owner === "shell" || msg.owner === "napplet" ? { owner: msg.owner } : {}, error });
8501
+ if (this.destroyed) return;
8502
+ if (msg.owner !== "napplet" && msg.owner !== "shell") return fail2("missing owner");
8503
+ const count = [...this.sessions.values()].filter((entry2) => entry2.windowId === windowId).length + [...this.pending.values()].filter((pending) => pending.windowId === windowId).length;
8504
+ if (count >= (this.options.maxSessionsPerWindow ?? 16)) return fail2("session limit exceeded");
8505
+ if (msg.owner === "shell" && !msg.source) return fail2("missing source");
8506
+ if (msg.owner === "shell" && !this.options.playback) return fail2("unsupported owner mode");
8507
+ const entry = {
8508
+ sessionId: this.canonicalId(windowId, msg.sessionId),
8509
+ windowId,
8510
+ owner: msg.owner,
8511
+ metadata: msg.metadata,
8512
+ context: msg.context,
8513
+ actions: normalizeActions(msg.capabilities),
8514
+ send
8536
8515
  };
8537
- entry.lastTouched = ++state.touchCounter;
8538
- if (state.activeSessionId !== message2.sessionId) setActive(state, message2.sessionId, entry.actions);
8539
- else state.bridge.setPlaybackState(message2.sessionId, message2.status);
8540
- }
8541
- state.options.onState?.(windowId, message2.sessionId, message2);
8542
- }
8543
- function handleMediaCapabilities(state, windowId, message2) {
8544
- const entry = state.sessionRegistry.get(message2.sessionId);
8545
- if (entry?.owner === "napplet") {
8546
- entry.actions = message2.actions;
8547
- entry.lastTouched = ++state.touchCounter;
8548
- if (message2.sessionId === state.activeSessionId) {
8549
- state.bridge.setActiveSession?.(message2.sessionId, entry.actions);
8550
- }
8551
- }
8552
- state.options.onCapabilities?.(windowId, message2.sessionId, message2.actions);
8553
- }
8554
- function handleMediaMessage2(state, windowId, message2, send) {
8555
- switch (message2.type) {
8556
- case "media.session.create":
8557
- handleSessionCreate(state, windowId, message2, send);
8558
- return;
8559
- case "media.session.update":
8560
- handleSessionUpdate(state, windowId, message2);
8561
- return;
8562
- case "media.session.destroy":
8563
- handleSessionDestroy(state, windowId, message2);
8564
- return;
8565
- case "media.state":
8566
- handleMediaState(state, windowId, message2);
8567
- return;
8568
- case "media.capabilities":
8569
- handleMediaCapabilities(state, windowId, message2);
8570
- return;
8571
- default: {
8572
- const id = message2.id ?? "";
8573
- send({
8574
- type: `${message2.type}.error`,
8575
- id,
8576
- error: `Unknown media method: ${message2.type}`
8577
- });
8516
+ if (msg.owner === "napplet") return this.accept(entry, msg.id);
8517
+ const abort = new AbortController();
8518
+ this.pending.set(abort, { windowId, fail: fail2 });
8519
+ const changed = (state, actions) => this.publishState(entry, state, actions);
8520
+ void Promise.resolve().then(() => {
8521
+ if (abort.signal.aborted) throw new Error("endpoint closed");
8522
+ return this.options.playback.open(windowId, msg, abort.signal, changed);
8523
+ }).then((playback) => {
8524
+ if (abort.signal.aborted || this.destroyed) return playback.destroy();
8525
+ this.pending.delete(abort);
8526
+ entry.playback = playback;
8527
+ entry.state = playback.state;
8528
+ entry.actions = [...playback.actions];
8529
+ this.accept(entry, msg.id);
8530
+ }).catch(() => {
8531
+ this.pending.delete(abort);
8532
+ if (!abort.signal.aborted && !this.destroyed) fail2("source unavailable or autoplay denied");
8533
+ }).finally(() => this.pending.delete(abort));
8534
+ }
8535
+ accept(entry, id) {
8536
+ this.sessions.set(entry.sessionId, entry);
8537
+ entry.send({ type: "media.session.create.result", id: id ?? "", sessionId: entry.sessionId, owner: entry.owner });
8538
+ if (this.sessions.get(entry.sessionId) !== entry) return;
8539
+ this.activate(entry.sessionId);
8540
+ this.sendCapabilities(entry);
8541
+ if (entry.owner === "shell" && entry.state) this.publishState(entry, entry.state, entry.actions);
8542
+ this.options.onSessionCreate?.(entry.windowId, entry.sessionId, entry.metadata);
8543
+ this.changed();
8544
+ }
8545
+ handle(windowId, message2, send) {
8546
+ if (this.destroyed) return;
8547
+ if (message2.type === "media.session.create") return this.create(windowId, message2, send);
8548
+ const msg = message2;
8549
+ const entry = this.sessions.get(msg.sessionId);
8550
+ if (!entry || entry.windowId !== windowId) return;
8551
+ switch (message2.type) {
8552
+ case "media.session.destroy":
8553
+ return this.retire(entry.sessionId);
8554
+ case "media.session.update": {
8555
+ const update = message2;
8556
+ entry.metadata = { ...entry.metadata, ...update.metadata };
8557
+ if (this.active === entry.sessionId) this.activate(entry.sessionId);
8558
+ this.options.onSessionUpdate?.(windowId, entry.sessionId, update.metadata);
8559
+ this.changed();
8560
+ return;
8561
+ }
8562
+ case "media.command":
8563
+ if (entry.owner === "shell") this.command(entry.sessionId, message2);
8564
+ return;
8565
+ case "media.state": {
8566
+ const report = message2;
8567
+ if (entry.owner !== "napplet" || !["playing", "paused", "stopped", "buffering"].includes(report.status)) return;
8568
+ const state = { status: report.status };
8569
+ for (const key of ["position", "duration", "volume"]) {
8570
+ const value = report[key];
8571
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0 && (key !== "volume" || value <= 1)) state[key] = value;
8572
+ }
8573
+ if (typeof report.reason === "string") state.reason = report.reason;
8574
+ this.publishState(entry, state, entry.actions);
8575
+ return;
8576
+ }
8577
+ case "media.capabilities":
8578
+ if (entry.owner !== "napplet") return;
8579
+ entry.actions = normalizeActions(message2.actions);
8580
+ if (this.active === entry.sessionId) this.activate(entry.sessionId);
8581
+ this.options.onCapabilities?.(windowId, entry.sessionId, entry.actions);
8582
+ this.sendCapabilities(entry);
8583
+ this.changed();
8578
8584
  }
8579
8585
  }
8580
- }
8581
- function destroyWindowSessions(state, windowId) {
8582
- const sessions = state.windowSessions.get(windowId);
8583
- if (sessions) {
8584
- const ownedActive = state.activeSessionId !== null && sessions.has(state.activeSessionId);
8585
- for (const sessionId of sessions) {
8586
- state.sessionRegistry.delete(sessionId);
8587
- state.bridge.destroySession?.(sessionId);
8586
+ destroyWindow(windowId) {
8587
+ for (const [abort, pending] of this.pending) if (pending.windowId === windowId) {
8588
+ abort.abort();
8589
+ this.pending.delete(abort);
8588
8590
  }
8589
- state.windowSessions.delete(windowId);
8590
- if (ownedActive) promoteNextActiveOrClear(state);
8591
+ for (const entry of this.sessions.values()) if (entry.windowId === windowId) this.retire(entry.sessionId, "destroyed", false);
8591
8592
  }
8592
- state.sendHandles.delete(windowId);
8593
- }
8594
- function destroyMediaState(state, unsubscribeAction) {
8595
- unsubscribeAction();
8596
- for (const sessionId of state.sessionRegistry.keys()) state.bridge.destroySession?.(sessionId);
8597
- state.bridge.setActiveSession?.(null);
8598
- state.sessionRegistry.clear();
8599
- state.windowSessions.clear();
8600
- state.sendHandles.clear();
8601
- state.activeSessionId = null;
8602
- state.touchCounter = 0;
8603
- state.sessionCounter = 0;
8593
+ };
8594
+ function normalizeActions(value) {
8595
+ const all = ["play", "pause", "stop", "next", "prev", "seek", "volume"];
8596
+ return Array.isArray(value) ? [...new Set(value.filter((action) => all.includes(action)))] : [];
8604
8597
  }
8605
8598
  function createMediaService(options = {}) {
8606
- const descriptor = {
8607
- name: "media",
8608
- version: MEDIA_SERVICE_VERSION,
8609
- description: options.hostBridge ? "NIP-5D media NAP reference handler (host-bridge delegated)" : "NIP-5D media NAP reference handler (navigator.mediaSession mirror)"
8610
- };
8611
- const bridge = options.hostBridge ?? createBrowserMediaBridge({
8612
- mediaSessionTarget: options.mediaSessionTarget,
8613
- documentTarget: options.documentTarget
8614
- });
8615
- const state = createMediaServiceState(options, bridge);
8616
- const unsubscribeAction = bridge.onAction((sessionId, action, value) => {
8617
- sendMediaCommand(state, sessionId, action, value);
8618
- });
8619
- return {
8620
- descriptor,
8621
- handleMessage(windowId, message2, send) {
8622
- handleMediaMessage2(state, windowId, message2, send);
8623
- },
8624
- onWindowDestroyed(windowId) {
8625
- destroyWindowSessions(state, windowId);
8599
+ const bridge = options.hostBridge ?? createBrowserMediaBridge(options);
8600
+ const registry2 = new MediaRegistry(options, bridge);
8601
+ const off = bridge.onAction((sessionId, action, value) => registry2.command(sessionId, { action, value }));
8602
+ const service = {
8603
+ descriptor: { name: "media", version: MEDIA_SERVICE_VERSION, description: "NAP-MEDIA session registry and player" },
8604
+ handleMessage: (windowId, message2, send) => registry2.handle(windowId, message2, send),
8605
+ onWindowDestroyed: (windowId) => registry2.destroyWindow(windowId),
8606
+ onCapabilityRevoked(windowId, capability) {
8607
+ if (capability !== null && capability !== "media:control") return;
8608
+ for (const [abort, pending] of registry2.pending) {
8609
+ if (pending.windowId !== windowId) continue;
8610
+ abort.abort();
8611
+ registry2.pending.delete(abort);
8612
+ pending.fail("permission revoked");
8613
+ }
8614
+ for (const entry of registry2.sessions.values()) if (entry.windowId === windowId) registry2.retire(entry.sessionId, "policy");
8615
+ },
8616
+ getSessions: () => registry2.snapshots(),
8617
+ subscribe(listener) {
8618
+ registry2.listeners.add(listener);
8619
+ listener(registry2.snapshots());
8620
+ return () => {
8621
+ registry2.listeners.delete(listener);
8622
+ };
8626
8623
  },
8624
+ command: (sessionId, command) => registry2.command(sessionId, command),
8625
+ retire: (sessionId, reason) => registry2.retire(sessionId, reason),
8626
+ getElement: (sessionId) => registry2.sessions.get(sessionId)?.playback?.element,
8627
8627
  destroy() {
8628
- destroyMediaState(state, unsubscribeAction);
8628
+ if (registry2.destroyed) return;
8629
+ registry2.destroyed = true;
8630
+ off();
8631
+ for (const [abort, pending] of registry2.pending) {
8632
+ abort.abort();
8633
+ registry2.pending.delete(abort);
8634
+ pending.fail("media service unavailable");
8635
+ }
8636
+ for (const id of registry2.sessions.keys()) registry2.retire(id, "policy");
8637
+ registry2.used.clear();
8638
+ registry2.listeners.clear();
8639
+ bridge.setActiveSession?.(null);
8629
8640
  }
8630
8641
  };
8642
+ service.onUnregistered = service.destroy;
8643
+ return service;
8631
8644
  }
8632
8645
  var NOTIFY_SERVICE_VERSION = "1.0.0";
8633
8646
  function errorText(error) {
@@ -9500,26 +9513,10 @@ async function fetchResourceItem(options, windowId, info, request, signal) {
9500
9513
  const { url } = request;
9501
9514
  const parsedUrl = parseResourceUrl(url);
9502
9515
  if (!parsedUrl) return resourceInvalidRequest(url, `invalid URL: ${url}`);
9503
- if (parsedUrl.origin !== "null" && options.isOriginGranted && options.getConnectGrants) {
9504
- const identity = options.resolveIdentity?.(windowId) ?? null;
9505
- if (!identity) {
9506
- return {
9507
- ok: false,
9508
- url,
9509
- error: "blocked-by-policy",
9510
- message: "napplet identity not resolvable for runtime origin policy"
9511
- };
9512
- }
9513
- const origin = parsedUrl.origin;
9514
- const grants = options.getConnectGrants(identity.dTag, identity.aggregateHash);
9515
- if (!options.isOriginGranted(origin, grants)) {
9516
- return {
9517
- ok: false,
9518
- url,
9519
- error: "blocked-by-policy",
9520
- message: `origin ${origin} not granted by runtime policy`
9521
- };
9522
- }
9516
+ try {
9517
+ assertResourceOrigin(options, windowId, parsedUrl);
9518
+ } catch (error) {
9519
+ return { ok: false, url, error: "blocked-by-policy", message: error instanceof Error ? error.message : String(error) };
9523
9520
  }
9524
9521
  try {
9525
9522
  const response = await options.fetch(url, {
@@ -9549,6 +9546,19 @@ async function fetchResourceItem(options, windowId, info, request, signal) {
9549
9546
  };
9550
9547
  }
9551
9548
  }
9549
+ function assertResourceOrigin(options, windowId, parsedUrl) {
9550
+ if (parsedUrl.origin !== "null" && options.isOriginGranted && options.getConnectGrants) {
9551
+ const identity = options.resolveIdentity?.(windowId) ?? null;
9552
+ if (!identity) {
9553
+ throw new ResourceServiceError("blocked-by-policy", "napplet identity not resolvable for runtime origin policy");
9554
+ }
9555
+ const origin = parsedUrl.origin;
9556
+ const grants = options.getConnectGrants(identity.dTag, identity.aggregateHash);
9557
+ if (!options.isOriginGranted(origin, grants)) {
9558
+ throw new ResourceServiceError("blocked-by-policy", `origin ${origin} not granted by runtime policy`);
9559
+ }
9560
+ }
9561
+ }
9552
9562
  async function handleBytes(options, state, windowId, msg, send) {
9553
9563
  const { requestId, ...request } = msg;
9554
9564
  const controller = new AbortController();
@@ -9668,6 +9678,14 @@ function createResourceService(options) {
9668
9678
  };
9669
9679
  const handler = {
9670
9680
  descriptor,
9681
+ async openStream(windowId, url, signal) {
9682
+ if (signal.aborted) throw new DOMException("Playback cancelled", "AbortError");
9683
+ const parsed = parseResourceUrl(url);
9684
+ if (!parsed) throw new ResourceServiceError("invalid-request", "invalid media URL");
9685
+ assertResourceOrigin(options, windowId, parsed);
9686
+ if (!options.stream) throw new ResourceServiceError("unsupported-scheme", "live media unavailable");
9687
+ return options.stream(url, { method: "GET", signal, windowId });
9688
+ },
9671
9689
  handleMessage(windowId, message2, send) {
9672
9690
  switch (message2.type) {
9673
9691
  case "resource.bytes": {
@@ -12591,10 +12609,10 @@ function createGamepadService(options = {}) {
12591
12609
  if (recipients.size === 0) cancel();
12592
12610
  }
12593
12611
  function allowSubscribe(windowId) {
12594
- const time = now2();
12612
+ const time2 = now2();
12595
12613
  let bucket = changes.get(windowId);
12596
- if (!bucket || time < bucket.start || time - bucket.start >= SUBSCRIBE_WINDOW_MS) {
12597
- bucket = { start: time, count: 0 };
12614
+ if (!bucket || time2 < bucket.start || time2 - bucket.start >= SUBSCRIBE_WINDOW_MS) {
12615
+ bucket = { start: time2, count: 0 };
12598
12616
  changes.set(windowId, bucket);
12599
12617
  }
12600
12618
  bucket.count += 1;
@@ -12664,6 +12682,517 @@ function browserGamepadOptions(host, resolveWindow = () => void 0) {
12664
12682
  }
12665
12683
  };
12666
12684
  }
12685
+ function waitEvent(target, event, signal, operation) {
12686
+ return new Promise((resolve, reject2) => {
12687
+ const cleanup = () => {
12688
+ target.removeEventListener(event, done);
12689
+ target.removeEventListener("error", fail2);
12690
+ signal.removeEventListener("abort", fail2);
12691
+ };
12692
+ const done = () => {
12693
+ cleanup();
12694
+ resolve();
12695
+ };
12696
+ const fail2 = () => {
12697
+ cleanup();
12698
+ reject2(new Error("live audio failed or cancelled"));
12699
+ };
12700
+ target.addEventListener(event, done, { once: true });
12701
+ target.addEventListener("error", fail2, { once: true });
12702
+ signal.addEventListener("abort", fail2, { once: true });
12703
+ if (signal.aborted) return fail2();
12704
+ try {
12705
+ operation?.();
12706
+ } catch {
12707
+ fail2();
12708
+ }
12709
+ });
12710
+ }
12711
+ function delay(signal) {
12712
+ return new Promise((resolve) => {
12713
+ const done = () => {
12714
+ clearTimeout(timer);
12715
+ signal.removeEventListener("abort", done);
12716
+ resolve();
12717
+ };
12718
+ const timer = setTimeout(done, 250);
12719
+ signal.addEventListener("abort", done, { once: true });
12720
+ if (signal.aborted) done();
12721
+ });
12722
+ }
12723
+ async function pumpAudio(source, element2, reader, mime, signal) {
12724
+ await waitEvent(source, "sourceopen", signal);
12725
+ const buffer = source.addSourceBuffer(mime);
12726
+ while (!signal.aborted) {
12727
+ const item = await reader.read();
12728
+ if (item.done) {
12729
+ if (source.readyState === "open") source.endOfStream();
12730
+ return;
12731
+ }
12732
+ if (item.value.byteLength > 1024 * 1024) throw new Error("live audio chunk too large");
12733
+ for (let offset = 0; offset < item.value.byteLength; offset += 64 * 1024) {
12734
+ while (!signal.aborted && buffer.buffered.length && buffer.buffered.end(buffer.buffered.length - 1) - element2.currentTime > 30) {
12735
+ await delay(signal);
12736
+ }
12737
+ const cutoff = element2.currentTime - 15;
12738
+ if (buffer.buffered.length && cutoff > buffer.buffered.start(0) + 5) {
12739
+ await waitEvent(buffer, "updateend", signal, () => buffer.remove(0, cutoff));
12740
+ }
12741
+ const bytes = item.value.slice(offset, offset + 64 * 1024);
12742
+ await waitEvent(buffer, "updateend", signal, () => buffer.appendBuffer(bytes));
12743
+ }
12744
+ }
12745
+ }
12746
+ function createMediaStream(response, element2, controller, urls) {
12747
+ const mime = response.headers.get("content-type") ?? "";
12748
+ if (!response.body || typeof MediaSource === "undefined" || !MediaSource.isTypeSupported(mime)) {
12749
+ void response.body?.cancel().catch(() => {
12750
+ });
12751
+ throw new Error("unsupported live media type");
12752
+ }
12753
+ const source = new MediaSource();
12754
+ const reader = response.body.getReader();
12755
+ const url = urls.createObjectURL(source);
12756
+ let destroyed = false;
12757
+ const cancel = () => {
12758
+ void reader.cancel().catch(() => {
12759
+ });
12760
+ };
12761
+ controller.signal.addEventListener("abort", cancel, { once: true });
12762
+ void pumpAudio(source, element2, reader, mime, controller.signal).catch(() => {
12763
+ if (!controller.signal.aborted) {
12764
+ controller.abort();
12765
+ element2.pause();
12766
+ element2.dispatchEvent(new Event("error"));
12767
+ }
12768
+ }).finally(() => {
12769
+ controller.signal.removeEventListener("abort", cancel);
12770
+ reader.releaseLock();
12771
+ });
12772
+ return {
12773
+ url,
12774
+ destroy() {
12775
+ if (destroyed) return;
12776
+ destroyed = true;
12777
+ controller.abort();
12778
+ urls.revokeObjectURL(url);
12779
+ }
12780
+ };
12781
+ }
12782
+ function readSource(resource, windowId, url, signal) {
12783
+ return new Promise((resolve, reject2) => {
12784
+ const id = `media-resource-${crypto.randomUUID()}`;
12785
+ const cleanup = () => {
12786
+ clearTimeout(timer);
12787
+ signal.removeEventListener("abort", abort);
12788
+ };
12789
+ const abort = () => {
12790
+ cleanup();
12791
+ resource.handleMessage(windowId, { type: "resource.cancel", id }, () => {
12792
+ });
12793
+ reject2(new Error("media source cancelled"));
12794
+ };
12795
+ const timer = setTimeout(abort, 2e4);
12796
+ signal.addEventListener("abort", abort, { once: true });
12797
+ if (signal.aborted) return abort();
12798
+ try {
12799
+ resource.handleMessage(windowId, { type: "resource.bytes", id, url }, (message2) => {
12800
+ const result2 = message2;
12801
+ if (result2.id !== id || signal.aborted) return;
12802
+ cleanup();
12803
+ if (result2.type === "resource.bytes.result" && result2.blob instanceof Blob) resolve(result2.blob);
12804
+ else reject2(new Error("media source blocked or unavailable"));
12805
+ });
12806
+ } catch (error) {
12807
+ cleanup();
12808
+ reject2(error);
12809
+ }
12810
+ });
12811
+ }
12812
+ function sourceUrl(options) {
12813
+ const source = options.source;
12814
+ if (typeof source?.url === "string" && source.url) return source.url;
12815
+ if (typeof source?.blossomHash === "string" && /^[a-f0-9]{64}$/i.test(source.blossomHash)) return `blossom:${source.blossomHash}`;
12816
+ throw new Error("unsupported source");
12817
+ }
12818
+ function loadMedia(element2, url, signal) {
12819
+ return new Promise((resolve, reject2) => {
12820
+ const cleanup = () => {
12821
+ clearTimeout(timer);
12822
+ element2.removeEventListener("loadedmetadata", loaded);
12823
+ element2.removeEventListener("error", failed2);
12824
+ signal.removeEventListener("abort", failed2);
12825
+ };
12826
+ const loaded = () => {
12827
+ cleanup();
12828
+ resolve();
12829
+ };
12830
+ const failed2 = () => {
12831
+ cleanup();
12832
+ reject2(new Error("media decoding failed or cancelled"));
12833
+ };
12834
+ const timer = setTimeout(failed2, 5e3);
12835
+ element2.addEventListener("loadedmetadata", loaded, { once: true });
12836
+ element2.addEventListener("error", failed2, { once: true });
12837
+ signal.addEventListener("abort", failed2, { once: true });
12838
+ if (signal.aborted) return failed2();
12839
+ try {
12840
+ element2.src = url;
12841
+ element2.load();
12842
+ } catch {
12843
+ failed2();
12844
+ }
12845
+ });
12846
+ }
12847
+ function attachPlayback(element2, live, release, changed) {
12848
+ let retired = false;
12849
+ let generation = 0;
12850
+ let state = { status: "paused", position: 0, volume: element2.volume };
12851
+ const actions = () => [
12852
+ "play",
12853
+ "pause",
12854
+ "stop",
12855
+ "volume",
12856
+ ...!live && Number.isFinite(element2.duration) && element2.duration > 0 ? ["seek"] : []
12857
+ ];
12858
+ const publish = (status = state.status, reason) => {
12859
+ if (retired) return;
12860
+ state = {
12861
+ status,
12862
+ position: element2.currentTime,
12863
+ volume: element2.volume,
12864
+ ...Number.isFinite(element2.duration) ? { duration: element2.duration } : {},
12865
+ ...reason ? { reason } : {}
12866
+ };
12867
+ changed({ ...state }, actions());
12868
+ };
12869
+ const handlers = {
12870
+ playing: () => publish("playing"),
12871
+ pause: () => {
12872
+ if (state.status !== "stopped") publish("paused");
12873
+ },
12874
+ waiting: () => publish("buffering"),
12875
+ ended: () => {
12876
+ generation++;
12877
+ publish("stopped", "ended");
12878
+ },
12879
+ error: () => {
12880
+ generation++;
12881
+ publish("stopped", "error");
12882
+ },
12883
+ timeupdate: () => publish(),
12884
+ durationchange: () => publish(),
12885
+ loadedmetadata: () => publish(),
12886
+ volumechange: () => publish(),
12887
+ seeked: () => publish()
12888
+ };
12889
+ for (const [event, handler] of Object.entries(handlers)) element2.addEventListener(event, handler);
12890
+ return {
12891
+ element: element2,
12892
+ get state() {
12893
+ return { ...state };
12894
+ },
12895
+ get actions() {
12896
+ return actions();
12897
+ },
12898
+ command(command) {
12899
+ if (retired || !validMediaCommand(command, actions())) return;
12900
+ const token = ++generation;
12901
+ switch (command.action) {
12902
+ case "play":
12903
+ if (live && element2.buffered.length && (element2.ended || element2.currentTime < element2.buffered.start(0))) element2.currentTime = element2.buffered.start(0);
12904
+ void element2.play().then(() => {
12905
+ if (!retired && token === generation) publish("playing", command.reason);
12906
+ }).catch(() => {
12907
+ if (!retired && token === generation) publish("paused", "error");
12908
+ });
12909
+ break;
12910
+ case "pause":
12911
+ element2.pause();
12912
+ publish("paused", command.reason);
12913
+ break;
12914
+ case "stop":
12915
+ element2.pause();
12916
+ if (!live) element2.currentTime = 0;
12917
+ publish("stopped", command.reason);
12918
+ break;
12919
+ case "seek":
12920
+ element2.currentTime = Math.min(command.value, element2.duration);
12921
+ publish();
12922
+ break;
12923
+ case "volume":
12924
+ element2.volume = command.value;
12925
+ publish();
12926
+ break;
12927
+ }
12928
+ },
12929
+ destroy() {
12930
+ if (retired) return;
12931
+ retired = true;
12932
+ generation++;
12933
+ for (const [event, handler] of Object.entries(handlers)) element2.removeEventListener(event, handler);
12934
+ element2.pause();
12935
+ element2.removeAttribute("src");
12936
+ element2.load();
12937
+ element2.remove();
12938
+ release();
12939
+ }
12940
+ };
12941
+ }
12942
+ function createBrowserMediaPlayback(options) {
12943
+ const doc = options.document ?? document;
12944
+ const urls = options.urls ?? URL;
12945
+ return {
12946
+ async open(windowId, request, signal, changed) {
12947
+ if (request.live && options.stream) return openLive(windowId, request, signal, changed, options, doc, urls);
12948
+ const blob = await readSource(options.resource, windowId, sourceUrl(request), signal);
12949
+ if (signal.aborted) throw new Error("media source cancelled");
12950
+ if (!/^(audio|video)\//.test(blob.type)) throw new Error("unsupported media type");
12951
+ const element2 = doc.createElement(blob.type.startsWith("video/") ? "video" : "audio");
12952
+ if (!element2.canPlayType(blob.type)) throw new Error("unsupported media type");
12953
+ element2.preload = "metadata";
12954
+ if (element2.tagName === "VIDEO") element2.playsInline = true;
12955
+ const url = urls.createObjectURL(blob);
12956
+ const playback = attachPlayback(element2, request.live === true, () => urls.revokeObjectURL(url), changed);
12957
+ const abort = () => playback.destroy();
12958
+ signal.addEventListener("abort", abort, { once: true });
12959
+ try {
12960
+ await loadMedia(element2, url, signal);
12961
+ if (request.autoplay) await element2.play();
12962
+ if (signal.aborted) throw new Error("media source cancelled");
12963
+ return playback;
12964
+ } catch (error) {
12965
+ playback.destroy();
12966
+ throw error;
12967
+ } finally {
12968
+ signal.removeEventListener("abort", abort);
12969
+ }
12970
+ }
12971
+ };
12972
+ }
12973
+ async function openLive(windowId, request, signal, changed, options, doc, urls) {
12974
+ const controller = new AbortController();
12975
+ const abort = () => controller.abort();
12976
+ signal.addEventListener("abort", abort, { once: true });
12977
+ const timer = setTimeout(abort, 2e4);
12978
+ let playback;
12979
+ try {
12980
+ if (signal.aborted) controller.abort();
12981
+ const response = await options.stream(windowId, sourceUrl(request), controller.signal);
12982
+ if (controller.signal.aborted) {
12983
+ await response.body?.cancel();
12984
+ throw new Error("media source cancelled");
12985
+ }
12986
+ const element2 = doc.createElement("audio");
12987
+ element2.preload = "auto";
12988
+ const stream = createMediaStream(response, element2, controller, urls);
12989
+ playback = attachPlayback(element2, true, stream.destroy, changed);
12990
+ await loadMedia(element2, stream.url, controller.signal);
12991
+ if (request.autoplay) await element2.play();
12992
+ if (controller.signal.aborted) throw new Error("media source cancelled");
12993
+ return playback;
12994
+ } catch (error) {
12995
+ playback?.destroy();
12996
+ controller.abort();
12997
+ throw error;
12998
+ } finally {
12999
+ clearTimeout(timer);
13000
+ signal.removeEventListener("abort", abort);
13001
+ }
13002
+ }
13003
+ function publicStreamUrl(value) {
13004
+ const url = new URL(value);
13005
+ const host = url.hostname.toLowerCase();
13006
+ const local = host === "localhost" || /\.(localhost|local|internal)$/.test(host) || !host.includes(".") || host.includes(":");
13007
+ const ip = /^\d+\.\d+\.\d+\.\d+$/.test(host) ? host.split(".").map(Number) : null;
13008
+ if (url.protocol !== "https:" || url.username || url.password || local || ip && (ip[0] === 0 || ip[0] === 10 || ip[0] === 127 || ip[0] >= 224 || ip[0] === 100 && ip[1] >= 64 && ip[1] <= 127 || ip[0] === 169 && ip[1] === 254 || ip[0] === 172 && ip[1] >= 16 && ip[1] <= 31 || ip[0] === 192 && ip[1] === 168 || ip[0] === 198 && (ip[1] === 18 || ip[1] === 19))) throw new ResourceServiceError("blocked-by-policy", "live media requires a public HTTPS URL without credentials");
13009
+ return url;
13010
+ }
13011
+ function audioMime(bytes) {
13012
+ if (bytes[0] === 73 && bytes[1] === 68 && bytes[2] === 51) return "audio/mpeg";
13013
+ if (bytes[0] === 255 && (bytes[1] & 224) === 224 && (bytes[1] & 24) !== 8) {
13014
+ if ((bytes[1] & 6) !== 0 && (bytes[2] & 240) !== 240 && (bytes[2] & 12) !== 12) return "audio/mpeg";
13015
+ if ((bytes[1] & 246) === 240) return "audio/aac";
13016
+ }
13017
+ throw new ResourceServiceError("decode-failed", "unsupported live audio bytes");
13018
+ }
13019
+ function createBrowserMediaStreamFetch(fetcher = globalThis.fetch) {
13020
+ return async (value, init) => {
13021
+ const url = publicStreamUrl(value);
13022
+ const response = await fetcher(url.href, {
13023
+ method: "GET",
13024
+ signal: init.signal,
13025
+ redirect: "error",
13026
+ credentials: "omit",
13027
+ referrerPolicy: "no-referrer"
13028
+ });
13029
+ if (!response.ok || !response.body) {
13030
+ await response.body?.cancel();
13031
+ throw new ResourceServiceError("network-error", "live audio unavailable");
13032
+ }
13033
+ const reader = response.body.getReader();
13034
+ try {
13035
+ const prefix = new Uint8Array(4);
13036
+ const chunks = [];
13037
+ let length = 0;
13038
+ while (length < prefix.length) {
13039
+ const { value: chunk, done } = await reader.read();
13040
+ if (done) throw new ResourceServiceError("decode-failed", "empty live audio");
13041
+ if (!chunk.byteLength) continue;
13042
+ if (chunk.byteLength > 1024 * 1024) throw new ResourceServiceError("too-large", "live audio chunk too large");
13043
+ prefix.set(chunk.subarray(0, prefix.length - length), length);
13044
+ length += Math.min(chunk.byteLength, prefix.length - length);
13045
+ chunks.push(chunk);
13046
+ }
13047
+ const mime = audioMime(prefix);
13048
+ return new Response(new ReadableStream({
13049
+ start(controller) {
13050
+ for (const chunk of chunks) controller.enqueue(chunk);
13051
+ },
13052
+ async pull(controller) {
13053
+ try {
13054
+ const item = await reader.read();
13055
+ if (item.done) {
13056
+ reader.releaseLock();
13057
+ controller.close();
13058
+ } else controller.enqueue(item.value);
13059
+ } catch (error) {
13060
+ controller.error(error);
13061
+ }
13062
+ },
13063
+ async cancel() {
13064
+ await reader.cancel();
13065
+ reader.releaseLock();
13066
+ }
13067
+ }), { headers: { "content-type": mime } });
13068
+ } catch (error) {
13069
+ await reader.cancel().catch(() => {
13070
+ });
13071
+ reader.releaseLock();
13072
+ throw error;
13073
+ }
13074
+ };
13075
+ }
13076
+ var PLAYER_STYLE = `
13077
+ :host { position:fixed; right:16px; bottom:48px; z-index:10000; width:min(360px,calc(100vw - 32px)); color-scheme:dark; font:14px/1.4 system-ui,sans-serif; color:#f4f0df; }
13078
+ :host([hidden]) { display:none; }
13079
+ details { background:#171b1b; border:1px solid #68716c; border-radius:12px; box-shadow:0 6px 24px #0006; }
13080
+ summary { padding:12px 16px; cursor:pointer; font-weight:600; }
13081
+ .sessions { max-height:60vh; overflow:auto; padding:0 12px 12px; }
13082
+ article { border-top:1px solid #49514d; padding-top:12px; margin-top:4px; }
13083
+ h3,p { margin:0 0 6px; overflow-wrap:anywhere; }
13084
+ p { color:#c7cdc9; font-size:12px; }
13085
+ .buttons { display:flex; gap:6px; flex-wrap:wrap; margin:8px 0; }
13086
+ button { padding:8px 10px; border:1px solid #68716c; border-radius:6px; color:inherit; background:#29312c; cursor:pointer; min-height:40px; }
13087
+ button:disabled { opacity:.5; cursor:default; }
13088
+ button:focus-visible, input:focus-visible, summary:focus-visible { outline:2px solid #e9d584; outline-offset:3px; }
13089
+ label { display:flex; align-items:center; gap:8px; margin:8px 0; }
13090
+ input { flex:1; min-width:0; accent-color:#e9d584; }
13091
+ video { display:block; width:100%; max-height:240px; background:#000; border-radius:6px; }
13092
+ audio { display:none; }
13093
+ `;
13094
+ function time(value = 0) {
13095
+ const seconds = Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
13096
+ return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
13097
+ }
13098
+ function makeRow(doc, service, sessionId) {
13099
+ const root = doc.createElement("article");
13100
+ root.dataset.sessionId = sessionId;
13101
+ const title = doc.createElement("h3");
13102
+ const detail = doc.createElement("p");
13103
+ const status = doc.createElement("p");
13104
+ const media = doc.createElement("div");
13105
+ const controls = doc.createElement("div");
13106
+ controls.className = "buttons";
13107
+ const buttons = /* @__PURE__ */ new Map();
13108
+ for (const [action, text] of [["prev", "Previous"], ["play", "Play"], ["pause", "Pause"], ["stop", "Stop"], ["next", "Next"]]) {
13109
+ const button2 = doc.createElement("button");
13110
+ button2.type = "button";
13111
+ button2.textContent = text;
13112
+ button2.onclick = () => service.command(sessionId, { action, reason: "user" });
13113
+ controls.append(button2);
13114
+ buttons.set(action, button2);
13115
+ }
13116
+ const close = doc.createElement("button");
13117
+ close.type = "button";
13118
+ close.textContent = "Close session";
13119
+ close.onclick = () => service.retire(sessionId, "user");
13120
+ controls.append(close);
13121
+ const range = (name, action, max, step) => {
13122
+ const label = doc.createElement("label");
13123
+ label.append(name);
13124
+ const input = doc.createElement("input");
13125
+ input.type = "range";
13126
+ input.min = "0";
13127
+ input.max = max;
13128
+ input.step = step;
13129
+ input.setAttribute("aria-label", name);
13130
+ input.onchange = () => service.command(sessionId, { action, value: Number(input.value), reason: "user" });
13131
+ label.append(input);
13132
+ return { label, input };
13133
+ };
13134
+ const seek = range("Position", "seek", "0", "0.1");
13135
+ const volume = range("Volume", "volume", "1", "0.01");
13136
+ root.append(title, detail, media, status, controls, seek.label, volume.label);
13137
+ return { root, title, detail, status, buttons, seek: seek.input, volume: volume.input, media };
13138
+ }
13139
+ function updateRow(row, session, service) {
13140
+ row.title.textContent = session.metadata?.title || "Untitled media";
13141
+ row.detail.textContent = [session.metadata?.artist, session.metadata?.album, session.context?.label, session.context?.detail].filter(Boolean).join(" \xB7 ");
13142
+ const state = session.state;
13143
+ row.status.textContent = `${state?.status ?? "Ready"} \xB7 ${time(state?.position)} / ${time(state?.duration ?? session.metadata?.duration)}${state?.reason === "error" ? " \xB7 Playback failed. Try Play again." : ""}`;
13144
+ for (const [action, button2] of row.buttons) {
13145
+ button2.hidden = !session.actions.includes(action) || action === "play" && state?.status === "playing" || action === "pause" && state?.status !== "playing" && state?.status !== "buffering";
13146
+ }
13147
+ row.seek.disabled = !session.actions.includes("seek");
13148
+ row.seek.max = String(state?.duration ?? session.metadata?.duration ?? 0);
13149
+ row.volume.disabled = !session.actions.includes("volume");
13150
+ if (row.seek.getRootNode() instanceof ShadowRoot && row.seek.getRootNode().activeElement !== row.seek) row.seek.value = String(state?.position ?? 0);
13151
+ if (row.volume.getRootNode() instanceof ShadowRoot && row.volume.getRootNode().activeElement !== row.volume) row.volume.value = String(state?.volume ?? 1);
13152
+ const element2 = service.getElement(session.sessionId);
13153
+ if (element2 && element2.parentElement !== row.media) row.media.append(element2);
13154
+ }
13155
+ function mountMediaPlayer(service, container = document.body) {
13156
+ const doc = container.ownerDocument;
13157
+ const host = doc.createElement("section");
13158
+ host.dataset.kehtoMediaPlayer = "";
13159
+ host.setAttribute("aria-label", "Media player");
13160
+ const shadow = host.attachShadow({ mode: "open" });
13161
+ const style = doc.createElement("style");
13162
+ style.textContent = PLAYER_STYLE;
13163
+ const details = doc.createElement("details");
13164
+ details.open = true;
13165
+ const summary = doc.createElement("summary");
13166
+ summary.textContent = "Media player";
13167
+ const sessions = doc.createElement("div");
13168
+ sessions.className = "sessions";
13169
+ details.append(summary, sessions);
13170
+ shadow.append(style, details);
13171
+ container.append(host);
13172
+ const rows = /* @__PURE__ */ new Map();
13173
+ const off = service.subscribe((snapshots) => {
13174
+ host.hidden = snapshots.length === 0;
13175
+ summary.textContent = `Media player (${snapshots.length})`;
13176
+ const live = new Set(snapshots.map((session) => session.sessionId));
13177
+ for (const [id, row] of rows) if (!live.has(id)) {
13178
+ row.root.remove();
13179
+ rows.delete(id);
13180
+ }
13181
+ for (const session of snapshots) {
13182
+ let row = rows.get(session.sessionId);
13183
+ if (!row) {
13184
+ row = makeRow(doc, service, session.sessionId);
13185
+ rows.set(session.sessionId, row);
13186
+ sessions.append(row.root);
13187
+ }
13188
+ updateRow(row, session, service);
13189
+ }
13190
+ });
13191
+ return () => {
13192
+ off();
13193
+ host.remove();
13194
+ };
13195
+ }
12667
13196
 
12668
13197
  // src/simulation.ts
12669
13198
  var PajaSimulationError = class extends Error {
@@ -13241,6 +13770,18 @@ function installPajaResourceSettings() {
13241
13770
  }
13242
13771
 
13243
13772
  // ../shell/dist/index.js
13773
+ function randomUUID() {
13774
+ const provider = globalThis.crypto;
13775
+ if (typeof provider?.randomUUID === "function") return provider.randomUUID();
13776
+ if (typeof provider?.getRandomValues !== "function") {
13777
+ throw new Error("@kehto/shell requires crypto.randomUUID or crypto.getRandomValues for UUID generation");
13778
+ }
13779
+ const bytes = provider.getRandomValues(new Uint8Array(16));
13780
+ bytes[6] = bytes[6] & 15 | 64;
13781
+ bytes[8] = bytes[8] & 63 | 128;
13782
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
13783
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
13784
+ }
13244
13785
  function bytesToHex3(bytes) {
13245
13786
  return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
13246
13787
  }
@@ -13305,7 +13846,7 @@ function createCacheAdapter(shellHooks) {
13305
13846
  async query(filters) {
13306
13847
  const workerRelay = shellHooks.workerRelay.getWorkerRelay();
13307
13848
  if (!workerRelay) return [];
13308
- const subId = crypto.randomUUID();
13849
+ const subId = randomUUID();
13309
13850
  return workerRelay.query(["REQ", subId, ...filters]);
13310
13851
  },
13311
13852
  store(event) {
@@ -13352,7 +13893,7 @@ function createCryptoAdapter(shellHooks) {
13352
13893
  return shellHooks.crypto.verifyEvent(event);
13353
13894
  },
13354
13895
  randomUUID() {
13355
- return crypto.randomUUID();
13896
+ return randomUUID();
13356
13897
  },
13357
13898
  randomBytes(length) {
13358
13899
  const bytes = new Uint8Array(length);
@@ -14363,7 +14904,7 @@ function registerNip5dSessionIfNeeded({
14363
14904
  dTag: identity.dTag,
14364
14905
  aggregateHash: identity.aggregateHash,
14365
14906
  registeredAt: Date.now(),
14366
- instanceId: crypto.randomUUID(),
14907
+ instanceId: randomUUID(),
14367
14908
  provenance: "nip-5d"
14368
14909
  };
14369
14910
  runtime.sessionRegistry.register(windowId, entry);
@@ -15411,36 +15952,90 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
15411
15952
  };
15412
15953
  }
15413
15954
  function makeMedia() {
15955
+ const sessions = /* @__PURE__ */ new Set();
15956
+ const ended = /* @__PURE__ */ new Map();
15957
+ const retained = /* @__PURE__ */ new Map();
15958
+ const callbacks = /* @__PURE__ */ new Map();
15959
+ const warnings = /* @__PURE__ */ new Set();
15960
+ const warn = (name, replacement) => {
15961
+ if (warnings.has(name)) return;
15962
+ warnings.add(name);
15963
+ console.warn(`[KEHTO-MEDIA-${name}] Deprecated media API; use ${replacement}. Warned once per endpoint.`);
15964
+ };
15965
+ listen((event) => {
15966
+ if (!isParentMessage(event)) return;
15967
+ const msg = event.data;
15968
+ if (!msg || typeof msg !== "object" || typeof msg.sessionId !== "string") return;
15969
+ const sessionId = msg.sessionId;
15970
+ if (msg.type === "media.session.create.result" && !msg.error) {
15971
+ if (!ended.has(sessionId)) sessions.add(sessionId);
15972
+ return;
15973
+ }
15974
+ if (!sessions.has(sessionId) || ended.has(sessionId)) return;
15975
+ if (msg.type === "media.session.ended") {
15976
+ ended.set(sessionId, msg);
15977
+ retained.delete(sessionId);
15978
+ sessions.delete(sessionId);
15979
+ } else if (["media.state", "media.capabilities", "media.controls"].includes(msg.type)) {
15980
+ const cache2 = retained.get(sessionId) ?? /* @__PURE__ */ new Map();
15981
+ cache2.set(msg.type, msg);
15982
+ retained.set(sessionId, cache2);
15983
+ } else if (msg.type !== "media.command") return;
15984
+ const delivery = Array.from(callbacks.get(sessionId)?.get(msg.type) ?? []);
15985
+ for (const callback of delivery) callback(msg);
15986
+ if (ended.has(sessionId)) callbacks.delete(sessionId);
15987
+ });
15414
15988
  const on = (type, sessionId, callback) => {
15415
- const off = listen((event) => {
15416
- if (!isParentMessage(event)) return;
15417
- const msg = event.data;
15418
- if (typeof msg === "object" && msg !== null && msg.type === type && msg.sessionId === sessionId) callback(msg);
15989
+ const terminal = ended.get(sessionId);
15990
+ if (terminal) {
15991
+ if (type === "media.session.ended") callback(terminal);
15992
+ return subscriptionHandle(() => {
15993
+ });
15994
+ }
15995
+ const byType = callbacks.get(sessionId) ?? /* @__PURE__ */ new Map();
15996
+ const handlers = byType.get(type) ?? /* @__PURE__ */ new Set();
15997
+ handlers.add(callback);
15998
+ byType.set(type, handlers);
15999
+ callbacks.set(sessionId, byType);
16000
+ const cached = retained.get(sessionId)?.get(type);
16001
+ if (cached) callback(cached);
16002
+ return subscriptionHandle(() => {
16003
+ handlers.delete(callback);
15419
16004
  });
15420
- return subscriptionHandle(off);
15421
16005
  };
15422
- return {
16006
+ const command = (sessionId, value) => {
16007
+ if (ended.has(sessionId)) return;
16008
+ fire({ ...value && typeof value === "object" ? value : {}, type: "media.command", sessionId });
16009
+ };
16010
+ return Object.freeze({
15423
16011
  createSession: (options) => request(
15424
- { type: "media.session.create", ...options && typeof options === "object" ? options : {} },
16012
+ { ...options && typeof options === "object" ? options : {}, type: "media.session.create" },
15425
16013
  "media.session.create.result",
15426
16014
  withoutEnvelope,
15427
16015
  { rejectOnError: false }
15428
16016
  ),
15429
16017
  updateSession: (sessionId, metadata) => fire({ type: "media.session.update", sessionId, metadata }),
15430
16018
  destroySession: (sessionId) => fire({ type: "media.session.destroy", sessionId }),
15431
- reportState: (sessionId, state) => fire({ type: "media.state", sessionId, ...state && typeof state === "object" ? state : {} }),
16019
+ reportState: (sessionId, state) => fire({ ...state && typeof state === "object" ? state : {}, type: "media.state", sessionId }),
15432
16020
  reportCapabilities: (sessionId, actions) => fire({ type: "media.capabilities", sessionId, actions }),
15433
- sendCommand: (sessionId, action, value) => fire({ type: "media.command", sessionId, action, ...value === void 0 ? {} : { value } }),
15434
- onCommand: (sessionId, callback) => on("media.command", sessionId, (msg) => callback(msg.action, msg.value)),
15435
- onState: (sessionId, callback) => on("media.state", sessionId, (msg) => callback({
15436
- status: msg.status,
15437
- position: msg.position,
15438
- duration: msg.duration,
15439
- volume: msg.volume
15440
- })),
16021
+ command,
16022
+ sendCommand: (sessionId, action, value) => {
16023
+ warn("SEND-COMMAND", "media.command(sessionId, { action, value })");
16024
+ command(sessionId, { action, ...value === void 0 ? {} : { value } });
16025
+ },
16026
+ onCommand: (sessionId, callback) => {
16027
+ const legacy = callback.length >= 2;
16028
+ if (legacy) warn("COMMAND-CALLBACK", "media.onCommand(sessionId, command => ...)");
16029
+ return on("media.command", sessionId, (msg) => legacy ? callback(msg.action, msg.value) : callback({ action: msg.action, ...msg.value === void 0 ? {} : { value: msg.value }, ...msg.reason === void 0 ? {} : { reason: msg.reason } }));
16030
+ },
16031
+ onState: (sessionId, callback) => on("media.state", sessionId, (msg) => {
16032
+ const { type: _type, sessionId: _sessionId, ...state } = msg;
16033
+ callback(state);
16034
+ }),
15441
16035
  onCapabilities: (sessionId, callback) => on("media.capabilities", sessionId, (msg) => callback(msg.actions)),
15442
- onControls: (sessionId, callback) => on("media.controls", sessionId, (msg) => callback(msg.controls))
15443
- };
16036
+ onControls: (sessionId, callback) => on("media.controls", sessionId, (msg) => callback(msg.controls)),
16037
+ onEnded: (sessionId, callback) => on("media.session.ended", sessionId, (msg) => callback({ sessionId: msg.sessionId, reason: msg.reason }))
16038
+ });
15444
16039
  }
15445
16040
  function makeNotify() {
15446
16041
  const on = (type, callback) => {
@@ -16078,10 +16673,12 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
16078
16673
  intent ??= Object.freeze(makeIntent());
16079
16674
  return intent;
16080
16675
  }
16676
+ let media;
16081
16677
  function isProtectedDomain(domain) {
16082
- return domain === "gamepad" || domain === "shell" || domain === "inc" || domain === "identity" || domain === "theme" || domain === "intent";
16678
+ return domain === "media" || domain === "gamepad" || domain === "shell" || domain === "inc" || domain === "identity" || domain === "theme" || domain === "intent";
16083
16679
  }
16084
16680
  function makeDomain(domain, existing) {
16681
+ if (domain === "media") return media ??= makeMedia();
16085
16682
  if (domain === "gamepad") return gamepad ??= makeGamepad();
16086
16683
  if (domain === "shell") return shell;
16087
16684
  if (domain === "inc") return makeProtectedInc(existing);
@@ -16096,8 +16693,6 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
16096
16693
  return makeStorage();
16097
16694
  case "keys":
16098
16695
  return makeKeys();
16099
- case "media":
16100
- return makeMedia();
16101
16696
  case "notify":
16102
16697
  return makeNotify();
16103
16698
  case "config":
@@ -19298,13 +19893,13 @@ function createPajaRelayBackend(getSimulation, confirmRequest, livePool = new Si
19298
19893
  if (matchesAnyFilter2(event, subscriber.filters)) subscriber.next(event);
19299
19894
  }
19300
19895
  }
19301
- async function attemptPublish(relayUrls2, event) {
19896
+ async function attemptPublish(relayUrls2, event, signerContext) {
19302
19897
  const simulation = getSimulation();
19303
19898
  const rejected2 = Object.fromEntries(relayUrls2.map((url) => [url, false]));
19304
19899
  if (simulation.relay.mode === "disabled") {
19305
19900
  return { outcomes: rejected2, error: "relay unavailable" };
19306
19901
  }
19307
- if (!await confirmRequest({ action: "publish", event })) {
19902
+ if (signerContext?.isCurrent && !signerContext.isCurrent() || !await confirmRequest({ action: "publish", event, ...signerContext ? { signerContext } : {} }) || signerContext?.isCurrent && !signerContext.isCurrent()) {
19308
19903
  return { outcomes: rejected2, error: "publish denied" };
19309
19904
  }
19310
19905
  const outcomes = simulation.relay.mode === "live" ? await publishLive(livePool, relayUrls2, event) : Object.fromEntries(relayUrls2.map((url) => [url, true]));
@@ -19346,8 +19941,8 @@ function createPajaRelayBackend(getSimulation, confirmRequest, livePool = new Si
19346
19941
  }
19347
19942
  };
19348
19943
  },
19349
- async publish(relayUrls2, event) {
19350
- const attempt = await attemptPublish(relayUrls2, event);
19944
+ async publish(relayUrls2, event, signerContext) {
19945
+ const attempt = await attemptPublish(relayUrls2, event, signerContext);
19351
19946
  if (attempt.error) throw new Error(attempt.error);
19352
19947
  },
19353
19948
  request(relayUrls2, filtersInput, context = { reason: "host" }) {
@@ -19387,8 +19982,8 @@ function createPajaRelayBackend(getSimulation, confirmRequest, livePool = new Si
19387
19982
  relayRequestObserver = observer;
19388
19983
  },
19389
19984
  query,
19390
- async publishToRelays(relayUrls2, event) {
19391
- return (await attemptPublish(relayUrls2, event)).outcomes;
19985
+ async publishToRelays(relayUrls2, event, signerContext) {
19986
+ return (await attemptPublish(relayUrls2, event, signerContext)).outcomes;
19392
19987
  },
19393
19988
  async publishWebrtcSignal(relayUrls2, event) {
19394
19989
  if (getSimulation().relay.mode !== "live" || relayUrls2.length === 0 || event.kind !== PAJA_WEBRTC_SIGNAL_KIND || !verifyEvent(event)) {
@@ -19820,7 +20415,7 @@ function createPajaRelayConfig(getSimulation) {
19820
20415
  refresh();
19821
20416
  return runtime;
19822
20417
  }
19823
- function createPajaRelayHooks(pool, getSimulation, relayConfig) {
20418
+ function createPajaRelayHooks(pool, getSimulation, relayConfig, getPublishPool = () => pool) {
19824
20419
  const cleanups = /* @__PURE__ */ new Map();
19825
20420
  const scoped = /* @__PURE__ */ new Map();
19826
20421
  function closeScopedRelay(windowId) {
@@ -19867,7 +20462,7 @@ function createPajaRelayHooks(pool, getSimulation, relayConfig) {
19867
20462
  const active = scoped.get(windowId);
19868
20463
  if (getSimulation().relay.mode !== "live" || !active || !verifyEvent(event)) return false;
19869
20464
  try {
19870
- await pool.publish([active.relayUrl], event);
20465
+ await getPublishPool(windowId).publish([active.relayUrl], event);
19871
20466
  return true;
19872
20467
  } catch {
19873
20468
  return false;
@@ -20455,7 +21050,7 @@ var BrowserWebrtcController = class {
20455
21050
  if (this.windowSessionCount(context.windowId) >= PAJA_WEBRTC_MAX_SESSIONS_PER_WINDOW) {
20456
21051
  throw new Error("session limit reached");
20457
21052
  }
20458
- const signer = this.requireSigner();
21053
+ const signer = this.requireSigner(context.windowId);
20459
21054
  const localPubkey = normalizePubkey3(await signer.getPublicKey());
20460
21055
  if (!localPubkey || localPubkey !== normalizePubkey3(this.options.getPubkey())) throw new Error("signaling unavailable");
20461
21056
  const identity = this.options.getIdentity(context.windowId);
@@ -20697,13 +21292,13 @@ var BrowserWebrtcController = class {
20697
21292
  if (!session || session.windowId !== windowId) throw new Error("session not found");
20698
21293
  return session;
20699
21294
  }
20700
- requireSigner() {
20701
- const signer = this.options.getSigner();
21295
+ requireSigner(windowId) {
21296
+ const signer = this.options.getSigner(windowId);
20702
21297
  if (!isSignalingSigner(signer)) throw new Error("signaling unavailable");
20703
21298
  return signer;
20704
21299
  }
20705
21300
  requireSessionSigner(session) {
20706
- const signer = this.requireSigner();
21301
+ const signer = this.requireSigner(session.windowId);
20707
21302
  if (normalizePubkey3(this.options.getPubkey()) !== session.localPubkey) throw new Error("signaling unavailable");
20708
21303
  return signer;
20709
21304
  }
@@ -21456,6 +22051,7 @@ function createPajaDevSigner(getSimulation, confirm, source) {
21456
22051
  getPublicKey: () => PAJA_DEV_SIGNER_PUBKEY,
21457
22052
  getRelays: () => Object.fromEntries(getPajaRelayUrls(getSimulation()).map((relay) => [relay, { read: true, write: true }])),
21458
22053
  async signEvent(event) {
22054
+ if (source?.isCurrent && !source.isCurrent()) throw new Error("Paja signing source changed");
21459
22055
  const signerContext = source ? { ...source, signerPubkey: PAJA_DEV_SIGNER_PUBKEY } : void 0;
21460
22056
  if (!await confirm({
21461
22057
  action: "sign",
@@ -21464,6 +22060,7 @@ function createPajaDevSigner(getSimulation, confirm, source) {
21464
22060
  })) {
21465
22061
  throw new Error("Paja signing request denied");
21466
22062
  }
22063
+ if (source?.isCurrent && !source.isCurrent()) throw new Error("Paja signing source changed");
21467
22064
  const template = { ...event };
21468
22065
  template.created_at ??= Math.floor(Date.now() / 1e3);
21469
22066
  template.tags ??= [];
@@ -21526,7 +22123,115 @@ function createPajaWorkerRelay(events) {
21526
22123
  };
21527
22124
  }
21528
22125
 
21529
- // src/browser-adapter.ts
22126
+ // src/browser-operation-scope.ts
22127
+ var documentId = Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, "0")).join("");
22128
+ function pajaDevelopmentConsentScope(url, windowId) {
22129
+ return `target-url:${url}|load:${documentId}:${windowId}`;
22130
+ }
22131
+ function scopePajaService(base, types, create, scopeKey) {
22132
+ const windows = /* @__PURE__ */ new Map();
22133
+ let runtime;
22134
+ let attached = true;
22135
+ return {
22136
+ ...base,
22137
+ onRegistered(context) {
22138
+ runtime = context;
22139
+ attached = true;
22140
+ base.onRegistered?.(context);
22141
+ },
22142
+ handleMessage(windowId, message2, send) {
22143
+ if (!attached) return;
22144
+ if (!types.includes(message2.type)) return base.handleMessage(windowId, message2, send);
22145
+ let entry = windows.get(windowId);
22146
+ const key = scopeKey?.(windowId);
22147
+ if (entry && entry.key !== key) {
22148
+ entry.active = false;
22149
+ entry.service.onWindowDestroyed?.(windowId);
22150
+ entry.service.onUnregistered?.();
22151
+ windows.delete(windowId);
22152
+ entry = void 0;
22153
+ }
22154
+ if (!entry) {
22155
+ const state = { active: true, key };
22156
+ const service = create(windowId, () => attached && state.active && (!runtime || runtime.listWindowIds().includes(windowId)));
22157
+ entry = Object.assign(state, { service });
22158
+ windows.set(windowId, entry);
22159
+ if (runtime) service.onRegistered?.(runtime);
22160
+ }
22161
+ entry.service.handleMessage(windowId, message2, send);
22162
+ },
22163
+ onWindowDestroyed(windowId) {
22164
+ const entry = windows.get(windowId);
22165
+ if (entry) {
22166
+ entry.active = false;
22167
+ entry.service.onWindowDestroyed?.(windowId);
22168
+ entry.service.onUnregistered?.();
22169
+ windows.delete(windowId);
22170
+ }
22171
+ base.onWindowDestroyed?.(windowId);
22172
+ },
22173
+ onCapabilityRevoked(windowId, capability) {
22174
+ const entry = windows.get(windowId);
22175
+ if (entry) {
22176
+ entry.active = false;
22177
+ entry.service.onCapabilityRevoked?.(windowId, capability);
22178
+ entry.service.onWindowDestroyed?.(windowId);
22179
+ entry.service.onUnregistered?.();
22180
+ windows.delete(windowId);
22181
+ }
22182
+ base.onCapabilityRevoked?.(windowId, capability);
22183
+ },
22184
+ onUnregistered() {
22185
+ attached = false;
22186
+ for (const [windowId, entry] of windows) {
22187
+ entry.active = false;
22188
+ entry.service.onWindowDestroyed?.(windowId);
22189
+ entry.service.onUnregistered?.();
22190
+ }
22191
+ windows.clear();
22192
+ base.onUnregistered?.();
22193
+ }
22194
+ };
22195
+ }
22196
+ function scopePajaRelayBackend(base, context) {
22197
+ const current = async () => {
22198
+ const value = await context();
22199
+ if (value?.isCurrent && !value.isCurrent()) throw new Error("Paja publication source changed");
22200
+ return value;
22201
+ };
22202
+ return {
22203
+ ...base,
22204
+ async publish(relays, event) {
22205
+ return base.publish(relays, event, await current());
22206
+ },
22207
+ async publishToRelays(relays, event) {
22208
+ return base.publishToRelays(relays, event, await current());
22209
+ }
22210
+ };
22211
+ }
22212
+ function createPajaWindowScope(options) {
22213
+ const account = options.getPubkey();
22214
+ const source = {
22215
+ ...options.source,
22216
+ isCurrent: () => options.isCurrent() && account === options.getPubkey() && (!options.source.isCurrent || options.source.isCurrent())
22217
+ };
22218
+ const getSigner = () => options.getSigner(source);
22219
+ return {
22220
+ source,
22221
+ getSigner,
22222
+ backend: scopePajaRelayBackend(options.backend, async () => {
22223
+ if (!source.isCurrent?.()) throw new Error("Paja publication source changed");
22224
+ const signerPubkey = await getSigner()?.getPublicKey?.();
22225
+ if (!signerPubkey || !account) return {
22226
+ ...source,
22227
+ signerPubkey: "host-generated",
22228
+ runtimeScope: `${source.runtimeScope}|host-session:${documentId}`
22229
+ };
22230
+ if (signerPubkey.toLowerCase() !== account.toLowerCase()) throw new Error("Paja signer account changed");
22231
+ return { ...source, signerPubkey };
22232
+ })
22233
+ };
22234
+ }
21530
22235
  function createPajaCvmRelayPool(backend) {
21531
22236
  return {
21532
22237
  subscribe(relays, filter, params) {
@@ -21546,7 +22251,29 @@ function createPajaCvmRelayPool(backend) {
21546
22251
  }
21547
22252
  };
21548
22253
  }
21549
- function createOutboxRouter(backend, getSimulation, relayConfig, confirmRequest, signerProvider) {
22254
+ function getRuntimePubkey(getSimulation, signerProvider) {
22255
+ return signerProvider?.getPubkey() || (signerProvider?.getMethod() === "dev" ? PAJA_DEV_SIGNER_PUBKEY : "") || getSimulation().identity.pubkey;
22256
+ }
22257
+ function createRuntimeSigner(getSimulation, confirmRequest, signerProvider, source) {
22258
+ const signer = signerProvider?.getSigner(source);
22259
+ if (!signer) {
22260
+ if (signerProvider?.getMethod() === "dev") {
22261
+ return createPajaDevSigner(getSimulation, confirmRequest, source);
22262
+ }
22263
+ const fixedPubkey = getSimulation().identity.pubkey;
22264
+ if (fixedPubkey) {
22265
+ return {
22266
+ getPublicKey: () => fixedPubkey,
22267
+ getRelays: () => Object.fromEntries(getPajaRelayUrls(getSimulation()).map((relay) => [relay, { read: true, write: true }]))
22268
+ };
22269
+ }
22270
+ return null;
22271
+ }
22272
+ return signer;
22273
+ }
22274
+
22275
+ // src/browser-adapter.ts
22276
+ function createOutboxRouter(backend, getSimulation, relayConfig, confirmRequest, signerProvider, source) {
21550
22277
  return createRelayPoolOutboxRouter({
21551
22278
  relayPool: createPajaOutboxRelayPool(backend),
21552
22279
  loadRelayLists: createPajaRelayListLoader(
@@ -21557,7 +22284,7 @@ function createOutboxRouter(backend, getSimulation, relayConfig, confirmRequest,
21557
22284
  ),
21558
22285
  fallbackRelays: relayConfig.outboxRelays,
21559
22286
  signEvent: async (template) => {
21560
- const signer = createRuntimeSigner(getSimulation, confirmRequest, signerProvider);
22287
+ const signer = createRuntimeSigner(getSimulation, confirmRequest, signerProvider, source);
21561
22288
  if (!signer?.signEvent) throw new Error("no signer configured");
21562
22289
  const event = { ...template };
21563
22290
  event.created_at ??= Math.floor(Date.now() / 1e3);
@@ -21581,27 +22308,23 @@ function createDevTheme(mode, values) {
21581
22308
  }
21582
22309
  };
21583
22310
  }
21584
- function getRuntimePubkey(getSimulation, signerProvider) {
21585
- return signerProvider?.getPubkey() || (signerProvider?.getMethod() === "dev" ? PAJA_DEV_SIGNER_PUBKEY : "") || getSimulation().identity.pubkey;
21586
- }
21587
- function createRuntimeSigner(getSimulation, confirmRequest, signerProvider, source) {
21588
- const signer = signerProvider?.getSigner(source);
21589
- if (!signer) {
21590
- if (signerProvider?.getMethod() === "dev") {
21591
- return createPajaDevSigner(getSimulation, confirmRequest, source);
21592
- }
21593
- const fixedPubkey = getSimulation().identity.pubkey;
21594
- if (fixedPubkey) {
21595
- return {
21596
- getPublicKey: () => fixedPubkey,
21597
- getRelays: () => Object.fromEntries(getPajaRelayUrls(getSimulation()).map((relay) => [relay, { read: true, write: true }]))
21598
- };
21599
- }
21600
- return null;
21601
- }
21602
- return signer;
21603
- }
21604
- function createDevServices(backend, getSimulation, relayConfig, onThemeService, onThemeBroadcast, confirmRequest, getConfiguredBlossomServers, uploadRuntime, signerProvider, getIdentity, userActivation, notifyOptions, configOptions) {
22311
+ function createDevServices(backend, getSimulation, relayConfig, onThemeService, onThemeBroadcast, confirmRequest, getConfiguredBlossomServers, uploadRuntime, signerProvider, getIdentity, userActivation, notifyOptions, configOptions, getSignerSource) {
22312
+ const scopeFor = (windowId, isCurrent) => createPajaWindowScope({
22313
+ backend,
22314
+ source: getSignerSource?.(windowId) ?? {
22315
+ windowId,
22316
+ napplet: getIdentity?.(windowId) ?? { dTag: "dev-target", aggregateHash: "paja" },
22317
+ runtimeScope: `window:${windowId}`
22318
+ },
22319
+ isCurrent,
22320
+ getPubkey: () => getRuntimePubkey(getSimulation, signerProvider),
22321
+ getSigner: (source) => createRuntimeSigner(getSimulation, confirmRequest, signerProvider, source)
22322
+ });
22323
+ const scopeKey = (windowId) => JSON.stringify([
22324
+ getSignerSource?.(windowId).runtimeScope,
22325
+ getIdentity?.(windowId).aggregateHash,
22326
+ getRuntimePubkey(getSimulation, signerProvider)
22327
+ ]);
21605
22328
  const theme = createThemeService({
21606
22329
  initialTheme: createDevTheme(getSimulation().theme.mode, getSimulation().theme.values),
21607
22330
  onBroadcast: onThemeBroadcast
@@ -21636,6 +22359,7 @@ function createDevServices(backend, getSimulation, relayConfig, onThemeService,
21636
22359
  });
21637
22360
  void socialCache.refreshActiveIdentity();
21638
22361
  const resourceService = createResourceService({
22362
+ stream: createBrowserMediaStreamFetch(),
21639
22363
  fetch: createPajaResourceFetch({
21640
22364
  getBlossomServers: ({ url, windowId }) => blossomEventResolver.getServers(url, windowId)
21641
22365
  }),
@@ -21657,7 +22381,7 @@ function createDevServices(backend, getSimulation, relayConfig, onThemeService,
21657
22381
  services.keys = createKeysService({ listenerTarget: document });
21658
22382
  }
21659
22383
  if (getSimulation().relay.mode === "live") {
21660
- services.relay = createRelayPoolService({
22384
+ const relayOptions = {
21661
22385
  subscribe: (filters, callback, relayUrls2, fromHint) => backend.subscription(
21662
22386
  (relayUrls2 ?? getReadRelays()).filter((url) => isPajaRelayAllowed(url, getAllRelays)),
21663
22387
  filters,
@@ -21670,11 +22394,19 @@ function createDevServices(backend, getSimulation, relayConfig, onThemeService,
21670
22394
  );
21671
22395
  }
21672
22396
  }),
21673
- publish: (event) => backend.publish(getWriteRelays(), event),
21674
22397
  selectRelayTier: getReadRelays,
21675
22398
  isAvailable: () => backend.isAvailable()
21676
- });
21677
- services.outbox = createOutboxService({
22399
+ };
22400
+ services.relay = scopePajaService(
22401
+ createRelayPoolService({ ...relayOptions, publish: (event) => backend.publish(getWriteRelays(), event) }),
22402
+ ["relay.publish", "relay.publishEncrypted"],
22403
+ (windowId, isCurrent) => {
22404
+ const scope = scopeFor(windowId, isCurrent);
22405
+ return createRelayPoolService({ ...relayOptions, publish: (event) => scope.backend.publish(getWriteRelays(), event) });
22406
+ },
22407
+ scopeKey
22408
+ );
22409
+ const outboxOptions = {
21678
22410
  router: baseOutboxRouter,
21679
22411
  getReadRouter: (windowId) => blossomEventResolver.decorate(baseOutboxRouter, windowId),
21680
22412
  getQueryRouter: (windowId, context) => blossomEventResolver.decorate(
@@ -21684,7 +22416,14 @@ function createDevServices(backend, getSimulation, relayConfig, onThemeService,
21684
22416
  ),
21685
22417
  windowId
21686
22418
  )
21687
- });
22419
+ };
22420
+ services.outbox = scopePajaService(createOutboxService(outboxOptions), ["outbox.publish"], (windowId, isCurrent) => {
22421
+ const scope = scopeFor(windowId, isCurrent);
22422
+ return createOutboxService({
22423
+ ...outboxOptions,
22424
+ router: createOutboxRouter(scope.backend, getSimulation, relayConfig, confirmRequest, signerProvider, scope.source)
22425
+ });
22426
+ }, scopeKey);
21688
22427
  }
21689
22428
  if (getSimulation().capabilities.domains.count && getSimulation().relay.mode === "live") {
21690
22429
  services.count = createCountService({
@@ -21715,17 +22454,28 @@ function createDevServices(backend, getSimulation, relayConfig, onThemeService,
21715
22454
  if (getSimulation().notifications.enabled && notifyOptions) {
21716
22455
  services.notify = createNotifyService(notifyOptions);
21717
22456
  }
21718
- if (getSimulation().media.enabled && typeof navigator !== "undefined" && "mediaSession" in navigator && typeof document !== "undefined") services.media = createMediaService({ mediaSessionTarget: navigator.mediaSession, documentTarget: document });
22457
+ if (getSimulation().media.enabled && typeof document !== "undefined" && document.body) {
22458
+ const media = createMediaService({ playback: createBrowserMediaPlayback({ resource: resourceService, stream: resourceService.openStream }) });
22459
+ const unmount = mountMediaPlayer(media);
22460
+ services.media = { ...media, onUnregistered() {
22461
+ unmount();
22462
+ media.destroy();
22463
+ } };
22464
+ }
21719
22465
  if (getSimulation().capabilities.domains.theme) services.theme = theme.handler;
21720
22466
  if (getSimulation().capabilities.domains.config && config) services.config = config.handler;
21721
22467
  if (getSimulation().cvm.enabled && getSimulation().relay.mode === "live" && backend.isAvailable()) {
21722
- services.cvm = createCvmService({
21723
- transport: createNostrCvmTransport({
21724
- defaultRelays: relayConfig.allRelays,
21725
- pool: createPajaCvmRelayPool(backend),
21726
- clientInfo: { name: "@kehto/paja", version: "0.11.0" }
21727
- })
21728
- });
22468
+ const cvm = (relay) => {
22469
+ const service = createCvmService({
22470
+ transport: createNostrCvmTransport({
22471
+ defaultRelays: relayConfig.allRelays,
22472
+ pool: createPajaCvmRelayPool(relay),
22473
+ clientInfo: { name: "@kehto/paja", version: "0.11.0" }
22474
+ })
22475
+ });
22476
+ return { ...service, onUnregistered: () => service.dispose() };
22477
+ };
22478
+ services.cvm = scopePajaService(cvm(backend), ["cvm.request", "cvm.close"], (windowId, isCurrent) => cvm(scopeFor(windowId, isCurrent).backend), scopeKey);
21729
22479
  }
21730
22480
  if (uploadRuntime) {
21731
22481
  services.upload = createUploadService({
@@ -21737,33 +22487,46 @@ function createDevServices(backend, getSimulation, relayConfig, onThemeService,
21737
22487
  services.link = createLinkService({
21738
22488
  open: async ({ windowId, url, options }) => {
21739
22489
  const napplet = getIdentity?.(windowId) ?? { dTag: "dev-target", aggregateHash: "paja" };
21740
- const allowed2 = await confirmRequest({
22490
+ const request = {
21741
22491
  action: "link",
21742
22492
  windowId,
21743
22493
  napplet,
21744
22494
  url: url.href,
21745
- ...options?.label ? { label: options.label } : {}
21746
- });
21747
- return { status: allowed2 && openPajaExternalLink(url) ? "opened" : "denied" };
22495
+ ...options?.label ? { label: options.label } : {},
22496
+ isCurrent: () => (!("isCurrent" in napplet) || typeof napplet.isCurrent !== "function" || napplet.isCurrent()) && (getIdentity?.(windowId).aggregateHash ?? napplet.aggregateHash) === napplet.aggregateHash
22497
+ };
22498
+ const open = () => request.isCurrent?.() !== false && openPajaExternalLink(url);
22499
+ try {
22500
+ const opened = userActivation ? await userActivation.run(request, open) : await confirmRequest(request) && open();
22501
+ return { status: opened ? "opened" : "denied" };
22502
+ } catch {
22503
+ return { status: "denied" };
22504
+ }
21748
22505
  }
21749
22506
  });
21750
22507
  }
21751
22508
  if (getSimulation().capabilities.domains.common && getSimulation().relay.mode === "live") {
21752
- services.common = createCommonService({
22509
+ services.common = scopePajaService(createCommonService({
21753
22510
  getProfile: (target) => commonBackend.getProfile(target),
21754
22511
  follows: () => commonBackend.follows(),
21755
22512
  follow: (pubkeys) => commonBackend.follow(pubkeys),
21756
22513
  unfollow: (pubkeys) => commonBackend.unfollow(pubkeys),
21757
22514
  react: (targetEventId, reaction, customEmojiHref) => commonBackend.react(targetEventId, reaction, customEmojiHref),
21758
22515
  report: (target, reason, text) => commonBackend.report(target, reason, text)
21759
- });
22516
+ }), ["common.follow", "common.unfollow", "common.react", "common.report"], (windowId, isCurrent) => {
22517
+ const scope = scopeFor(windowId, isCurrent);
22518
+ return createCommonService(createPajaCommonBackend({ relay: scope.backend, getRelays: getAllRelays, getSigner: scope.getSigner }));
22519
+ }, scopeKey);
21760
22520
  }
21761
22521
  if (getSimulation().capabilities.domains.lists && getSimulation().relay.mode === "live") {
21762
- services.lists = createListsService({
22522
+ services.lists = scopePajaService(createListsService({
21763
22523
  supported: () => listsBackend.supported(),
21764
22524
  add: (list, items, options) => listsBackend.add(list, items, options),
21765
22525
  remove: (list, items, options) => listsBackend.remove(list, items, options)
21766
- });
22526
+ }), ["lists.add", "lists.remove"], (windowId, isCurrent) => {
22527
+ const scope = scopeFor(windowId, isCurrent);
22528
+ return createListsService(createPajaListsBackend({ relay: scope.backend, getRelays: getAllRelays, getSigner: scope.getSigner }));
22529
+ }, scopeKey);
21767
22530
  }
21768
22531
  if (getSimulation().capabilities.domains.serial) {
21769
22532
  const controller = userActivation ? createBrowserSerialController(userActivation) : null;
@@ -21783,7 +22546,7 @@ function createDevServices(backend, getSimulation, relayConfig, onThemeService,
21783
22546
  },
21784
22547
  publish: (event) => backend.publishWebrtcSignal(getAllRelays(), event)
21785
22548
  },
21786
- getSigner: () => createRuntimeSigner(getSimulation, confirmRequest, signerProvider),
22549
+ getSigner: (windowId) => createRuntimeSigner(getSimulation, confirmRequest, signerProvider, windowId ? getSignerSource?.(windowId) : void 0),
21787
22550
  getPubkey: () => getRuntimePubkey(getSimulation, signerProvider),
21788
22551
  getIdentity: getIdentity ?? (() => ({ dTag: "dev-target", aggregateHash: "paja" })),
21789
22552
  confirm: confirmRequest
@@ -21826,10 +22589,16 @@ function createPajaAdapter(config, getSimulation, onThemeService, onThemeBroadca
21826
22589
  };
21827
22590
  const signerSource = (windowId) => {
21828
22591
  const napplet = resolveIdentity(windowId);
22592
+ const account = getRuntimePubkey(getSimulation, signerProvider);
22593
+ const runtimeScope = "consentScope" in napplet && typeof napplet.consentScope === "string" ? napplet.consentScope : config.target?.mode === "iframe-url" ? pajaDevelopmentConsentScope(config.target.url, windowId) : `artifact:${napplet.aggregateHash}`;
21829
22594
  return {
21830
22595
  windowId,
21831
22596
  napplet,
21832
- runtimeScope: config.target?.mode === "iframe-url" ? `target-url:${config.target.url}` : `artifact:${napplet.aggregateHash}`
22597
+ runtimeScope,
22598
+ isCurrent: () => {
22599
+ const current = resolveIdentity(windowId);
22600
+ return (!("isCurrent" in napplet) || typeof napplet.isCurrent !== "function" || napplet.isCurrent()) && account === getRuntimePubkey(getSimulation, signerProvider) && current.dTag === napplet.dTag && current.aggregateHash === napplet.aggregateHash && (!("consentScope" in napplet) || "consentScope" in current && current.consentScope === napplet.consentScope);
22601
+ }
21833
22602
  };
21834
22603
  };
21835
22604
  const relayBackend = createPajaRelayBackend(getSimulation, confirmRequest);
@@ -21864,7 +22633,8 @@ function createPajaAdapter(config, getSimulation, onThemeService, onThemeBroadca
21864
22633
  resolveIdentity,
21865
22634
  userActivation,
21866
22635
  notifyOptions,
21867
- configOptions
22636
+ configOptions,
22637
+ signerSource
21868
22638
  );
21869
22639
  const services = serviceBundle.services;
21870
22640
  const ready = createPajaBrowserFsBackend({
@@ -21888,7 +22658,13 @@ function createPajaAdapter(config, getSimulation, onThemeService, onThemeBroadca
21888
22658
  notifyIntentChanged: () => {
21889
22659
  },
21890
22660
  setWindowBlossomServers: serviceBundle.setWindowBlossomServers,
21891
- relayPool: createPajaRelayHooks(relayBackend, getSimulation, relayConfig),
22661
+ relayPool: createPajaRelayHooks(relayBackend, getSimulation, relayConfig, (windowId) => createPajaWindowScope({
22662
+ backend: relayBackend,
22663
+ source: signerSource(windowId),
22664
+ isCurrent: () => true,
22665
+ getPubkey: () => getRuntimePubkey(getSimulation, signerProvider),
22666
+ getSigner: (source) => createRuntimeSigner(getSimulation, confirmRequest, signerProvider, source)
22667
+ }).backend),
21892
22668
  relayConfig,
21893
22669
  windowManager: { createWindow: () => null },
21894
22670
  auth: {
@@ -22494,7 +23270,14 @@ function redactPajaMessageForLog(message2) {
22494
23270
  function isRecord7(value) {
22495
23271
  return typeof value === "object" && value !== null && !Array.isArray(value);
22496
23272
  }
22497
- function installPajaOriginRegistryProxy(originRegistry2, stateRef) {
23273
+ function installPajaOriginRegistryProxy(originRegistry2, stateRef, onWindowRemoved) {
23274
+ if (onWindowRemoved && originRegistry2.unregister) {
23275
+ const unregister = originRegistry2.unregister.bind(originRegistry2);
23276
+ originRegistry2.unregister = (windowId) => {
23277
+ onWindowRemoved(windowId);
23278
+ unregister(windowId);
23279
+ };
23280
+ }
22498
23281
  const originalGetIframeWindow = originRegistry2.getIframeWindow.bind(originRegistry2);
22499
23282
  originRegistry2.getIframeWindow = (windowId) => {
22500
23283
  const win = originalGetIframeWindow(windowId);
@@ -22628,8 +23411,8 @@ function renderSignerStatus(state, signerPubkey) {
22628
23411
  const methodLabel = state.signer.method === "nip07" ? "NIP-07" : state.signer.method === "nip46" ? "bunker" : state.signer.method === "dev" ? "dev" : "none";
22629
23412
  const relay = state.signer.relay ? ` \xB7 relay ${state.signer.relay}` : "";
22630
23413
  const prefix = state.signer.status === "disconnected" ? "no signer connected" : state.signer.status === "error" ? `${methodLabel} error: ${state.signer.error ?? "unknown error"} \xB7 fallback pubkey ${fallbackPubkey}` : `${methodLabel} ${state.signer.status} \xB7 pubkey ${pubkey2 || "(none)"}${relay}`;
22631
- const consentSummary = state.signerConsentCount === 0 ? "signing asks every time" : `${state.signerConsentCount} remembered signing approval${state.signerConsentCount === 1 ? "" : "s"}`;
22632
- el.textContent = `${prefix} \xB7 ${consentSummary} \xB7 publishing asks every time`;
23414
+ const consentSummary = state.signerConsentCount === 0 ? "signing and publishing ask every time" : `${state.signerConsentCount} remembered signing/publishing approval${state.signerConsentCount === 1 ? "" : "s"}`;
23415
+ el.textContent = `${prefix} \xB7 ${consentSummary}`;
22633
23416
  clearConsent.hidden = state.signerConsentCount === 0;
22634
23417
  clearConsent.textContent = `Forget ${state.signerConsentCount} remembered approval${state.signerConsentCount === 1 ? "" : "s"}`;
22635
23418
  clearConsent.onclick = () => state.clearSignerConsent();
@@ -22857,6 +23640,7 @@ function createConfirmedSigner(signer, confirmRequest, source) {
22857
23640
  return {
22858
23641
  ...signer,
22859
23642
  async signEvent(event) {
23643
+ if (source?.isCurrent && !source.isCurrent()) throw new Error("Paja signing source changed");
22860
23644
  if (typeof signer.signEvent !== "function") {
22861
23645
  throw new Error("Signer does not support event signing");
22862
23646
  }
@@ -22868,6 +23652,7 @@ function createConfirmedSigner(signer, confirmRequest, source) {
22868
23652
  })) {
22869
23653
  throw new Error("Paja signing request denied");
22870
23654
  }
23655
+ if (source?.isCurrent && !source.isCurrent()) throw new Error("Paja signing source changed");
22871
23656
  return signer.signEvent(event);
22872
23657
  }
22873
23658
  };
@@ -22989,6 +23774,7 @@ var PAJA_SIGNER_CONSENT_VERSION = 1;
22989
23774
  var MAX_CONSENT_SUBJECTS = 128;
22990
23775
  var MAX_KINDS_PER_SUBJECT = 128;
22991
23776
  var MAX_IDENTITY_FIELD_LENGTH = 512;
23777
+ var warnedLegacyConsent = false;
22992
23778
  function createPajaSignerConsentStore(storage = readPajaSignerConsentStorage()) {
22993
23779
  let grants = readConsentDocument(storage).grants;
22994
23780
  const persist = () => {
@@ -23013,38 +23799,60 @@ function createPajaSignerConsentStore(storage = readPajaSignerConsentStorage())
23013
23799
  const existing = grants.find((grant2) => sameSubject(grant2, subject));
23014
23800
  if (existing) return existing;
23015
23801
  if (grants.length >= MAX_CONSENT_SUBJECTS) return null;
23016
- const created = { ...subject, trusted: false, kinds: [] };
23802
+ const created = { ...subject, trusted: false, kinds: [], publishTrusted: false, publishKinds: [] };
23017
23803
  grants = [...grants, created];
23018
23804
  return created;
23019
23805
  };
23020
23806
  return {
23021
- match(context, kind) {
23807
+ match(context, kind, action = "sign") {
23808
+ if (context.isCurrent && !context.isCurrent()) return null;
23022
23809
  const normalizedKind = normalizeKind(kind);
23023
23810
  if (normalizedKind === null) return null;
23024
23811
  const record2 = recordFor(context);
23025
23812
  if (!record2) return null;
23026
- if (record2.trusted) return "napplet";
23027
- return record2.kinds.includes(normalizedKind) ? "kind" : null;
23813
+ const trusted = action === "sign" ? record2.trusted : record2.publishTrusted;
23814
+ const kinds = action === "sign" ? record2.kinds : record2.publishKinds;
23815
+ if (trusted) return "napplet";
23816
+ return kinds.includes(normalizedKind) ? "kind" : null;
23028
23817
  },
23029
- rememberKind(context, kind) {
23818
+ rememberKind(context, kind, action = "sign") {
23819
+ if (context.isCurrent && !context.isCurrent()) return false;
23030
23820
  const normalizedKind = normalizeKind(kind);
23031
23821
  if (normalizedKind === null) return false;
23032
23822
  const record2 = ensureRecord(context);
23033
23823
  if (!record2) return false;
23034
- if (record2.trusted || record2.kinds.includes(normalizedKind)) return true;
23035
- if (record2.kinds.length >= MAX_KINDS_PER_SUBJECT) return false;
23036
- record2.kinds = [...record2.kinds, normalizedKind].sort((left, right) => left - right);
23824
+ const kinds = action === "sign" ? record2.kinds : record2.publishKinds;
23825
+ if ((action === "sign" ? record2.trusted : record2.publishTrusted) || kinds.includes(normalizedKind)) return true;
23826
+ if (kinds.length >= MAX_KINDS_PER_SUBJECT) return false;
23827
+ const next = [...kinds, normalizedKind].sort((left, right) => left - right);
23828
+ if (action === "sign") record2.kinds = next;
23829
+ else record2.publishKinds = next;
23037
23830
  persist();
23038
23831
  return true;
23039
23832
  },
23040
- trustNapplet(context) {
23833
+ trustNapplet(context, action = "sign") {
23834
+ if (context.isCurrent && !context.isCurrent()) return false;
23041
23835
  const record2 = ensureRecord(context);
23042
23836
  if (!record2) return false;
23043
- if (!record2.trusted || record2.kinds.length > 0) {
23837
+ if (action === "sign") {
23044
23838
  record2.trusted = true;
23045
23839
  record2.kinds = [];
23046
- persist();
23840
+ } else {
23841
+ record2.publishTrusted = true;
23842
+ record2.publishKinds = [];
23047
23843
  }
23844
+ persist();
23845
+ return true;
23846
+ },
23847
+ trustVersion(context) {
23848
+ if (context.isCurrent && !context.isCurrent()) return false;
23849
+ const record2 = ensureRecord(context);
23850
+ if (!record2) return false;
23851
+ record2.trusted = true;
23852
+ record2.kinds = [];
23853
+ record2.publishTrusted = true;
23854
+ record2.publishKinds = [];
23855
+ persist();
23048
23856
  return true;
23049
23857
  },
23050
23858
  clear() {
@@ -23069,7 +23877,7 @@ function createPajaSignerConsentStore(storage = readPajaSignerConsentStorage())
23069
23877
  }
23070
23878
  },
23071
23879
  count() {
23072
- return grants.reduce((total, grant2) => total + (grant2.trusted ? 1 : grant2.kinds.length), 0);
23880
+ return grants.reduce((total, grant2) => total + (grant2.trusted ? 1 : grant2.kinds.length) + (grant2.publishTrusted ? 1 : grant2.publishKinds.length), 0);
23073
23881
  }
23074
23882
  };
23075
23883
  }
@@ -23096,6 +23904,10 @@ function readConsentDocument(storage) {
23096
23904
  for (const candidate of parsed.grants.slice(0, MAX_CONSENT_SUBJECTS)) {
23097
23905
  const record2 = normalizeRecord(candidate);
23098
23906
  if (!record2 || grants.some((existing) => sameSubject(existing, record2))) continue;
23907
+ if (!warnedLegacyConsent && candidate && typeof candidate === "object" && !("publishTrusted" in candidate) && !("publishKinds" in candidate)) {
23908
+ warnedLegacyConsent = true;
23909
+ console.warn("[KEHTO-PAJA-SIGNER-CONSENT-V1] Loaded older signing-only approvals. Publishing still requires approval; review the current napplet version to allow signing and publishing together. This warning appears once per host module lifetime.");
23910
+ }
23099
23911
  grants.push(record2);
23100
23912
  }
23101
23913
  return { version: PAJA_SIGNER_CONSENT_VERSION, grants };
@@ -23117,7 +23929,10 @@ function normalizeRecord(value) {
23117
23929
  return {
23118
23930
  ...subject,
23119
23931
  trusted: candidate.trusted,
23120
- kinds: candidate.trusted ? [] : kinds
23932
+ kinds: candidate.trusted ? [] : kinds,
23933
+ // Old records are signing-only; their omission never grants publication.
23934
+ publishTrusted: candidate.publishTrusted === true,
23935
+ publishKinds: candidate.publishTrusted === true ? [] : Array.isArray(candidate.publishKinds) ? [...new Set(candidate.publishKinds.map(normalizeKind).filter((kind) => kind !== null))].slice(0, MAX_KINDS_PER_SUBJECT) : []
23121
23936
  };
23122
23937
  }
23123
23938
  function normalizeContext(context) {
@@ -23129,8 +23944,9 @@ function normalizeContext(context) {
23129
23944
  );
23130
23945
  }
23131
23946
  function normalizeSubject(signerPubkey, dTag, aggregateHash, runtimeScope) {
23132
- if (typeof signerPubkey !== "string" || !/^[0-9a-f]{64}$/i.test(signerPubkey)) return null;
23133
- if (!validIdentityField(dTag) || !validIdentityField(aggregateHash) || !validIdentityField(runtimeScope)) return null;
23947
+ const hostGenerated = signerPubkey === "host-generated" && typeof runtimeScope === "string" && /\|host-session:[a-f0-9]{32}$/.test(runtimeScope);
23948
+ if (typeof signerPubkey !== "string" || !/^[0-9a-f]{64}$/i.test(signerPubkey) && !hostGenerated) return null;
23949
+ if (typeof dTag !== "string" || dTag.length > MAX_IDENTITY_FIELD_LENGTH || !validIdentityField(aggregateHash) || !validIdentityField(runtimeScope)) return null;
23134
23950
  return {
23135
23951
  signerPubkey: signerPubkey.toLowerCase(),
23136
23952
  dTag,
@@ -23155,52 +23971,53 @@ function confirmationDetails(...lines) {
23155
23971
  function confirmationCopy(title, summary, approveLabel, ...details) {
23156
23972
  return { title, summary, details: confirmationDetails(...details), approveLabel };
23157
23973
  }
23158
- function createPajaConfirmationController(getState, options = {}) {
23159
- const dialog = document.getElementById("paja-confirmation-dialog");
23160
- const title = document.getElementById("paja-confirmation-title");
23161
- const summary = document.getElementById("paja-confirmation-summary");
23162
- const details = document.getElementById("paja-confirmation-details");
23163
- const approve = document.getElementById("paja-confirmation-approve");
23164
- const deny = document.getElementById("paja-confirmation-deny");
23974
+ function createSignerConsentChoices(consentStore, reportSignerConsentChange) {
23165
23975
  const signerConsent = document.getElementById("paja-signer-consent");
23166
23976
  const signerConsentOnce = document.getElementById("paja-signer-consent-once");
23167
23977
  const signerConsentKind = document.getElementById("paja-signer-consent-kind");
23168
23978
  const signerConsentNapplet = document.getElementById("paja-signer-consent-napplet");
23979
+ const signerConsentVersion = document.getElementById("paja-signer-consent-version");
23169
23980
  const signerConsentKindValue = document.getElementById("paja-signer-consent-kind-value");
23170
23981
  const signerConsentNappletValue = document.getElementById("paja-signer-consent-napplet-value");
23171
- const ready = dialog instanceof HTMLDialogElement && title instanceof HTMLElement && summary instanceof HTMLElement && details instanceof HTMLElement && approve instanceof HTMLButtonElement && deny instanceof HTMLButtonElement;
23172
23982
  const signerConsentReady = signerConsent instanceof HTMLFieldSetElement && signerConsentOnce instanceof HTMLInputElement && signerConsentKind instanceof HTMLInputElement && signerConsentNapplet instanceof HTMLInputElement && signerConsentKindValue instanceof HTMLElement && signerConsentNappletValue instanceof HTMLElement;
23173
- const consentStore = createPajaSignerConsentStore(
23174
- options.storage === void 0 ? void 0 : options.storage
23175
- );
23176
- const queue = [];
23177
- let active = null;
23178
- let previousFocus = null;
23179
- let disposed = false;
23180
- const reportSignerConsentChange = () => {
23181
- options.onSignerConsentChange?.(consentStore.count());
23182
- };
23183
23983
  const configureSignerConsent = (request) => {
23184
23984
  if (!signerConsentReady) return;
23185
23985
  signerConsent.hidden = true;
23186
23986
  signerConsentOnce.checked = true;
23187
23987
  signerConsentKind.checked = false;
23188
23988
  signerConsentNapplet.checked = false;
23989
+ if (signerConsentVersion instanceof HTMLInputElement) signerConsentVersion.checked = false;
23189
23990
  const candidate = signerConsentCandidate(request);
23190
23991
  if (!candidate) return;
23191
23992
  signerConsent.hidden = false;
23192
23993
  signerConsentKindValue.textContent = String(candidate.kind);
23193
- signerConsentNappletValue.textContent = candidate.context.napplet.dTag;
23994
+ signerConsentNappletValue.textContent = candidate.context.napplet.dTag || "Root napplet";
23995
+ const verb = request.action === "publish" ? "Publish" : "Sign";
23996
+ for (const [id, text] of [
23997
+ ["paja-signer-consent-legend", `Remember this ${request.action === "publish" ? "publishing" : "signing"} choice`],
23998
+ ["paja-signer-consent-once-label", `${verb} this event only`],
23999
+ ["paja-signer-consent-kind-verb", `Always ${verb.toLowerCase()} kind`],
24000
+ ["paja-signer-consent-napplet-verb", `Allow all ${request.action === "publish" ? "publishing" : "signing"} from`],
24001
+ ["paja-signer-consent-warning", `Paja will ${verb.toLowerCase()} any event this napplet version requests without asking again. A different version or signer needs new approval.`]
24002
+ ]) {
24003
+ const element2 = document.getElementById(id);
24004
+ if (element2) element2.textContent = text;
24005
+ }
23194
24006
  };
23195
24007
  const rememberSignerChoice = (request) => {
23196
24008
  if (!signerConsentReady) return "once";
23197
24009
  const candidate = signerConsentCandidate(request);
23198
24010
  if (!candidate) return "once";
23199
- if (signerConsentNapplet.checked && consentStore.trustNapplet(candidate.context)) {
24011
+ if (signerConsentVersion instanceof HTMLInputElement && signerConsentVersion.checked && consentStore.trustVersion(candidate.context)) {
24012
+ reportSignerConsentChange();
24013
+ return "trust-version";
24014
+ }
24015
+ const action = request.action === "publish" ? "publish" : "sign";
24016
+ if (signerConsentNapplet.checked && consentStore.trustNapplet(candidate.context, action)) {
23200
24017
  reportSignerConsentChange();
23201
24018
  return "trust-napplet";
23202
24019
  }
23203
- if (signerConsentKind.checked && consentStore.rememberKind(candidate.context, candidate.kind)) {
24020
+ if (signerConsentKind.checked && consentStore.rememberKind(candidate.context, candidate.kind, action)) {
23204
24021
  reportSignerConsentChange();
23205
24022
  return "remember-kind";
23206
24023
  }
@@ -23208,14 +24025,40 @@ function createPajaConfirmationController(getState, options = {}) {
23208
24025
  };
23209
24026
  const rememberedSignerChoice = (request) => {
23210
24027
  const candidate = signerConsentCandidate(request);
23211
- return candidate ? consentStore.match(candidate.context, candidate.kind) : null;
24028
+ return candidate ? consentStore.match(candidate.context, candidate.kind, request.action === "publish" ? "publish" : "sign") : null;
23212
24029
  };
24030
+ return { configure: configureSignerConsent, remember: rememberSignerChoice, match: rememberedSignerChoice };
24031
+ }
24032
+ function createPajaConfirmationController(getState, options = {}) {
24033
+ const dialog = document.getElementById("paja-confirmation-dialog");
24034
+ const title = document.getElementById("paja-confirmation-title");
24035
+ const summary = document.getElementById("paja-confirmation-summary");
24036
+ const details = document.getElementById("paja-confirmation-details");
24037
+ const approve = document.getElementById("paja-confirmation-approve");
24038
+ const deny = document.getElementById("paja-confirmation-deny");
24039
+ const ready = dialog instanceof HTMLDialogElement && title instanceof HTMLElement && summary instanceof HTMLElement && details instanceof HTMLElement && approve instanceof HTMLButtonElement && deny instanceof HTMLButtonElement;
24040
+ const consentStore = createPajaSignerConsentStore(
24041
+ options.storage === void 0 ? void 0 : options.storage
24042
+ );
24043
+ const queue = [];
24044
+ let active = null;
24045
+ let previousFocus = null;
24046
+ let disposed = false;
24047
+ const reportSignerConsentChange = () => {
24048
+ options.onSignerConsentChange?.(consentStore.count());
24049
+ };
24050
+ const choices = createSignerConsentChoices(consentStore, reportSignerConsentChange);
23213
24051
  const pump = () => {
23214
24052
  if (!ready || disposed || active) return;
23215
24053
  while (!active && queue.length > 0) {
23216
24054
  const candidate = queue.shift() ?? null;
23217
24055
  if (!candidate) break;
23218
- const remembered = rememberedSignerChoice(candidate.request);
24056
+ if (!isRequestCurrent(candidate.request)) {
24057
+ recordPajaConfirmation(getState(), candidate.request, false);
24058
+ candidate.deny();
24059
+ continue;
24060
+ }
24061
+ const remembered = choices.match(candidate.request);
23219
24062
  if (!remembered) {
23220
24063
  active = candidate;
23221
24064
  break;
@@ -23234,7 +24077,7 @@ function createPajaConfirmationController(getState, options = {}) {
23234
24077
  summary.textContent = copy.summary;
23235
24078
  details.textContent = copy.details;
23236
24079
  approve.textContent = copy.approveLabel;
23237
- configureSignerConsent(active.request);
24080
+ choices.configure(active.request);
23238
24081
  previousFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
23239
24082
  dialog.showModal();
23240
24083
  deny.focus();
@@ -23242,9 +24085,10 @@ function createPajaConfirmationController(getState, options = {}) {
23242
24085
  const settle6 = (allowed2) => {
23243
24086
  const current = active;
23244
24087
  if (!current) return;
24088
+ allowed2 = allowed2 && isRequestCurrent(current.request);
23245
24089
  active = null;
23246
24090
  if (ready && dialog.open) dialog.close();
23247
- const approvalMode = allowed2 ? rememberSignerChoice(current.request) : void 0;
24091
+ const approvalMode = allowed2 ? choices.remember(current.request) : void 0;
23248
24092
  recordPajaConfirmation(getState(), current.request, allowed2, approvalMode);
23249
24093
  if (allowed2) current.approve();
23250
24094
  else current.deny();
@@ -23263,6 +24107,16 @@ function createPajaConfirmationController(getState, options = {}) {
23263
24107
  deny.addEventListener("click", onDeny);
23264
24108
  dialog.addEventListener("cancel", onCancel);
23265
24109
  }
24110
+ const cancelMatching = (matches) => {
24111
+ for (let index = queue.length - 1; index >= 0; index--) {
24112
+ const pending = queue[index];
24113
+ if (!matches(pending.request)) continue;
24114
+ queue.splice(index, 1);
24115
+ recordPajaConfirmation(getState(), pending.request, false);
24116
+ pending.deny();
24117
+ }
24118
+ if (active && matches(active.request)) settle6(false);
24119
+ };
23266
24120
  return {
23267
24121
  confirm(request) {
23268
24122
  if (!ready || disposed) {
@@ -23305,6 +24159,12 @@ function createPajaConfirmationController(getState, options = {}) {
23305
24159
  return cleared;
23306
24160
  },
23307
24161
  getSignerConsentCount: () => consentStore.count(),
24162
+ cancelWindow(windowId) {
24163
+ cancelMatching((request) => ("windowId" in request ? request.windowId : "signerContext" in request ? request.signerContext?.windowId : void 0) === windowId);
24164
+ },
24165
+ cancelSignerRequests() {
24166
+ cancelMatching((request) => request.action === "sign" || request.action === "publish");
24167
+ },
23308
24168
  dispose() {
23309
24169
  if (disposed) return;
23310
24170
  disposed = true;
@@ -23322,12 +24182,16 @@ function createPajaConfirmationController(getState, options = {}) {
23322
24182
  };
23323
24183
  }
23324
24184
  function signerConsentCandidate(request) {
23325
- if (request.action !== "sign" || !request.signerContext) return null;
24185
+ if (request.action !== "sign" && request.action !== "publish" || !request.signerContext) return null;
23326
24186
  if (!isPajaSignerConsentContext(request.signerContext)) return null;
23327
24187
  const kind = request.event.kind;
23328
24188
  if (typeof kind !== "number" || !Number.isSafeInteger(kind) || kind < 0 || kind > 65535) return null;
23329
24189
  return { context: request.signerContext, kind };
23330
24190
  }
24191
+ function isRequestCurrent(request) {
24192
+ if (request.isCurrent && !request.isCurrent()) return false;
24193
+ return !("signerContext" in request) || !request.signerContext?.isCurrent || request.signerContext.isCurrent();
24194
+ }
23331
24195
  function describeConfirmation(request) {
23332
24196
  if (request.action === "upload") {
23333
24197
  return confirmationCopy(
@@ -23348,6 +24212,7 @@ function describeConfirmation(request) {
23348
24212
  `${request.napplet.dTag} requests browser navigation.`,
23349
24213
  "Open link",
23350
24214
  `Napplet: ${request.napplet.dTag} (${request.windowId})`,
24215
+ `Version: ${request.napplet.aggregateHash}`,
23351
24216
  request.label ? `Label: ${request.label}` : void 0,
23352
24217
  `Destination: ${request.url}`
23353
24218
  );
@@ -23412,12 +24277,13 @@ function describeConfirmation(request) {
23412
24277
  const signerContext = request.signerContext;
23413
24278
  return {
23414
24279
  title: request.action === "sign" ? "Sign this Nostr event?" : "Publish this Nostr event?",
23415
- summary: request.action === "sign" ? signerContext ? `${signerContext.napplet.dTag} requests a signature from the active signer.` : "A Paja host operation requests a signature from the active signer." : "Paja will send this event to the configured relay set.",
24280
+ summary: request.action === "sign" ? signerContext ? `${signerContext.napplet.dTag} requests a signature from the active signer.` : "A Paja host operation requests a signature from the active signer." : signerContext ? `${signerContext.napplet.dTag} requests publication to the configured relays.` : "A Paja host operation will send this event to the configured relay set.",
23416
24281
  details: confirmationDetails(
23417
24282
  signerContext ? `Napplet: ${signerContext.napplet.dTag} (${signerContext.windowId})` : void 0,
23418
- signerContext ? `Identity hash: ${signerContext.napplet.aggregateHash}` : void 0,
24283
+ signerContext ? `Version: ${signerContext.napplet.aggregateHash}` : void 0,
24284
+ signerContext ? `Approval scope: ${signerContext.runtimeScope}` : void 0,
23419
24285
  signerContext?.runtimeScope.startsWith("target-url:") ? `Target URL: ${signerContext.runtimeScope.slice("target-url:".length)}` : void 0,
23420
- signerContext ? `Signer: ${signerContext.signerPubkey}` : void 0,
24286
+ signerContext ? `Signer: ${signerContext.signerPubkey === "host-generated" ? "Host-generated events (this Paja session)" : signerContext.signerPubkey}` : void 0,
23421
24287
  `Kind: ${kind}`,
23422
24288
  `Content: ${content}`
23423
24289
  ),
@@ -26528,8 +27394,17 @@ async function installPajaHost() {
26528
27394
  confirmationController.confirm
26529
27395
  );
26530
27396
  const getWindowIdentity = (windowId) => {
26531
- const tabTarget = stateRef?.tabs.find((tab) => tab.windowId === windowId)?.resolvedTarget;
26532
- return getTargetIdentity(config, tabTarget ?? stateRef?.resolvedTarget);
27397
+ const tab = stateRef?.tabs.find((tab2) => tab2.windowId === windowId);
27398
+ const target = tab?.resolvedTarget ?? stateRef?.resolvedTarget;
27399
+ const identity = getTargetIdentity(config, target);
27400
+ return {
27401
+ ...identity,
27402
+ consentScope: target ? `${isPajaLocalTarget(target) ? "local-file" : target.manifest.catalogId}:artifact:${target.aggregateHash}` : pajaDevelopmentConsentScope(config.target.url, windowId ?? ""),
27403
+ isCurrent: () => {
27404
+ const targetFrame = tab?.frame ?? frame;
27405
+ return !!targetFrame?.contentWindow && originRegistry.getWindowId(targetFrame.contentWindow) === windowId && (!tab || stateRef?.tabs.includes(tab) === true);
27406
+ }
27407
+ };
26533
27408
  };
26534
27409
  const notifyController = createPajaNotifyController({
26535
27410
  confirm: confirmationController.confirm,
@@ -26583,11 +27458,12 @@ async function installPajaHost() {
26583
27458
  await adapter.ready;
26584
27459
  const bridge = createShellBridge(adapter);
26585
27460
  const stopIdentityChanges = signerController.subscribe(() => {
27461
+ confirmationController.cancelSignerRequests();
26586
27462
  bridge.publishIdentityChanged(adapter.auth.getUserPubkey() ?? "");
26587
27463
  });
26588
27464
  themeBroadcast.attach(bridge);
26589
27465
  bridgeRef = bridge;
26590
- installPajaOriginRegistryProxy(originRegistry, () => stateRef);
27466
+ installPajaOriginRegistryProxy(originRegistry, () => stateRef, (windowId) => confirmationController.cancelWindow(windowId));
26591
27467
  const capabilities = buildShellCapabilities(adapter);
26592
27468
  const context = {
26593
27469
  config,