@kehto/paja 0.24.5 → 0.25.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2361,7 +2361,7 @@ var getPublicKey = i.getPublicKey;
2361
2361
  var finalizeEvent = i.finalizeEvent;
2362
2362
  var verifyEvent = i.verifyEvent;
2363
2363
 
2364
- // ../nip/dist/chunk-AKQIPGRC.js
2364
+ // ../nip/dist/chunk-RW3L2FAS.js
2365
2365
  var NappletResolutionError = class extends Error {
2366
2366
  code;
2367
2367
  constructor(code, message2) {
@@ -2492,6 +2492,113 @@ function warnLegacyManifest() {
2492
2492
  console.warn("[KEHTO_COMPAT_LEGACY_MANIFEST] Legacy aggregate manifest resolved. Republish with @napplet/vite-plugin >=0.15 using the current single-artifact schema. See docs/compatibility.md.");
2493
2493
  }
2494
2494
  var HASH = /^[a-f0-9]{64}$/;
2495
+ var MIME_TYPE = /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/i;
2496
+ var DIMENSIONS = /^([1-9][0-9]*)x([1-9][0-9]*)$/;
2497
+ var INTEGER = /^(?:0|[1-9][0-9]*)$/;
2498
+ var SECONDS = /^(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$/;
2499
+ var SCREENSHOT_FORMATS = ["image/png", "image/jpeg", "image/webp"];
2500
+ function fieldsOf(tag) {
2501
+ const fields = /* @__PURE__ */ new Map();
2502
+ for (const field of tag.slice(1)) {
2503
+ if (typeof field !== "string") continue;
2504
+ const space = field.indexOf(" ");
2505
+ const key = space < 0 ? field : field.slice(0, space);
2506
+ const values = fields.get(key) ?? [];
2507
+ values.push(space < 0 ? "" : field.slice(space + 1));
2508
+ fields.set(key, values);
2509
+ }
2510
+ return fields;
2511
+ }
2512
+ function parseMediaTag(tag, kind) {
2513
+ const fields = fieldsOf(tag);
2514
+ const hashes = fields.get("x");
2515
+ if (!hashes || hashes.length !== 1 || !HASH.test(hashes[0])) return void 0;
2516
+ const media = { sha256: hashes[0] };
2517
+ const optional = (key, accept) => {
2518
+ const values = fields.get(key);
2519
+ return values?.length === 1 && accept(values[0]) ? values[0] : void 0;
2520
+ };
2521
+ const mimeType = optional("m", (value) => MIME_TYPE.test(value));
2522
+ if (mimeType !== void 0) {
2523
+ const lower = mimeType.toLowerCase();
2524
+ const decodable = kind === "preview" ? lower.startsWith("video/") : SCREENSHOT_FORMATS.includes(lower);
2525
+ if (!decodable) return void 0;
2526
+ media.mimeType = mimeType;
2527
+ }
2528
+ const dim = optional("dim", (value) => DIMENSIONS.test(value));
2529
+ if (dim !== void 0) {
2530
+ const [, width, height] = DIMENSIONS.exec(dim);
2531
+ media.dim = { width: Number(width), height: Number(height) };
2532
+ }
2533
+ const size = optional("size", (value) => INTEGER.test(value));
2534
+ if (size !== void 0) media.size = Number(size);
2535
+ if (kind === "preview") {
2536
+ const duration = optional("duration", (value) => SECONDS.test(value));
2537
+ if (duration !== void 0) media.duration = Number(duration);
2538
+ }
2539
+ const alt = optional("alt", (value) => value.trim().length > 0);
2540
+ if (alt !== void 0) media.alt = alt;
2541
+ return media;
2542
+ }
2543
+ function parsePresentationMedia(tags) {
2544
+ const screenshots = [];
2545
+ for (const tag of tags) {
2546
+ if (tag[0] !== "screenshot") continue;
2547
+ const media = parseMediaTag(tag, "screenshot");
2548
+ if (media) screenshots.push(media);
2549
+ }
2550
+ const previews = tags.filter((tag) => tag[0] === "preview");
2551
+ const preview = previews.length === 1 ? parseMediaTag(previews[0], "preview") : void 0;
2552
+ return preview ? { screenshots, preview } : { screenshots };
2553
+ }
2554
+ var HASH2 = /^[a-f0-9]{64}$/;
2555
+ var GIT_COMMIT = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
2556
+ var SCP_LOCATION = /^(?:[^@\s/:]+@)?[^:\s/]+:[^\s]+$/;
2557
+ var WINDOWS_DRIVE = /^[a-z]:[\\/]/i;
2558
+ var MIME_TYPE2 = /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/i;
2559
+ function isSourceLocation(value) {
2560
+ if (!value || /\s/.test(value) || WINDOWS_DRIVE.test(value)) return false;
2561
+ try {
2562
+ const { protocol } = new URL(value);
2563
+ if (["http:", "https:", "ssh:", "git:"].includes(protocol)) return true;
2564
+ if (protocol === "nostr:") return value.startsWith("nostr://") && value.length > "nostr://".length;
2565
+ } catch {
2566
+ }
2567
+ return !value.includes("://") && SCP_LOCATION.test(value);
2568
+ }
2569
+ function isArchiveUrl(value) {
2570
+ if (!value || value.includes("#")) return false;
2571
+ try {
2572
+ const url = new URL(value);
2573
+ return url.protocol === "https:" && !url.username && !url.password;
2574
+ } catch {
2575
+ return false;
2576
+ }
2577
+ }
2578
+ function sourceArchiveFromTags(tags) {
2579
+ const archives = tags.filter((tag) => tag[0] === "source-archive");
2580
+ if (archives.length !== 1) return void 0;
2581
+ const [, url, sha2563, mimeType] = archives[0];
2582
+ if (archives[0].length !== 4 || !isArchiveUrl(url) || !HASH2.test(sha2563) || !MIME_TYPE2.test(mimeType)) {
2583
+ return void 0;
2584
+ }
2585
+ return { url, sha256: sha2563, mimeType };
2586
+ }
2587
+ function parseSourceMetadata(tags) {
2588
+ const metadata = {};
2589
+ const sources2 = tags.filter((tag) => tag[0] === "source");
2590
+ if (sources2.length === 1 && sources2[0].length === 2 && isSourceLocation(sources2[0][1])) {
2591
+ metadata.source = sources2[0][1];
2592
+ }
2593
+ const commits = tags.filter((tag) => tag[0] === "source-commit");
2594
+ if (metadata.source !== void 0 && commits.length === 1 && commits[0].length === 2 && GIT_COMMIT.test(commits[0][1])) {
2595
+ metadata.sourceCommit = commits[0][1];
2596
+ }
2597
+ const sourceArchive = sourceArchiveFromTags(tags);
2598
+ if (sourceArchive) metadata.sourceArchive = sourceArchive;
2599
+ return metadata;
2600
+ }
2601
+ var HASH3 = /^[a-f0-9]{64}$/;
2495
2602
  var DOMAIN = /^[a-z][a-z0-9-]*$/;
2496
2603
  var SLUG = /^[a-z0-9][a-z0-9-]*$/;
2497
2604
  function invalid(message2) {
@@ -2527,7 +2634,7 @@ function iconFromTags(tags) {
2527
2634
  const icons = tags.filter((tag) => tag[0] === "icon");
2528
2635
  if (icons.length !== 1) return void 0;
2529
2636
  const [, hash, mimeType] = icons[0];
2530
- if (icons[0].length !== 3 || !HASH.test(hash)) return void 0;
2637
+ if (icons[0].length !== 3 || !HASH3.test(hash)) return void 0;
2531
2638
  if (mimeType !== "image/png" && mimeType !== "image/jpeg" && mimeType !== "image/webp") {
2532
2639
  return void 0;
2533
2640
  }
@@ -2536,7 +2643,7 @@ function iconFromTags(tags) {
2536
2643
  function parseCurrentManifest(event) {
2537
2644
  const tags = event.tags;
2538
2645
  const artifactHash = single(tags, "x");
2539
- if (!artifactHash || !HASH.test(artifactHash)) invalid("invalid artifact x hash");
2646
+ if (!artifactHash || !HASH3.test(artifactHash)) invalid("invalid artifact x hash");
2540
2647
  if (typeof event.content !== "string" || !event.content.trim()) {
2541
2648
  invalid("manifest content must be a non-empty plain-text description");
2542
2649
  }
@@ -2572,7 +2679,10 @@ function parseCurrentManifest(event) {
2572
2679
  archetypes,
2573
2680
  title: single(tags, "title"),
2574
2681
  description: event.content,
2575
- source: single(tags, "source"),
2682
+ // Source and presentation media are informational: malformed or repeated
2683
+ // tags are ignored and never prevent playback (NIP-5D §Source, §Presentation media).
2684
+ ...parseSourceMetadata(tags),
2685
+ ...parsePresentationMedia(tags),
2576
2686
  icon: iconFromTags(tags),
2577
2687
  parent,
2578
2688
  root
@@ -19893,13 +20003,13 @@ function createPajaRelayBackend(getSimulation, confirmRequest, livePool = new Si
19893
20003
  if (matchesAnyFilter2(event, subscriber.filters)) subscriber.next(event);
19894
20004
  }
19895
20005
  }
19896
- async function attemptPublish(relayUrls2, event) {
20006
+ async function attemptPublish(relayUrls2, event, signerContext) {
19897
20007
  const simulation = getSimulation();
19898
20008
  const rejected2 = Object.fromEntries(relayUrls2.map((url) => [url, false]));
19899
20009
  if (simulation.relay.mode === "disabled") {
19900
20010
  return { outcomes: rejected2, error: "relay unavailable" };
19901
20011
  }
19902
- if (!await confirmRequest({ action: "publish", event })) {
20012
+ if (signerContext?.isCurrent && !signerContext.isCurrent() || !await confirmRequest({ action: "publish", event, ...signerContext ? { signerContext } : {} }) || signerContext?.isCurrent && !signerContext.isCurrent()) {
19903
20013
  return { outcomes: rejected2, error: "publish denied" };
19904
20014
  }
19905
20015
  const outcomes = simulation.relay.mode === "live" ? await publishLive(livePool, relayUrls2, event) : Object.fromEntries(relayUrls2.map((url) => [url, true]));
@@ -19941,8 +20051,8 @@ function createPajaRelayBackend(getSimulation, confirmRequest, livePool = new Si
19941
20051
  }
19942
20052
  };
19943
20053
  },
19944
- async publish(relayUrls2, event) {
19945
- const attempt = await attemptPublish(relayUrls2, event);
20054
+ async publish(relayUrls2, event, signerContext) {
20055
+ const attempt = await attemptPublish(relayUrls2, event, signerContext);
19946
20056
  if (attempt.error) throw new Error(attempt.error);
19947
20057
  },
19948
20058
  request(relayUrls2, filtersInput, context = { reason: "host" }) {
@@ -19982,8 +20092,8 @@ function createPajaRelayBackend(getSimulation, confirmRequest, livePool = new Si
19982
20092
  relayRequestObserver = observer;
19983
20093
  },
19984
20094
  query,
19985
- async publishToRelays(relayUrls2, event) {
19986
- return (await attemptPublish(relayUrls2, event)).outcomes;
20095
+ async publishToRelays(relayUrls2, event, signerContext) {
20096
+ return (await attemptPublish(relayUrls2, event, signerContext)).outcomes;
19987
20097
  },
19988
20098
  async publishWebrtcSignal(relayUrls2, event) {
19989
20099
  if (getSimulation().relay.mode !== "live" || relayUrls2.length === 0 || event.kind !== PAJA_WEBRTC_SIGNAL_KIND || !verifyEvent(event)) {
@@ -20415,7 +20525,7 @@ function createPajaRelayConfig(getSimulation) {
20415
20525
  refresh();
20416
20526
  return runtime;
20417
20527
  }
20418
- function createPajaRelayHooks(pool, getSimulation, relayConfig) {
20528
+ function createPajaRelayHooks(pool, getSimulation, relayConfig, getPublishPool = () => pool) {
20419
20529
  const cleanups = /* @__PURE__ */ new Map();
20420
20530
  const scoped = /* @__PURE__ */ new Map();
20421
20531
  function closeScopedRelay(windowId) {
@@ -20462,7 +20572,7 @@ function createPajaRelayHooks(pool, getSimulation, relayConfig) {
20462
20572
  const active = scoped.get(windowId);
20463
20573
  if (getSimulation().relay.mode !== "live" || !active || !verifyEvent(event)) return false;
20464
20574
  try {
20465
- await pool.publish([active.relayUrl], event);
20575
+ await getPublishPool(windowId).publish([active.relayUrl], event);
20466
20576
  return true;
20467
20577
  } catch {
20468
20578
  return false;
@@ -21050,7 +21160,7 @@ var BrowserWebrtcController = class {
21050
21160
  if (this.windowSessionCount(context.windowId) >= PAJA_WEBRTC_MAX_SESSIONS_PER_WINDOW) {
21051
21161
  throw new Error("session limit reached");
21052
21162
  }
21053
- const signer = this.requireSigner();
21163
+ const signer = this.requireSigner(context.windowId);
21054
21164
  const localPubkey = normalizePubkey3(await signer.getPublicKey());
21055
21165
  if (!localPubkey || localPubkey !== normalizePubkey3(this.options.getPubkey())) throw new Error("signaling unavailable");
21056
21166
  const identity = this.options.getIdentity(context.windowId);
@@ -21292,13 +21402,13 @@ var BrowserWebrtcController = class {
21292
21402
  if (!session || session.windowId !== windowId) throw new Error("session not found");
21293
21403
  return session;
21294
21404
  }
21295
- requireSigner() {
21296
- const signer = this.options.getSigner();
21405
+ requireSigner(windowId) {
21406
+ const signer = this.options.getSigner(windowId);
21297
21407
  if (!isSignalingSigner(signer)) throw new Error("signaling unavailable");
21298
21408
  return signer;
21299
21409
  }
21300
21410
  requireSessionSigner(session) {
21301
- const signer = this.requireSigner();
21411
+ const signer = this.requireSigner(session.windowId);
21302
21412
  if (normalizePubkey3(this.options.getPubkey()) !== session.localPubkey) throw new Error("signaling unavailable");
21303
21413
  return signer;
21304
21414
  }
@@ -22051,6 +22161,7 @@ function createPajaDevSigner(getSimulation, confirm, source) {
22051
22161
  getPublicKey: () => PAJA_DEV_SIGNER_PUBKEY,
22052
22162
  getRelays: () => Object.fromEntries(getPajaRelayUrls(getSimulation()).map((relay) => [relay, { read: true, write: true }])),
22053
22163
  async signEvent(event) {
22164
+ if (source?.isCurrent && !source.isCurrent()) throw new Error("Paja signing source changed");
22054
22165
  const signerContext = source ? { ...source, signerPubkey: PAJA_DEV_SIGNER_PUBKEY } : void 0;
22055
22166
  if (!await confirm({
22056
22167
  action: "sign",
@@ -22059,6 +22170,7 @@ function createPajaDevSigner(getSimulation, confirm, source) {
22059
22170
  })) {
22060
22171
  throw new Error("Paja signing request denied");
22061
22172
  }
22173
+ if (source?.isCurrent && !source.isCurrent()) throw new Error("Paja signing source changed");
22062
22174
  const template = { ...event };
22063
22175
  template.created_at ??= Math.floor(Date.now() / 1e3);
22064
22176
  template.tags ??= [];
@@ -22121,7 +22233,115 @@ function createPajaWorkerRelay(events) {
22121
22233
  };
22122
22234
  }
22123
22235
 
22124
- // src/browser-adapter.ts
22236
+ // src/browser-operation-scope.ts
22237
+ var documentId = Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, "0")).join("");
22238
+ function pajaDevelopmentConsentScope(url, windowId) {
22239
+ return `target-url:${url}|load:${documentId}:${windowId}`;
22240
+ }
22241
+ function scopePajaService(base, types, create, scopeKey) {
22242
+ const windows = /* @__PURE__ */ new Map();
22243
+ let runtime;
22244
+ let attached = true;
22245
+ return {
22246
+ ...base,
22247
+ onRegistered(context) {
22248
+ runtime = context;
22249
+ attached = true;
22250
+ base.onRegistered?.(context);
22251
+ },
22252
+ handleMessage(windowId, message2, send) {
22253
+ if (!attached) return;
22254
+ if (!types.includes(message2.type)) return base.handleMessage(windowId, message2, send);
22255
+ let entry = windows.get(windowId);
22256
+ const key = scopeKey?.(windowId);
22257
+ if (entry && entry.key !== key) {
22258
+ entry.active = false;
22259
+ entry.service.onWindowDestroyed?.(windowId);
22260
+ entry.service.onUnregistered?.();
22261
+ windows.delete(windowId);
22262
+ entry = void 0;
22263
+ }
22264
+ if (!entry) {
22265
+ const state = { active: true, key };
22266
+ const service = create(windowId, () => attached && state.active && (!runtime || runtime.listWindowIds().includes(windowId)));
22267
+ entry = Object.assign(state, { service });
22268
+ windows.set(windowId, entry);
22269
+ if (runtime) service.onRegistered?.(runtime);
22270
+ }
22271
+ entry.service.handleMessage(windowId, message2, send);
22272
+ },
22273
+ onWindowDestroyed(windowId) {
22274
+ const entry = windows.get(windowId);
22275
+ if (entry) {
22276
+ entry.active = false;
22277
+ entry.service.onWindowDestroyed?.(windowId);
22278
+ entry.service.onUnregistered?.();
22279
+ windows.delete(windowId);
22280
+ }
22281
+ base.onWindowDestroyed?.(windowId);
22282
+ },
22283
+ onCapabilityRevoked(windowId, capability) {
22284
+ const entry = windows.get(windowId);
22285
+ if (entry) {
22286
+ entry.active = false;
22287
+ entry.service.onCapabilityRevoked?.(windowId, capability);
22288
+ entry.service.onWindowDestroyed?.(windowId);
22289
+ entry.service.onUnregistered?.();
22290
+ windows.delete(windowId);
22291
+ }
22292
+ base.onCapabilityRevoked?.(windowId, capability);
22293
+ },
22294
+ onUnregistered() {
22295
+ attached = false;
22296
+ for (const [windowId, entry] of windows) {
22297
+ entry.active = false;
22298
+ entry.service.onWindowDestroyed?.(windowId);
22299
+ entry.service.onUnregistered?.();
22300
+ }
22301
+ windows.clear();
22302
+ base.onUnregistered?.();
22303
+ }
22304
+ };
22305
+ }
22306
+ function scopePajaRelayBackend(base, context) {
22307
+ const current = async () => {
22308
+ const value = await context();
22309
+ if (value?.isCurrent && !value.isCurrent()) throw new Error("Paja publication source changed");
22310
+ return value;
22311
+ };
22312
+ return {
22313
+ ...base,
22314
+ async publish(relays, event) {
22315
+ return base.publish(relays, event, await current());
22316
+ },
22317
+ async publishToRelays(relays, event) {
22318
+ return base.publishToRelays(relays, event, await current());
22319
+ }
22320
+ };
22321
+ }
22322
+ function createPajaWindowScope(options) {
22323
+ const account = options.getPubkey();
22324
+ const source = {
22325
+ ...options.source,
22326
+ isCurrent: () => options.isCurrent() && account === options.getPubkey() && (!options.source.isCurrent || options.source.isCurrent())
22327
+ };
22328
+ const getSigner = () => options.getSigner(source);
22329
+ return {
22330
+ source,
22331
+ getSigner,
22332
+ backend: scopePajaRelayBackend(options.backend, async () => {
22333
+ if (!source.isCurrent?.()) throw new Error("Paja publication source changed");
22334
+ const signerPubkey = await getSigner()?.getPublicKey?.();
22335
+ if (!signerPubkey || !account) return {
22336
+ ...source,
22337
+ signerPubkey: "host-generated",
22338
+ runtimeScope: `${source.runtimeScope}|host-session:${documentId}`
22339
+ };
22340
+ if (signerPubkey.toLowerCase() !== account.toLowerCase()) throw new Error("Paja signer account changed");
22341
+ return { ...source, signerPubkey };
22342
+ })
22343
+ };
22344
+ }
22125
22345
  function createPajaCvmRelayPool(backend) {
22126
22346
  return {
22127
22347
  subscribe(relays, filter, params) {
@@ -22141,7 +22361,29 @@ function createPajaCvmRelayPool(backend) {
22141
22361
  }
22142
22362
  };
22143
22363
  }
22144
- function createOutboxRouter(backend, getSimulation, relayConfig, confirmRequest, signerProvider) {
22364
+ function getRuntimePubkey(getSimulation, signerProvider) {
22365
+ return signerProvider?.getPubkey() || (signerProvider?.getMethod() === "dev" ? PAJA_DEV_SIGNER_PUBKEY : "") || getSimulation().identity.pubkey;
22366
+ }
22367
+ function createRuntimeSigner(getSimulation, confirmRequest, signerProvider, source) {
22368
+ const signer = signerProvider?.getSigner(source);
22369
+ if (!signer) {
22370
+ if (signerProvider?.getMethod() === "dev") {
22371
+ return createPajaDevSigner(getSimulation, confirmRequest, source);
22372
+ }
22373
+ const fixedPubkey = getSimulation().identity.pubkey;
22374
+ if (fixedPubkey) {
22375
+ return {
22376
+ getPublicKey: () => fixedPubkey,
22377
+ getRelays: () => Object.fromEntries(getPajaRelayUrls(getSimulation()).map((relay) => [relay, { read: true, write: true }]))
22378
+ };
22379
+ }
22380
+ return null;
22381
+ }
22382
+ return signer;
22383
+ }
22384
+
22385
+ // src/browser-adapter.ts
22386
+ function createOutboxRouter(backend, getSimulation, relayConfig, confirmRequest, signerProvider, source) {
22145
22387
  return createRelayPoolOutboxRouter({
22146
22388
  relayPool: createPajaOutboxRelayPool(backend),
22147
22389
  loadRelayLists: createPajaRelayListLoader(
@@ -22152,7 +22394,7 @@ function createOutboxRouter(backend, getSimulation, relayConfig, confirmRequest,
22152
22394
  ),
22153
22395
  fallbackRelays: relayConfig.outboxRelays,
22154
22396
  signEvent: async (template) => {
22155
- const signer = createRuntimeSigner(getSimulation, confirmRequest, signerProvider);
22397
+ const signer = createRuntimeSigner(getSimulation, confirmRequest, signerProvider, source);
22156
22398
  if (!signer?.signEvent) throw new Error("no signer configured");
22157
22399
  const event = { ...template };
22158
22400
  event.created_at ??= Math.floor(Date.now() / 1e3);
@@ -22176,27 +22418,23 @@ function createDevTheme(mode, values) {
22176
22418
  }
22177
22419
  };
22178
22420
  }
22179
- function getRuntimePubkey(getSimulation, signerProvider) {
22180
- return signerProvider?.getPubkey() || (signerProvider?.getMethod() === "dev" ? PAJA_DEV_SIGNER_PUBKEY : "") || getSimulation().identity.pubkey;
22181
- }
22182
- function createRuntimeSigner(getSimulation, confirmRequest, signerProvider, source) {
22183
- const signer = signerProvider?.getSigner(source);
22184
- if (!signer) {
22185
- if (signerProvider?.getMethod() === "dev") {
22186
- return createPajaDevSigner(getSimulation, confirmRequest, source);
22187
- }
22188
- const fixedPubkey = getSimulation().identity.pubkey;
22189
- if (fixedPubkey) {
22190
- return {
22191
- getPublicKey: () => fixedPubkey,
22192
- getRelays: () => Object.fromEntries(getPajaRelayUrls(getSimulation()).map((relay) => [relay, { read: true, write: true }]))
22193
- };
22194
- }
22195
- return null;
22196
- }
22197
- return signer;
22198
- }
22199
- function createDevServices(backend, getSimulation, relayConfig, onThemeService, onThemeBroadcast, confirmRequest, getConfiguredBlossomServers, uploadRuntime, signerProvider, getIdentity, userActivation, notifyOptions, configOptions) {
22421
+ function createDevServices(backend, getSimulation, relayConfig, onThemeService, onThemeBroadcast, confirmRequest, getConfiguredBlossomServers, uploadRuntime, signerProvider, getIdentity, userActivation, notifyOptions, configOptions, getSignerSource) {
22422
+ const scopeFor = (windowId, isCurrent) => createPajaWindowScope({
22423
+ backend,
22424
+ source: getSignerSource?.(windowId) ?? {
22425
+ windowId,
22426
+ napplet: getIdentity?.(windowId) ?? { dTag: "dev-target", aggregateHash: "paja" },
22427
+ runtimeScope: `window:${windowId}`
22428
+ },
22429
+ isCurrent,
22430
+ getPubkey: () => getRuntimePubkey(getSimulation, signerProvider),
22431
+ getSigner: (source) => createRuntimeSigner(getSimulation, confirmRequest, signerProvider, source)
22432
+ });
22433
+ const scopeKey = (windowId) => JSON.stringify([
22434
+ getSignerSource?.(windowId).runtimeScope,
22435
+ getIdentity?.(windowId).aggregateHash,
22436
+ getRuntimePubkey(getSimulation, signerProvider)
22437
+ ]);
22200
22438
  const theme = createThemeService({
22201
22439
  initialTheme: createDevTheme(getSimulation().theme.mode, getSimulation().theme.values),
22202
22440
  onBroadcast: onThemeBroadcast
@@ -22253,7 +22491,7 @@ function createDevServices(backend, getSimulation, relayConfig, onThemeService,
22253
22491
  services.keys = createKeysService({ listenerTarget: document });
22254
22492
  }
22255
22493
  if (getSimulation().relay.mode === "live") {
22256
- services.relay = createRelayPoolService({
22494
+ const relayOptions = {
22257
22495
  subscribe: (filters, callback, relayUrls2, fromHint) => backend.subscription(
22258
22496
  (relayUrls2 ?? getReadRelays()).filter((url) => isPajaRelayAllowed(url, getAllRelays)),
22259
22497
  filters,
@@ -22266,11 +22504,19 @@ function createDevServices(backend, getSimulation, relayConfig, onThemeService,
22266
22504
  );
22267
22505
  }
22268
22506
  }),
22269
- publish: (event) => backend.publish(getWriteRelays(), event),
22270
22507
  selectRelayTier: getReadRelays,
22271
22508
  isAvailable: () => backend.isAvailable()
22272
- });
22273
- services.outbox = createOutboxService({
22509
+ };
22510
+ services.relay = scopePajaService(
22511
+ createRelayPoolService({ ...relayOptions, publish: (event) => backend.publish(getWriteRelays(), event) }),
22512
+ ["relay.publish", "relay.publishEncrypted"],
22513
+ (windowId, isCurrent) => {
22514
+ const scope = scopeFor(windowId, isCurrent);
22515
+ return createRelayPoolService({ ...relayOptions, publish: (event) => scope.backend.publish(getWriteRelays(), event) });
22516
+ },
22517
+ scopeKey
22518
+ );
22519
+ const outboxOptions = {
22274
22520
  router: baseOutboxRouter,
22275
22521
  getReadRouter: (windowId) => blossomEventResolver.decorate(baseOutboxRouter, windowId),
22276
22522
  getQueryRouter: (windowId, context) => blossomEventResolver.decorate(
@@ -22280,7 +22526,14 @@ function createDevServices(backend, getSimulation, relayConfig, onThemeService,
22280
22526
  ),
22281
22527
  windowId
22282
22528
  )
22283
- });
22529
+ };
22530
+ services.outbox = scopePajaService(createOutboxService(outboxOptions), ["outbox.publish"], (windowId, isCurrent) => {
22531
+ const scope = scopeFor(windowId, isCurrent);
22532
+ return createOutboxService({
22533
+ ...outboxOptions,
22534
+ router: createOutboxRouter(scope.backend, getSimulation, relayConfig, confirmRequest, signerProvider, scope.source)
22535
+ });
22536
+ }, scopeKey);
22284
22537
  }
22285
22538
  if (getSimulation().capabilities.domains.count && getSimulation().relay.mode === "live") {
22286
22539
  services.count = createCountService({
@@ -22322,13 +22575,17 @@ function createDevServices(backend, getSimulation, relayConfig, onThemeService,
22322
22575
  if (getSimulation().capabilities.domains.theme) services.theme = theme.handler;
22323
22576
  if (getSimulation().capabilities.domains.config && config) services.config = config.handler;
22324
22577
  if (getSimulation().cvm.enabled && getSimulation().relay.mode === "live" && backend.isAvailable()) {
22325
- services.cvm = createCvmService({
22326
- transport: createNostrCvmTransport({
22327
- defaultRelays: relayConfig.allRelays,
22328
- pool: createPajaCvmRelayPool(backend),
22329
- clientInfo: { name: "@kehto/paja", version: "0.11.0" }
22330
- })
22331
- });
22578
+ const cvm = (relay) => {
22579
+ const service = createCvmService({
22580
+ transport: createNostrCvmTransport({
22581
+ defaultRelays: relayConfig.allRelays,
22582
+ pool: createPajaCvmRelayPool(relay),
22583
+ clientInfo: { name: "@kehto/paja", version: "0.11.0" }
22584
+ })
22585
+ });
22586
+ return { ...service, onUnregistered: () => service.dispose() };
22587
+ };
22588
+ services.cvm = scopePajaService(cvm(backend), ["cvm.request", "cvm.close"], (windowId, isCurrent) => cvm(scopeFor(windowId, isCurrent).backend), scopeKey);
22332
22589
  }
22333
22590
  if (uploadRuntime) {
22334
22591
  services.upload = createUploadService({
@@ -22340,33 +22597,46 @@ function createDevServices(backend, getSimulation, relayConfig, onThemeService,
22340
22597
  services.link = createLinkService({
22341
22598
  open: async ({ windowId, url, options }) => {
22342
22599
  const napplet = getIdentity?.(windowId) ?? { dTag: "dev-target", aggregateHash: "paja" };
22343
- const allowed2 = await confirmRequest({
22600
+ const request = {
22344
22601
  action: "link",
22345
22602
  windowId,
22346
22603
  napplet,
22347
22604
  url: url.href,
22348
- ...options?.label ? { label: options.label } : {}
22349
- });
22350
- return { status: allowed2 && openPajaExternalLink(url) ? "opened" : "denied" };
22605
+ ...options?.label ? { label: options.label } : {},
22606
+ isCurrent: () => (!("isCurrent" in napplet) || typeof napplet.isCurrent !== "function" || napplet.isCurrent()) && (getIdentity?.(windowId).aggregateHash ?? napplet.aggregateHash) === napplet.aggregateHash
22607
+ };
22608
+ const open = () => request.isCurrent?.() !== false && openPajaExternalLink(url);
22609
+ try {
22610
+ const opened = userActivation ? await userActivation.run(request, open) : await confirmRequest(request) && open();
22611
+ return { status: opened ? "opened" : "denied" };
22612
+ } catch {
22613
+ return { status: "denied" };
22614
+ }
22351
22615
  }
22352
22616
  });
22353
22617
  }
22354
22618
  if (getSimulation().capabilities.domains.common && getSimulation().relay.mode === "live") {
22355
- services.common = createCommonService({
22619
+ services.common = scopePajaService(createCommonService({
22356
22620
  getProfile: (target) => commonBackend.getProfile(target),
22357
22621
  follows: () => commonBackend.follows(),
22358
22622
  follow: (pubkeys) => commonBackend.follow(pubkeys),
22359
22623
  unfollow: (pubkeys) => commonBackend.unfollow(pubkeys),
22360
22624
  react: (targetEventId, reaction, customEmojiHref) => commonBackend.react(targetEventId, reaction, customEmojiHref),
22361
22625
  report: (target, reason, text) => commonBackend.report(target, reason, text)
22362
- });
22626
+ }), ["common.follow", "common.unfollow", "common.react", "common.report"], (windowId, isCurrent) => {
22627
+ const scope = scopeFor(windowId, isCurrent);
22628
+ return createCommonService(createPajaCommonBackend({ relay: scope.backend, getRelays: getAllRelays, getSigner: scope.getSigner }));
22629
+ }, scopeKey);
22363
22630
  }
22364
22631
  if (getSimulation().capabilities.domains.lists && getSimulation().relay.mode === "live") {
22365
- services.lists = createListsService({
22632
+ services.lists = scopePajaService(createListsService({
22366
22633
  supported: () => listsBackend.supported(),
22367
22634
  add: (list, items, options) => listsBackend.add(list, items, options),
22368
22635
  remove: (list, items, options) => listsBackend.remove(list, items, options)
22369
- });
22636
+ }), ["lists.add", "lists.remove"], (windowId, isCurrent) => {
22637
+ const scope = scopeFor(windowId, isCurrent);
22638
+ return createListsService(createPajaListsBackend({ relay: scope.backend, getRelays: getAllRelays, getSigner: scope.getSigner }));
22639
+ }, scopeKey);
22370
22640
  }
22371
22641
  if (getSimulation().capabilities.domains.serial) {
22372
22642
  const controller = userActivation ? createBrowserSerialController(userActivation) : null;
@@ -22386,7 +22656,7 @@ function createDevServices(backend, getSimulation, relayConfig, onThemeService,
22386
22656
  },
22387
22657
  publish: (event) => backend.publishWebrtcSignal(getAllRelays(), event)
22388
22658
  },
22389
- getSigner: () => createRuntimeSigner(getSimulation, confirmRequest, signerProvider),
22659
+ getSigner: (windowId) => createRuntimeSigner(getSimulation, confirmRequest, signerProvider, windowId ? getSignerSource?.(windowId) : void 0),
22390
22660
  getPubkey: () => getRuntimePubkey(getSimulation, signerProvider),
22391
22661
  getIdentity: getIdentity ?? (() => ({ dTag: "dev-target", aggregateHash: "paja" })),
22392
22662
  confirm: confirmRequest
@@ -22429,10 +22699,16 @@ function createPajaAdapter(config, getSimulation, onThemeService, onThemeBroadca
22429
22699
  };
22430
22700
  const signerSource = (windowId) => {
22431
22701
  const napplet = resolveIdentity(windowId);
22702
+ const account = getRuntimePubkey(getSimulation, signerProvider);
22703
+ const runtimeScope = "consentScope" in napplet && typeof napplet.consentScope === "string" ? napplet.consentScope : config.target?.mode === "iframe-url" ? pajaDevelopmentConsentScope(config.target.url, windowId) : `artifact:${napplet.aggregateHash}`;
22432
22704
  return {
22433
22705
  windowId,
22434
22706
  napplet,
22435
- runtimeScope: config.target?.mode === "iframe-url" ? `target-url:${config.target.url}` : `artifact:${napplet.aggregateHash}`
22707
+ runtimeScope,
22708
+ isCurrent: () => {
22709
+ const current = resolveIdentity(windowId);
22710
+ 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);
22711
+ }
22436
22712
  };
22437
22713
  };
22438
22714
  const relayBackend = createPajaRelayBackend(getSimulation, confirmRequest);
@@ -22467,7 +22743,8 @@ function createPajaAdapter(config, getSimulation, onThemeService, onThemeBroadca
22467
22743
  resolveIdentity,
22468
22744
  userActivation,
22469
22745
  notifyOptions,
22470
- configOptions
22746
+ configOptions,
22747
+ signerSource
22471
22748
  );
22472
22749
  const services = serviceBundle.services;
22473
22750
  const ready = createPajaBrowserFsBackend({
@@ -22491,7 +22768,13 @@ function createPajaAdapter(config, getSimulation, onThemeService, onThemeBroadca
22491
22768
  notifyIntentChanged: () => {
22492
22769
  },
22493
22770
  setWindowBlossomServers: serviceBundle.setWindowBlossomServers,
22494
- relayPool: createPajaRelayHooks(relayBackend, getSimulation, relayConfig),
22771
+ relayPool: createPajaRelayHooks(relayBackend, getSimulation, relayConfig, (windowId) => createPajaWindowScope({
22772
+ backend: relayBackend,
22773
+ source: signerSource(windowId),
22774
+ isCurrent: () => true,
22775
+ getPubkey: () => getRuntimePubkey(getSimulation, signerProvider),
22776
+ getSigner: (source) => createRuntimeSigner(getSimulation, confirmRequest, signerProvider, source)
22777
+ }).backend),
22495
22778
  relayConfig,
22496
22779
  windowManager: { createWindow: () => null },
22497
22780
  auth: {
@@ -23097,7 +23380,14 @@ function redactPajaMessageForLog(message2) {
23097
23380
  function isRecord7(value) {
23098
23381
  return typeof value === "object" && value !== null && !Array.isArray(value);
23099
23382
  }
23100
- function installPajaOriginRegistryProxy(originRegistry2, stateRef) {
23383
+ function installPajaOriginRegistryProxy(originRegistry2, stateRef, onWindowRemoved) {
23384
+ if (onWindowRemoved && originRegistry2.unregister) {
23385
+ const unregister = originRegistry2.unregister.bind(originRegistry2);
23386
+ originRegistry2.unregister = (windowId) => {
23387
+ onWindowRemoved(windowId);
23388
+ unregister(windowId);
23389
+ };
23390
+ }
23101
23391
  const originalGetIframeWindow = originRegistry2.getIframeWindow.bind(originRegistry2);
23102
23392
  originRegistry2.getIframeWindow = (windowId) => {
23103
23393
  const win = originalGetIframeWindow(windowId);
@@ -23231,8 +23521,8 @@ function renderSignerStatus(state, signerPubkey) {
23231
23521
  const methodLabel = state.signer.method === "nip07" ? "NIP-07" : state.signer.method === "nip46" ? "bunker" : state.signer.method === "dev" ? "dev" : "none";
23232
23522
  const relay = state.signer.relay ? ` \xB7 relay ${state.signer.relay}` : "";
23233
23523
  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}`;
23234
- const consentSummary = state.signerConsentCount === 0 ? "signing asks every time" : `${state.signerConsentCount} remembered signing approval${state.signerConsentCount === 1 ? "" : "s"}`;
23235
- el.textContent = `${prefix} \xB7 ${consentSummary} \xB7 publishing asks every time`;
23524
+ const consentSummary = state.signerConsentCount === 0 ? "signing and publishing ask every time" : `${state.signerConsentCount} remembered signing/publishing approval${state.signerConsentCount === 1 ? "" : "s"}`;
23525
+ el.textContent = `${prefix} \xB7 ${consentSummary}`;
23236
23526
  clearConsent.hidden = state.signerConsentCount === 0;
23237
23527
  clearConsent.textContent = `Forget ${state.signerConsentCount} remembered approval${state.signerConsentCount === 1 ? "" : "s"}`;
23238
23528
  clearConsent.onclick = () => state.clearSignerConsent();
@@ -23460,6 +23750,7 @@ function createConfirmedSigner(signer, confirmRequest, source) {
23460
23750
  return {
23461
23751
  ...signer,
23462
23752
  async signEvent(event) {
23753
+ if (source?.isCurrent && !source.isCurrent()) throw new Error("Paja signing source changed");
23463
23754
  if (typeof signer.signEvent !== "function") {
23464
23755
  throw new Error("Signer does not support event signing");
23465
23756
  }
@@ -23471,6 +23762,7 @@ function createConfirmedSigner(signer, confirmRequest, source) {
23471
23762
  })) {
23472
23763
  throw new Error("Paja signing request denied");
23473
23764
  }
23765
+ if (source?.isCurrent && !source.isCurrent()) throw new Error("Paja signing source changed");
23474
23766
  return signer.signEvent(event);
23475
23767
  }
23476
23768
  };
@@ -23592,6 +23884,7 @@ var PAJA_SIGNER_CONSENT_VERSION = 1;
23592
23884
  var MAX_CONSENT_SUBJECTS = 128;
23593
23885
  var MAX_KINDS_PER_SUBJECT = 128;
23594
23886
  var MAX_IDENTITY_FIELD_LENGTH = 512;
23887
+ var warnedLegacyConsent = false;
23595
23888
  function createPajaSignerConsentStore(storage = readPajaSignerConsentStorage()) {
23596
23889
  let grants = readConsentDocument(storage).grants;
23597
23890
  const persist = () => {
@@ -23616,38 +23909,60 @@ function createPajaSignerConsentStore(storage = readPajaSignerConsentStorage())
23616
23909
  const existing = grants.find((grant2) => sameSubject(grant2, subject));
23617
23910
  if (existing) return existing;
23618
23911
  if (grants.length >= MAX_CONSENT_SUBJECTS) return null;
23619
- const created = { ...subject, trusted: false, kinds: [] };
23912
+ const created = { ...subject, trusted: false, kinds: [], publishTrusted: false, publishKinds: [] };
23620
23913
  grants = [...grants, created];
23621
23914
  return created;
23622
23915
  };
23623
23916
  return {
23624
- match(context, kind) {
23917
+ match(context, kind, action = "sign") {
23918
+ if (context.isCurrent && !context.isCurrent()) return null;
23625
23919
  const normalizedKind = normalizeKind(kind);
23626
23920
  if (normalizedKind === null) return null;
23627
23921
  const record2 = recordFor(context);
23628
23922
  if (!record2) return null;
23629
- if (record2.trusted) return "napplet";
23630
- return record2.kinds.includes(normalizedKind) ? "kind" : null;
23923
+ const trusted = action === "sign" ? record2.trusted : record2.publishTrusted;
23924
+ const kinds = action === "sign" ? record2.kinds : record2.publishKinds;
23925
+ if (trusted) return "napplet";
23926
+ return kinds.includes(normalizedKind) ? "kind" : null;
23631
23927
  },
23632
- rememberKind(context, kind) {
23928
+ rememberKind(context, kind, action = "sign") {
23929
+ if (context.isCurrent && !context.isCurrent()) return false;
23633
23930
  const normalizedKind = normalizeKind(kind);
23634
23931
  if (normalizedKind === null) return false;
23635
23932
  const record2 = ensureRecord(context);
23636
23933
  if (!record2) return false;
23637
- if (record2.trusted || record2.kinds.includes(normalizedKind)) return true;
23638
- if (record2.kinds.length >= MAX_KINDS_PER_SUBJECT) return false;
23639
- record2.kinds = [...record2.kinds, normalizedKind].sort((left, right) => left - right);
23934
+ const kinds = action === "sign" ? record2.kinds : record2.publishKinds;
23935
+ if ((action === "sign" ? record2.trusted : record2.publishTrusted) || kinds.includes(normalizedKind)) return true;
23936
+ if (kinds.length >= MAX_KINDS_PER_SUBJECT) return false;
23937
+ const next = [...kinds, normalizedKind].sort((left, right) => left - right);
23938
+ if (action === "sign") record2.kinds = next;
23939
+ else record2.publishKinds = next;
23640
23940
  persist();
23641
23941
  return true;
23642
23942
  },
23643
- trustNapplet(context) {
23943
+ trustNapplet(context, action = "sign") {
23944
+ if (context.isCurrent && !context.isCurrent()) return false;
23644
23945
  const record2 = ensureRecord(context);
23645
23946
  if (!record2) return false;
23646
- if (!record2.trusted || record2.kinds.length > 0) {
23947
+ if (action === "sign") {
23647
23948
  record2.trusted = true;
23648
23949
  record2.kinds = [];
23649
- persist();
23950
+ } else {
23951
+ record2.publishTrusted = true;
23952
+ record2.publishKinds = [];
23650
23953
  }
23954
+ persist();
23955
+ return true;
23956
+ },
23957
+ trustVersion(context) {
23958
+ if (context.isCurrent && !context.isCurrent()) return false;
23959
+ const record2 = ensureRecord(context);
23960
+ if (!record2) return false;
23961
+ record2.trusted = true;
23962
+ record2.kinds = [];
23963
+ record2.publishTrusted = true;
23964
+ record2.publishKinds = [];
23965
+ persist();
23651
23966
  return true;
23652
23967
  },
23653
23968
  clear() {
@@ -23672,7 +23987,7 @@ function createPajaSignerConsentStore(storage = readPajaSignerConsentStorage())
23672
23987
  }
23673
23988
  },
23674
23989
  count() {
23675
- return grants.reduce((total, grant2) => total + (grant2.trusted ? 1 : grant2.kinds.length), 0);
23990
+ return grants.reduce((total, grant2) => total + (grant2.trusted ? 1 : grant2.kinds.length) + (grant2.publishTrusted ? 1 : grant2.publishKinds.length), 0);
23676
23991
  }
23677
23992
  };
23678
23993
  }
@@ -23699,6 +24014,10 @@ function readConsentDocument(storage) {
23699
24014
  for (const candidate of parsed.grants.slice(0, MAX_CONSENT_SUBJECTS)) {
23700
24015
  const record2 = normalizeRecord(candidate);
23701
24016
  if (!record2 || grants.some((existing) => sameSubject(existing, record2))) continue;
24017
+ if (!warnedLegacyConsent && candidate && typeof candidate === "object" && !("publishTrusted" in candidate) && !("publishKinds" in candidate)) {
24018
+ warnedLegacyConsent = true;
24019
+ 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.");
24020
+ }
23702
24021
  grants.push(record2);
23703
24022
  }
23704
24023
  return { version: PAJA_SIGNER_CONSENT_VERSION, grants };
@@ -23720,7 +24039,10 @@ function normalizeRecord(value) {
23720
24039
  return {
23721
24040
  ...subject,
23722
24041
  trusted: candidate.trusted,
23723
- kinds: candidate.trusted ? [] : kinds
24042
+ kinds: candidate.trusted ? [] : kinds,
24043
+ // Old records are signing-only; their omission never grants publication.
24044
+ publishTrusted: candidate.publishTrusted === true,
24045
+ publishKinds: candidate.publishTrusted === true ? [] : Array.isArray(candidate.publishKinds) ? [...new Set(candidate.publishKinds.map(normalizeKind).filter((kind) => kind !== null))].slice(0, MAX_KINDS_PER_SUBJECT) : []
23724
24046
  };
23725
24047
  }
23726
24048
  function normalizeContext(context) {
@@ -23732,8 +24054,9 @@ function normalizeContext(context) {
23732
24054
  );
23733
24055
  }
23734
24056
  function normalizeSubject(signerPubkey, dTag, aggregateHash, runtimeScope) {
23735
- if (typeof signerPubkey !== "string" || !/^[0-9a-f]{64}$/i.test(signerPubkey)) return null;
23736
- if (!validIdentityField(dTag) || !validIdentityField(aggregateHash) || !validIdentityField(runtimeScope)) return null;
24057
+ const hostGenerated = signerPubkey === "host-generated" && typeof runtimeScope === "string" && /\|host-session:[a-f0-9]{32}$/.test(runtimeScope);
24058
+ if (typeof signerPubkey !== "string" || !/^[0-9a-f]{64}$/i.test(signerPubkey) && !hostGenerated) return null;
24059
+ if (typeof dTag !== "string" || dTag.length > MAX_IDENTITY_FIELD_LENGTH || !validIdentityField(aggregateHash) || !validIdentityField(runtimeScope)) return null;
23737
24060
  return {
23738
24061
  signerPubkey: signerPubkey.toLowerCase(),
23739
24062
  dTag,
@@ -23758,52 +24081,53 @@ function confirmationDetails(...lines) {
23758
24081
  function confirmationCopy(title, summary, approveLabel, ...details) {
23759
24082
  return { title, summary, details: confirmationDetails(...details), approveLabel };
23760
24083
  }
23761
- function createPajaConfirmationController(getState, options = {}) {
23762
- const dialog = document.getElementById("paja-confirmation-dialog");
23763
- const title = document.getElementById("paja-confirmation-title");
23764
- const summary = document.getElementById("paja-confirmation-summary");
23765
- const details = document.getElementById("paja-confirmation-details");
23766
- const approve = document.getElementById("paja-confirmation-approve");
23767
- const deny = document.getElementById("paja-confirmation-deny");
24084
+ function createSignerConsentChoices(consentStore, reportSignerConsentChange) {
23768
24085
  const signerConsent = document.getElementById("paja-signer-consent");
23769
24086
  const signerConsentOnce = document.getElementById("paja-signer-consent-once");
23770
24087
  const signerConsentKind = document.getElementById("paja-signer-consent-kind");
23771
24088
  const signerConsentNapplet = document.getElementById("paja-signer-consent-napplet");
24089
+ const signerConsentVersion = document.getElementById("paja-signer-consent-version");
23772
24090
  const signerConsentKindValue = document.getElementById("paja-signer-consent-kind-value");
23773
24091
  const signerConsentNappletValue = document.getElementById("paja-signer-consent-napplet-value");
23774
- const ready = dialog instanceof HTMLDialogElement && title instanceof HTMLElement && summary instanceof HTMLElement && details instanceof HTMLElement && approve instanceof HTMLButtonElement && deny instanceof HTMLButtonElement;
23775
24092
  const signerConsentReady = signerConsent instanceof HTMLFieldSetElement && signerConsentOnce instanceof HTMLInputElement && signerConsentKind instanceof HTMLInputElement && signerConsentNapplet instanceof HTMLInputElement && signerConsentKindValue instanceof HTMLElement && signerConsentNappletValue instanceof HTMLElement;
23776
- const consentStore = createPajaSignerConsentStore(
23777
- options.storage === void 0 ? void 0 : options.storage
23778
- );
23779
- const queue = [];
23780
- let active = null;
23781
- let previousFocus = null;
23782
- let disposed = false;
23783
- const reportSignerConsentChange = () => {
23784
- options.onSignerConsentChange?.(consentStore.count());
23785
- };
23786
24093
  const configureSignerConsent = (request) => {
23787
24094
  if (!signerConsentReady) return;
23788
24095
  signerConsent.hidden = true;
23789
24096
  signerConsentOnce.checked = true;
23790
24097
  signerConsentKind.checked = false;
23791
24098
  signerConsentNapplet.checked = false;
24099
+ if (signerConsentVersion instanceof HTMLInputElement) signerConsentVersion.checked = false;
23792
24100
  const candidate = signerConsentCandidate(request);
23793
24101
  if (!candidate) return;
23794
24102
  signerConsent.hidden = false;
23795
24103
  signerConsentKindValue.textContent = String(candidate.kind);
23796
- signerConsentNappletValue.textContent = candidate.context.napplet.dTag;
24104
+ signerConsentNappletValue.textContent = candidate.context.napplet.dTag || "Root napplet";
24105
+ const verb = request.action === "publish" ? "Publish" : "Sign";
24106
+ for (const [id, text] of [
24107
+ ["paja-signer-consent-legend", `Remember this ${request.action === "publish" ? "publishing" : "signing"} choice`],
24108
+ ["paja-signer-consent-once-label", `${verb} this event only`],
24109
+ ["paja-signer-consent-kind-verb", `Always ${verb.toLowerCase()} kind`],
24110
+ ["paja-signer-consent-napplet-verb", `Allow all ${request.action === "publish" ? "publishing" : "signing"} from`],
24111
+ ["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.`]
24112
+ ]) {
24113
+ const element2 = document.getElementById(id);
24114
+ if (element2) element2.textContent = text;
24115
+ }
23797
24116
  };
23798
24117
  const rememberSignerChoice = (request) => {
23799
24118
  if (!signerConsentReady) return "once";
23800
24119
  const candidate = signerConsentCandidate(request);
23801
24120
  if (!candidate) return "once";
23802
- if (signerConsentNapplet.checked && consentStore.trustNapplet(candidate.context)) {
24121
+ if (signerConsentVersion instanceof HTMLInputElement && signerConsentVersion.checked && consentStore.trustVersion(candidate.context)) {
24122
+ reportSignerConsentChange();
24123
+ return "trust-version";
24124
+ }
24125
+ const action = request.action === "publish" ? "publish" : "sign";
24126
+ if (signerConsentNapplet.checked && consentStore.trustNapplet(candidate.context, action)) {
23803
24127
  reportSignerConsentChange();
23804
24128
  return "trust-napplet";
23805
24129
  }
23806
- if (signerConsentKind.checked && consentStore.rememberKind(candidate.context, candidate.kind)) {
24130
+ if (signerConsentKind.checked && consentStore.rememberKind(candidate.context, candidate.kind, action)) {
23807
24131
  reportSignerConsentChange();
23808
24132
  return "remember-kind";
23809
24133
  }
@@ -23811,14 +24135,40 @@ function createPajaConfirmationController(getState, options = {}) {
23811
24135
  };
23812
24136
  const rememberedSignerChoice = (request) => {
23813
24137
  const candidate = signerConsentCandidate(request);
23814
- return candidate ? consentStore.match(candidate.context, candidate.kind) : null;
24138
+ return candidate ? consentStore.match(candidate.context, candidate.kind, request.action === "publish" ? "publish" : "sign") : null;
23815
24139
  };
24140
+ return { configure: configureSignerConsent, remember: rememberSignerChoice, match: rememberedSignerChoice };
24141
+ }
24142
+ function createPajaConfirmationController(getState, options = {}) {
24143
+ const dialog = document.getElementById("paja-confirmation-dialog");
24144
+ const title = document.getElementById("paja-confirmation-title");
24145
+ const summary = document.getElementById("paja-confirmation-summary");
24146
+ const details = document.getElementById("paja-confirmation-details");
24147
+ const approve = document.getElementById("paja-confirmation-approve");
24148
+ const deny = document.getElementById("paja-confirmation-deny");
24149
+ const ready = dialog instanceof HTMLDialogElement && title instanceof HTMLElement && summary instanceof HTMLElement && details instanceof HTMLElement && approve instanceof HTMLButtonElement && deny instanceof HTMLButtonElement;
24150
+ const consentStore = createPajaSignerConsentStore(
24151
+ options.storage === void 0 ? void 0 : options.storage
24152
+ );
24153
+ const queue = [];
24154
+ let active = null;
24155
+ let previousFocus = null;
24156
+ let disposed = false;
24157
+ const reportSignerConsentChange = () => {
24158
+ options.onSignerConsentChange?.(consentStore.count());
24159
+ };
24160
+ const choices = createSignerConsentChoices(consentStore, reportSignerConsentChange);
23816
24161
  const pump = () => {
23817
24162
  if (!ready || disposed || active) return;
23818
24163
  while (!active && queue.length > 0) {
23819
24164
  const candidate = queue.shift() ?? null;
23820
24165
  if (!candidate) break;
23821
- const remembered = rememberedSignerChoice(candidate.request);
24166
+ if (!isRequestCurrent(candidate.request)) {
24167
+ recordPajaConfirmation(getState(), candidate.request, false);
24168
+ candidate.deny();
24169
+ continue;
24170
+ }
24171
+ const remembered = choices.match(candidate.request);
23822
24172
  if (!remembered) {
23823
24173
  active = candidate;
23824
24174
  break;
@@ -23837,7 +24187,7 @@ function createPajaConfirmationController(getState, options = {}) {
23837
24187
  summary.textContent = copy.summary;
23838
24188
  details.textContent = copy.details;
23839
24189
  approve.textContent = copy.approveLabel;
23840
- configureSignerConsent(active.request);
24190
+ choices.configure(active.request);
23841
24191
  previousFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
23842
24192
  dialog.showModal();
23843
24193
  deny.focus();
@@ -23845,9 +24195,10 @@ function createPajaConfirmationController(getState, options = {}) {
23845
24195
  const settle6 = (allowed2) => {
23846
24196
  const current = active;
23847
24197
  if (!current) return;
24198
+ allowed2 = allowed2 && isRequestCurrent(current.request);
23848
24199
  active = null;
23849
24200
  if (ready && dialog.open) dialog.close();
23850
- const approvalMode = allowed2 ? rememberSignerChoice(current.request) : void 0;
24201
+ const approvalMode = allowed2 ? choices.remember(current.request) : void 0;
23851
24202
  recordPajaConfirmation(getState(), current.request, allowed2, approvalMode);
23852
24203
  if (allowed2) current.approve();
23853
24204
  else current.deny();
@@ -23866,6 +24217,16 @@ function createPajaConfirmationController(getState, options = {}) {
23866
24217
  deny.addEventListener("click", onDeny);
23867
24218
  dialog.addEventListener("cancel", onCancel);
23868
24219
  }
24220
+ const cancelMatching = (matches) => {
24221
+ for (let index = queue.length - 1; index >= 0; index--) {
24222
+ const pending = queue[index];
24223
+ if (!matches(pending.request)) continue;
24224
+ queue.splice(index, 1);
24225
+ recordPajaConfirmation(getState(), pending.request, false);
24226
+ pending.deny();
24227
+ }
24228
+ if (active && matches(active.request)) settle6(false);
24229
+ };
23869
24230
  return {
23870
24231
  confirm(request) {
23871
24232
  if (!ready || disposed) {
@@ -23908,6 +24269,12 @@ function createPajaConfirmationController(getState, options = {}) {
23908
24269
  return cleared;
23909
24270
  },
23910
24271
  getSignerConsentCount: () => consentStore.count(),
24272
+ cancelWindow(windowId) {
24273
+ cancelMatching((request) => ("windowId" in request ? request.windowId : "signerContext" in request ? request.signerContext?.windowId : void 0) === windowId);
24274
+ },
24275
+ cancelSignerRequests() {
24276
+ cancelMatching((request) => request.action === "sign" || request.action === "publish");
24277
+ },
23911
24278
  dispose() {
23912
24279
  if (disposed) return;
23913
24280
  disposed = true;
@@ -23925,12 +24292,16 @@ function createPajaConfirmationController(getState, options = {}) {
23925
24292
  };
23926
24293
  }
23927
24294
  function signerConsentCandidate(request) {
23928
- if (request.action !== "sign" || !request.signerContext) return null;
24295
+ if (request.action !== "sign" && request.action !== "publish" || !request.signerContext) return null;
23929
24296
  if (!isPajaSignerConsentContext(request.signerContext)) return null;
23930
24297
  const kind = request.event.kind;
23931
24298
  if (typeof kind !== "number" || !Number.isSafeInteger(kind) || kind < 0 || kind > 65535) return null;
23932
24299
  return { context: request.signerContext, kind };
23933
24300
  }
24301
+ function isRequestCurrent(request) {
24302
+ if (request.isCurrent && !request.isCurrent()) return false;
24303
+ return !("signerContext" in request) || !request.signerContext?.isCurrent || request.signerContext.isCurrent();
24304
+ }
23934
24305
  function describeConfirmation(request) {
23935
24306
  if (request.action === "upload") {
23936
24307
  return confirmationCopy(
@@ -23951,6 +24322,7 @@ function describeConfirmation(request) {
23951
24322
  `${request.napplet.dTag} requests browser navigation.`,
23952
24323
  "Open link",
23953
24324
  `Napplet: ${request.napplet.dTag} (${request.windowId})`,
24325
+ `Version: ${request.napplet.aggregateHash}`,
23954
24326
  request.label ? `Label: ${request.label}` : void 0,
23955
24327
  `Destination: ${request.url}`
23956
24328
  );
@@ -24015,12 +24387,13 @@ function describeConfirmation(request) {
24015
24387
  const signerContext = request.signerContext;
24016
24388
  return {
24017
24389
  title: request.action === "sign" ? "Sign this Nostr event?" : "Publish this Nostr event?",
24018
- 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.",
24390
+ 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.",
24019
24391
  details: confirmationDetails(
24020
24392
  signerContext ? `Napplet: ${signerContext.napplet.dTag} (${signerContext.windowId})` : void 0,
24021
- signerContext ? `Identity hash: ${signerContext.napplet.aggregateHash}` : void 0,
24393
+ signerContext ? `Version: ${signerContext.napplet.aggregateHash}` : void 0,
24394
+ signerContext ? `Approval scope: ${signerContext.runtimeScope}` : void 0,
24022
24395
  signerContext?.runtimeScope.startsWith("target-url:") ? `Target URL: ${signerContext.runtimeScope.slice("target-url:".length)}` : void 0,
24023
- signerContext ? `Signer: ${signerContext.signerPubkey}` : void 0,
24396
+ signerContext ? `Signer: ${signerContext.signerPubkey === "host-generated" ? "Host-generated events (this Paja session)" : signerContext.signerPubkey}` : void 0,
24024
24397
  `Kind: ${kind}`,
24025
24398
  `Content: ${content}`
24026
24399
  ),
@@ -27131,8 +27504,17 @@ async function installPajaHost() {
27131
27504
  confirmationController.confirm
27132
27505
  );
27133
27506
  const getWindowIdentity = (windowId) => {
27134
- const tabTarget = stateRef?.tabs.find((tab) => tab.windowId === windowId)?.resolvedTarget;
27135
- return getTargetIdentity(config, tabTarget ?? stateRef?.resolvedTarget);
27507
+ const tab = stateRef?.tabs.find((tab2) => tab2.windowId === windowId);
27508
+ const target = tab?.resolvedTarget ?? stateRef?.resolvedTarget;
27509
+ const identity = getTargetIdentity(config, target);
27510
+ return {
27511
+ ...identity,
27512
+ consentScope: target ? `${isPajaLocalTarget(target) ? "local-file" : target.manifest.catalogId}:artifact:${target.aggregateHash}` : pajaDevelopmentConsentScope(config.target.url, windowId ?? ""),
27513
+ isCurrent: () => {
27514
+ const targetFrame = tab?.frame ?? frame;
27515
+ return !!targetFrame?.contentWindow && originRegistry.getWindowId(targetFrame.contentWindow) === windowId && (!tab || stateRef?.tabs.includes(tab) === true);
27516
+ }
27517
+ };
27136
27518
  };
27137
27519
  const notifyController = createPajaNotifyController({
27138
27520
  confirm: confirmationController.confirm,
@@ -27186,11 +27568,12 @@ async function installPajaHost() {
27186
27568
  await adapter.ready;
27187
27569
  const bridge = createShellBridge(adapter);
27188
27570
  const stopIdentityChanges = signerController.subscribe(() => {
27571
+ confirmationController.cancelSignerRequests();
27189
27572
  bridge.publishIdentityChanged(adapter.auth.getUserPubkey() ?? "");
27190
27573
  });
27191
27574
  themeBroadcast.attach(bridge);
27192
27575
  bridgeRef = bridge;
27193
- installPajaOriginRegistryProxy(originRegistry, () => stateRef);
27576
+ installPajaOriginRegistryProxy(originRegistry, () => stateRef, (windowId) => confirmationController.cancelWindow(windowId));
27194
27577
  const capabilities = buildShellCapabilities(adapter);
27195
27578
  const context = {
27196
27579
  config,