@kehto/paja 0.34.0 → 0.35.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.
@@ -3450,7 +3450,7 @@ function uploadMap(action) {
3450
3450
  return { senderCap: "upload:write", recipientCap: null };
3451
3451
  }
3452
3452
  function intentMap(action) {
3453
- if (action === "changed" || action === "invoke.result" || action === "available.result" || action === "handlers.result") {
3453
+ if (action === "changed" || action === "deliver" || action === "invoke.result" || action === "available.result" || action === "handlers.result") {
3454
3454
  return { senderCap: null, recipientCap: "intent:read" };
3455
3455
  }
3456
3456
  if (action === "invoke") return { senderCap: "intent:write", recipientCap: null };
@@ -3540,137 +3540,6 @@ function resolveCapabilitiesNap(msg) {
3540
3540
  }
3541
3541
 
3542
3542
  // ../firewall/dist/index.js
3543
- function toKey2(napplet, opClass) {
3544
- return `${napplet}:${opClass}`;
3545
- }
3546
- function actionToDecision(action) {
3547
- if (action === "block") return "reject";
3548
- return "pass";
3549
- }
3550
- function evaluate(config, state, observation) {
3551
- const { napplet, opClass, now: now2 } = observation;
3552
- const nappletRules = config.napplets[napplet];
3553
- const policy = nappletRules?.policy;
3554
- if (policy === "allow") {
3555
- return {
3556
- decision: "pass",
3557
- action: "ignore",
3558
- ruleId: "policy:allow",
3559
- reason: `napplet ${napplet} has allow policy \u2014 bypassing all checks`,
3560
- newState: state
3561
- };
3562
- }
3563
- if (policy === "deny") {
3564
- return {
3565
- decision: "reject",
3566
- action: "block",
3567
- ruleId: "policy:deny",
3568
- reason: `napplet ${napplet} has deny policy \u2014 always rejected`,
3569
- newState: state
3570
- };
3571
- }
3572
- if (policy === "ask") {
3573
- return {
3574
- decision: "prompt",
3575
- action: "block",
3576
- ruleId: "policy:ask",
3577
- reason: `napplet ${napplet} has ask policy \u2014 prompting for consent`,
3578
- newState: state
3579
- };
3580
- }
3581
- const { initElapsedMs } = observation;
3582
- if (initElapsedMs !== void 0 && initElapsedMs < config.burstGuard.windowMs) {
3583
- const burstKey = observation.initKey ?? napplet;
3584
- const existingBurst = state.bursts[burstKey];
3585
- const activeBurst = existingBurst !== void 0 && now2 - existingBurst.windowStart < config.burstGuard.windowMs ? existingBurst : void 0;
3586
- const newBurst = {
3587
- count: (activeBurst?.count ?? 0) + 1,
3588
- windowStart: activeBurst?.windowStart ?? now2
3589
- };
3590
- const newBursts = { ...state.bursts, [burstKey]: newBurst };
3591
- if (newBurst.count > config.burstGuard.maxOps) {
3592
- const burstAction = config.burstGuard.action;
3593
- return {
3594
- decision: actionToDecision(burstAction),
3595
- action: burstAction,
3596
- ruleId: "burst",
3597
- reason: `napplet ${napplet} exceeded init-burst limit (${newBurst.count} > ${config.burstGuard.maxOps} ops within ${config.burstGuard.windowMs}ms)`,
3598
- newState: { ...state, bursts: newBursts }
3599
- };
3600
- }
3601
- state = { ...state, bursts: newBursts };
3602
- }
3603
- for (const matcher of config.matchers) {
3604
- if (matcher.opClass !== void 0 && matcher.opClass !== opClass) continue;
3605
- if (matcher.kinds !== void 0) {
3606
- if (observation.kind === void 0) continue;
3607
- if (!matcher.kinds.includes(observation.kind)) continue;
3608
- }
3609
- if (matcher.minSize !== void 0) {
3610
- if (observation.size === void 0) continue;
3611
- if (observation.size < matcher.minSize) continue;
3612
- }
3613
- if (matcher.focused !== void 0 && matcher.focused !== observation.focused) continue;
3614
- if (matcher.maxMsSinceFocusGain !== void 0) {
3615
- if (observation.msSinceFocusGain === void 0) continue;
3616
- if (observation.msSinceFocusGain > matcher.maxMsSinceFocusGain) continue;
3617
- }
3618
- const matcherAction = matcher.action;
3619
- return {
3620
- decision: actionToDecision(matcherAction),
3621
- action: matcherAction,
3622
- ruleId: `matcher:${matcher.id}`,
3623
- reason: `content matcher '${matcher.id}' fired`,
3624
- newState: state
3625
- };
3626
- }
3627
- let rateLimit = config.defaultRate;
3628
- let rateLimitRuleId = "rate:default";
3629
- if (nappletRules) {
3630
- const opClassLimit = nappletRules.rateLimits[opClass];
3631
- if (opClassLimit) {
3632
- rateLimit = opClassLimit;
3633
- rateLimitRuleId = "rate:opclass";
3634
- } else if (nappletRules.globalRate) {
3635
- rateLimit = nappletRules.globalRate;
3636
- rateLimitRuleId = "rate:global";
3637
- }
3638
- }
3639
- const effectiveCapacity = observation.focused ? rateLimit.capacity : rateLimit.capacity * config.unfocusedMultiplier;
3640
- const refillRatePerMs = effectiveCapacity / rateLimit.windowMs;
3641
- const bucketKey = toKey2(napplet, opClass);
3642
- const existingBucket = state.buckets[bucketKey];
3643
- const lastRefill = existingBucket?.lastRefill ?? now2;
3644
- const initialTokens = existingBucket?.tokens ?? effectiveCapacity;
3645
- const elapsed = Math.max(0, now2 - lastRefill);
3646
- const tokens = Math.min(effectiveCapacity, initialTokens + elapsed * refillRatePerMs);
3647
- if (tokens >= 1) {
3648
- const nextBucket = { tokens: tokens - 1, lastRefill: now2 };
3649
- return {
3650
- decision: "pass",
3651
- action: "ignore",
3652
- ruleId: rateLimitRuleId,
3653
- reason: `within budget (${rateLimitRuleId})`,
3654
- newState: {
3655
- ...state,
3656
- buckets: { ...state.buckets, [bucketKey]: nextBucket }
3657
- }
3658
- };
3659
- } else {
3660
- const nextBucket = { tokens, lastRefill: now2 };
3661
- const exceedAction = rateLimit.action;
3662
- return {
3663
- decision: actionToDecision(exceedAction),
3664
- action: exceedAction,
3665
- ruleId: rateLimitRuleId,
3666
- reason: `rate limit exceeded (${rateLimitRuleId}): ${tokens.toFixed(4)} tokens available, need 1`,
3667
- newState: {
3668
- ...state,
3669
- buckets: { ...state.buckets, [bucketKey]: nextBucket }
3670
- }
3671
- };
3672
- }
3673
- }
3674
3543
  var DOMAIN2 = /^[a-z][a-z0-9-]*$/;
3675
3544
  function permissionText(value, max = 4096) {
3676
3545
  return typeof value === "string" && value.length > 0 && value.length <= max && !/[\u0000-\u001f\u007f]/.test(value);
@@ -3861,183 +3730,105 @@ function deserializePermissions(raw, options = {}) {
3861
3730
  return { ok: false, reason: "invalid-state" };
3862
3731
  }
3863
3732
  }
3864
- var DEFAULT_EXCEED_ACTION = "flag";
3865
- var DEFAULT_BURST_ACTION = "block";
3866
- var DEFAULT_UNFOCUSED_MULTIPLIER = 0.25;
3867
- var DEFAULT_RATE_CAPACITY = 60;
3868
- var DEFAULT_RATE_WINDOW_MS = 6e4;
3869
- var DEFAULT_BURST_WINDOW_MS = 3e3;
3870
- var DEFAULT_BURST_MAX_OPS = 20;
3871
- function defaultConfig() {
3872
- return {
3873
- napplets: {},
3874
- matchers: [],
3875
- burstGuard: {
3876
- windowMs: DEFAULT_BURST_WINDOW_MS,
3877
- maxOps: DEFAULT_BURST_MAX_OPS,
3878
- action: DEFAULT_BURST_ACTION
3879
- },
3880
- defaultRate: {
3881
- capacity: DEFAULT_RATE_CAPACITY,
3882
- windowMs: DEFAULT_RATE_WINDOW_MS,
3883
- action: DEFAULT_EXCEED_ACTION
3884
- },
3885
- unfocusedMultiplier: DEFAULT_UNFOCUSED_MULTIPLIER
3886
- };
3887
- }
3888
- function createState2() {
3889
- return { buckets: {}, bursts: {} };
3890
- }
3891
- function getNapplet(config, napplet) {
3892
- const existing = config.napplets[napplet];
3893
- if (existing) return existing;
3894
- return { rateLimits: {} };
3895
- }
3896
- function setPolicy(config, napplet, policy) {
3897
- const entry = getNapplet(config, napplet);
3898
- return {
3899
- ...config,
3900
- napplets: {
3901
- ...config.napplets,
3902
- [napplet]: { ...entry, policy }
3903
- }
3904
- };
3905
- }
3906
- function setRateLimit(config, napplet, opClass, limit) {
3907
- const entry = getNapplet(config, napplet);
3908
- return {
3909
- ...config,
3910
- napplets: {
3911
- ...config.napplets,
3912
- [napplet]: {
3913
- ...entry,
3914
- rateLimits: { ...entry.rateLimits, [opClass]: limit }
3915
- }
3916
- }
3917
- };
3918
- }
3919
- function setGlobalRate(config, napplet, limit) {
3920
- const entry = getNapplet(config, napplet);
3921
- return {
3922
- ...config,
3923
- napplets: {
3924
- ...config.napplets,
3925
- [napplet]: { ...entry, globalRate: limit }
3926
- }
3927
- };
3928
- }
3929
- function setUnfocusedMultiplier(config, multiplier) {
3930
- if (!Number.isFinite(multiplier) || multiplier <= 0) {
3931
- throw new RangeError("unfocusedMultiplier must be a finite number above zero");
3932
- }
3933
- return { ...config, unfocusedMultiplier: multiplier };
3934
- }
3935
- function setBurstGuard(config, guard) {
3936
- const { windowMs, maxOps, action } = guard;
3937
- if (!Number.isFinite(windowMs) || windowMs < 0) {
3938
- throw new RangeError("burstGuard.windowMs must be a finite number of zero or more");
3939
- }
3940
- if (!Number.isSafeInteger(maxOps) || maxOps < 0) {
3941
- throw new RangeError("burstGuard.maxOps must be a non-negative safe integer");
3942
- }
3943
- if (!isValidAction(action)) {
3944
- throw new RangeError("burstGuard.action must be 'flag', 'block' or 'ignore'");
3733
+ var DOMAIN22 = /^[a-z][a-z0-9-]*$/;
3734
+ var OPERATION = /^[a-z][a-z0-9-]*\.[A-Za-z0-9][A-Za-z0-9._-]*$/;
3735
+ var MAX_RULES = 512;
3736
+ var MAX_NAPPLETS = 256;
3737
+ var MAX_SUBJECT_LENGTH = 4096;
3738
+ var MAX_DOCUMENT_LENGTH = 512 * 1024;
3739
+ function isAction(value) {
3740
+ return value === "allow" || value === "ask" || value === "deny";
3741
+ }
3742
+ function actionMap(value, key) {
3743
+ if (value === void 0) return Object.freeze({});
3744
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("Invalid permission rule map");
3745
+ const entries = Object.entries(value);
3746
+ if (entries.length > MAX_RULES) throw new RangeError("Permission rule limit exceeded");
3747
+ const result2 = {};
3748
+ for (const [name, action] of entries) {
3749
+ if (!key.test(name) || name.length > 256 || !isAction(action)) throw new TypeError("Invalid permission rule");
3750
+ result2[name] = action;
3945
3751
  }
3946
- return { ...config, burstGuard: { windowMs, maxOps, action } };
3947
- }
3948
- function addMatcher(config, matcher) {
3949
- return { ...config, matchers: [...config.matchers, matcher] };
3752
+ return Object.freeze(result2);
3950
3753
  }
3951
- function serialize2(config) {
3952
- return JSON.stringify(config);
3953
- }
3954
- var VALID_ACTIONS = ["flag", "block", "ignore"];
3955
- function isValidAction(v) {
3956
- return VALID_ACTIONS.includes(v);
3957
- }
3958
- function isValidRateLimit(v) {
3959
- if (typeof v !== "object" || v === null) return false;
3960
- const r = v;
3961
- return typeof r["capacity"] === "number" && isFinite(r["capacity"]) && typeof r["windowMs"] === "number" && isFinite(r["windowMs"]) && isValidAction(r["action"]);
3754
+ function scopeSnapshot(value) {
3755
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("Invalid napplet permission rules");
3756
+ const scope = value;
3757
+ if (scope.default !== void 0 && !isAction(scope.default)) throw new TypeError("Invalid permission rule");
3758
+ return Object.freeze({
3759
+ ...scope.default !== void 0 ? { default: scope.default } : {},
3760
+ domains: actionMap(scope.domains, DOMAIN22),
3761
+ operations: actionMap(scope.operations, OPERATION)
3762
+ });
3962
3763
  }
3963
- function isValidBurstGuard(v) {
3964
- if (typeof v !== "object" || v === null) return false;
3965
- const b = v;
3966
- return typeof b["windowMs"] === "number" && isFinite(b["windowMs"]) && typeof b["maxOps"] === "number" && isFinite(b["maxOps"]) && isValidAction(b["action"]);
3764
+ function subjectText(value) {
3765
+ return value.length > 0 && value.length <= MAX_SUBJECT_LENGTH && !/[\u0000-\u001f\u007f]/.test(value);
3967
3766
  }
3968
- function isValidContentMatcher(v) {
3969
- if (typeof v !== "object" || v === null) return false;
3970
- const m = v;
3971
- if (typeof m["id"] !== "string") return false;
3972
- if (!isValidAction(m["action"])) return false;
3973
- if ("opClass" in m && typeof m["opClass"] !== "string") return false;
3974
- if ("minSize" in m && typeof m["minSize"] !== "number") return false;
3975
- if ("focused" in m && typeof m["focused"] !== "boolean") return false;
3976
- if ("maxMsSinceFocusGain" in m && typeof m["maxMsSinceFocusGain"] !== "number") return false;
3977
- if ("kinds" in m) {
3978
- if (!Array.isArray(m["kinds"])) return false;
3979
- if (!m["kinds"].every((k) => typeof k === "number")) return false;
3767
+ function createPermissionRules(init = {}) {
3768
+ if (init.default !== void 0 && !isAction(init.default)) throw new TypeError("Invalid permission rule");
3769
+ const napplets = {};
3770
+ const entries = Object.entries(init.napplets ?? {});
3771
+ if (entries.length > MAX_NAPPLETS) throw new RangeError("Permission rule limit exceeded");
3772
+ for (const [subject, scope] of entries) {
3773
+ if (!subjectText(subject)) throw new TypeError("Invalid permission rule subject");
3774
+ const snapshot22 = scopeSnapshot(scope);
3775
+ const empty = snapshot22.default === void 0 && !Object.keys(snapshot22.domains).length && !Object.keys(snapshot22.operations).length;
3776
+ if (!empty) napplets[subject] = snapshot22;
3980
3777
  }
3981
- return true;
3982
- }
3983
- function isValidNappletRules(v) {
3984
- if (typeof v !== "object" || v === null) return false;
3985
- const n = v;
3986
- if (typeof n["rateLimits"] !== "object" || n["rateLimits"] === null) return false;
3987
- for (const limit of Object.values(n["rateLimits"])) {
3988
- if (!isValidRateLimit(limit)) return false;
3989
- }
3990
- if ("policy" in n) {
3991
- const p = n["policy"];
3992
- if (p !== "allow" && p !== "deny" && p !== "ask") return false;
3993
- }
3994
- if ("globalRate" in n && !isValidRateLimit(n["globalRate"])) return false;
3995
- return true;
3778
+ return Object.freeze({
3779
+ version: 1,
3780
+ default: init.default ?? "ask",
3781
+ domains: actionMap(init.domains, DOMAIN22),
3782
+ operations: actionMap(init.operations, OPERATION),
3783
+ napplets: Object.freeze(napplets)
3784
+ });
3996
3785
  }
3997
- function deserialize2(json) {
3786
+ function permissionRuleSubject(principal) {
3787
+ return principal.kind === "verified" ? principal.manifestKey : `development:${principal.target}`;
3788
+ }
3789
+ function resolvePermissionRule(rules, principal, requirement) {
3790
+ const operation = requirement.category === "interface" ? void 0 : requirement.operation;
3791
+ const napplet = rules.napplets[permissionRuleSubject(principal)];
3792
+ const pick = (scope) => {
3793
+ if (!scope) return void 0;
3794
+ const byOperation = operation !== void 0 && Object.hasOwn(scope.operations, operation) ? scope.operations[operation] : void 0;
3795
+ const byDomain = Object.hasOwn(scope.domains, requirement.domain) ? scope.domains[requirement.domain] : void 0;
3796
+ return byOperation ?? byDomain ?? scope.default;
3797
+ };
3798
+ return pick(napplet) ?? pick(rules) ?? rules.default;
3799
+ }
3800
+ function withEntry(map, key, action) {
3801
+ const next = { ...map };
3802
+ if (action === void 0) delete next[key];
3803
+ else next[key] = action;
3804
+ return next;
3805
+ }
3806
+ function setPermissionRule(rules, target, action) {
3807
+ if (target.domain !== void 0 && target.operation !== void 0) throw new TypeError("A rule targets a domain or an operation, not both");
3808
+ const apply = (scope) => {
3809
+ if (target.operation !== void 0) return { ...scope, operations: withEntry(scope.operations, target.operation, action) };
3810
+ if (target.domain !== void 0) return { ...scope, domains: withEntry(scope.domains, target.domain, action) };
3811
+ const { default: _removed, ...rest } = scope;
3812
+ return action === void 0 ? rest : { ...rest, default: action };
3813
+ };
3814
+ if (target.napplet === void 0) return createPermissionRules(apply(rules));
3815
+ const current = rules.napplets[target.napplet] ?? { domains: {}, operations: {} };
3816
+ return createPermissionRules({ ...rules, napplets: { ...rules.napplets, [target.napplet]: apply(current) } });
3817
+ }
3818
+ function serializePermissionRules(rules) {
3819
+ return JSON.stringify(createPermissionRules(rules));
3820
+ }
3821
+ function deserializePermissionRules(raw) {
3998
3822
  try {
3999
- const parsed = JSON.parse(json);
4000
- if (typeof parsed !== "object" || parsed === null || typeof parsed.napplets !== "object" || parsed.napplets === null || !Array.isArray(parsed.matchers) || !isValidBurstGuard(parsed.burstGuard) || !isValidRateLimit(parsed.defaultRate) || typeof parsed.unfocusedMultiplier !== "number" || !isFinite(parsed.unfocusedMultiplier)) {
4001
- return defaultConfig();
4002
- }
4003
- const napplets = {};
4004
- for (const [key, value] of Object.entries(parsed.napplets)) {
4005
- if (!isValidNappletRules(value)) return defaultConfig();
4006
- const raw = value;
4007
- const rateLimits = {};
4008
- for (const [opClass, limit] of Object.entries(raw.rateLimits)) {
4009
- rateLimits[opClass] = limit;
4010
- }
4011
- const entry = { rateLimits };
4012
- const withPolicy = raw.policy !== void 0 ? { ...entry, policy: raw.policy } : entry;
4013
- const withGlobalRate = raw.globalRate !== void 0 ? { ...withPolicy, globalRate: raw.globalRate } : withPolicy;
4014
- napplets[key] = withGlobalRate;
4015
- }
4016
- const matchers = [];
4017
- for (const item of parsed.matchers) {
4018
- if (!isValidContentMatcher(item)) return defaultConfig();
4019
- matchers.push(item);
4020
- }
4021
- const bg = parsed.burstGuard;
4022
- const dr = parsed.defaultRate;
4023
- return {
4024
- napplets,
4025
- matchers,
4026
- burstGuard: {
4027
- windowMs: bg["windowMs"],
4028
- maxOps: bg["maxOps"],
4029
- action: bg["action"]
4030
- },
4031
- defaultRate: {
4032
- capacity: dr["capacity"],
4033
- windowMs: dr["windowMs"],
4034
- action: dr["action"]
4035
- },
4036
- unfocusedMultiplier: parsed.unfocusedMultiplier
4037
- };
3823
+ if (raw.length > MAX_DOCUMENT_LENGTH) return { ok: false, reason: "invalid-rules" };
3824
+ const parsed = JSON.parse(raw);
3825
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return { ok: false, reason: "invalid-rules" };
3826
+ if (parsed.version !== 1) return { ok: false, reason: "unsupported-version" };
3827
+ if (!isAction(parsed.default)) return { ok: false, reason: "invalid-rules" };
3828
+ return { ok: true, rules: createPermissionRules(parsed) };
4038
3829
  } catch {
3830
+ return { ok: false, reason: "invalid-rules" };
4039
3831
  }
4040
- return defaultConfig();
4041
3832
  }
4042
3833
 
4043
3834
  // ../../node_modules/.pnpm/@napplet+core@0.41.0/node_modules/@napplet/core/dist/index.js
@@ -4552,142 +4343,168 @@ function createAclState(persistence, defaultPolicy = "permissive", onMutation, p
4552
4343
  }
4553
4344
  };
4554
4345
  }
4555
- function createFirewallState(persistence, onMutation) {
4556
- let config = defaultConfig();
4557
- let counters = createState2();
4558
- const mutate = (next) => {
4559
- onMutation?.();
4560
- config = next;
4561
- };
4562
- return {
4563
- evaluate(observation) {
4564
- const result2 = evaluate(config, counters, observation);
4565
- counters = result2.newState;
4566
- return result2;
4567
- },
4568
- resetInitBudget(initKey) {
4569
- if (!Object.hasOwn(counters.bursts, initKey)) return;
4570
- const bursts = { ...counters.bursts };
4571
- delete bursts[initKey];
4572
- counters = { ...counters, bursts };
4573
- },
4574
- setPolicy(napplet, policy) {
4575
- mutate(setPolicy(config, napplet, policy));
4576
- },
4577
- setRateLimit(napplet, opClass, limit) {
4578
- mutate(setRateLimit(config, napplet, opClass, limit));
4579
- },
4580
- setGlobalRate(napplet, limit) {
4581
- mutate(setGlobalRate(config, napplet, limit));
4582
- },
4583
- setUnfocusedMultiplier(multiplier) {
4584
- mutate(setUnfocusedMultiplier(config, multiplier));
4585
- },
4586
- setBurstGuard(guard) {
4587
- mutate(setBurstGuard(config, guard));
4588
- },
4589
- addMatcher(matcher) {
4590
- mutate(addMatcher(config, matcher));
4591
- },
4592
- getConfig() {
4593
- return config;
4594
- },
4595
- persist() {
4346
+ var DEFAULT_RULE_GRANT_PREFIX = "rule:";
4347
+ function createApprovalCoordinator(options) {
4348
+ const maxPending = options.maxPending ?? 64;
4349
+ const timeoutMs = options.timeoutMs ?? 6e4;
4350
+ if (!Number.isSafeInteger(maxPending) || maxPending < 1 || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2147483647) {
4351
+ throw new RangeError("Invalid approval queue limits");
4352
+ }
4353
+ const pending = /* @__PURE__ */ new Set();
4354
+ const groups = /* @__PURE__ */ new Map();
4355
+ let reserved = 0;
4356
+ let disposed = false;
4357
+ function cancel(sessionId) {
4358
+ for (const entry of pending) {
4359
+ if (sessionId === void 0 || entry.sessionId === sessionId) entry.controller.abort();
4360
+ }
4361
+ }
4362
+ function snapshot4(principal, sessionId, requirements3) {
4363
+ const request = {
4364
+ principal: Object.freeze({ ...principal }),
4365
+ sessionId,
4366
+ requestId: options.createId(),
4367
+ requirements: requirements3
4368
+ };
4369
+ const normalized = evaluatePermissions(createPermissionState(), request, options).missing;
4370
+ return Object.freeze({ ...request, requirements: normalized });
4371
+ }
4372
+ async function approve(request, entry, current, allowLifetimes) {
4373
+ if (!current()) return { status: "cancelled" };
4374
+ const state = options.getState();
4375
+ const decision = evaluatePermissions(state, request, options);
4376
+ if (decision.decision === "deny") return { status: "denied" };
4377
+ if (decision.decision === "allow") return void 0;
4378
+ let preset = "ask";
4379
+ try {
4380
+ preset = options.defaultDecision?.(request, decision.missing) ?? "ask";
4381
+ } catch {
4382
+ preset = "ask";
4383
+ }
4384
+ if (preset === "deny") return { status: "denied" };
4385
+ const byRule = preset === "allow" && allowLifetimes.includes("session");
4386
+ let answer;
4387
+ if (byRule) {
4388
+ answer = { effect: "allow", lifetime: "session" };
4389
+ } else {
4390
+ if (!options.prompt) return { status: "unavailable" };
4596
4391
  try {
4597
- persistence?.persist(serialize2(config));
4392
+ if (options.beforePrompt && !options.beforePrompt(request)) return { status: "busy" };
4598
4393
  } catch {
4394
+ return { status: "unavailable" };
4599
4395
  }
4600
- },
4601
- load() {
4602
4396
  try {
4603
- const raw = persistence?.load() ?? null;
4604
- if (!raw) return;
4605
- config = deserialize2(raw);
4397
+ answer = await options.prompt(Object.freeze({ request, missing: decision.missing, signal: entry.controller.signal, allowLifetimes }));
4606
4398
  } catch {
4607
- config = defaultConfig();
4399
+ return { status: current() ? "unavailable" : "cancelled" };
4608
4400
  }
4609
- },
4610
- clear() {
4611
- config = defaultConfig();
4612
- counters = createState2();
4401
+ }
4402
+ if (!current()) return { status: "cancelled" };
4403
+ if (answer?.effect === "cancel") return { status: "cancelled" };
4404
+ const latest = options.getState();
4405
+ const rechecked = evaluatePermissions(latest, request, options);
4406
+ if (rechecked.decision === "deny") return { status: "denied" };
4407
+ const shown = new Set(decision.missing.map((requirement) => JSON.stringify(requirement)));
4408
+ if (rechecked.missing.some((requirement) => !shown.has(JSON.stringify(requirement)))) return { status: "cancelled" };
4409
+ if (!answer || answer.effect !== "allow" && answer.effect !== "deny" || !["once", "session", "persistent"].includes(answer.lifetime)) return { status: "unavailable" };
4410
+ if (answer.effect === "allow" && !allowLifetimes.includes(answer.lifetime)) return { status: "unavailable" };
4411
+ if (answer.effect === "deny" && answer.lifetime === "once") return { status: "denied" };
4412
+ try {
4413
+ let next = latest;
4414
+ for (const [index, permission] of decision.missing.entries()) {
4415
+ next = putPermissionGrant(next, {
4416
+ id: `${byRule ? DEFAULT_RULE_GRANT_PREFIX : ""}${request.requestId}-${index}`,
4417
+ principal: request.principal,
4418
+ permission,
4419
+ effect: answer.effect,
4420
+ lifetime: answer.lifetime,
4421
+ ...answer.lifetime !== "persistent" ? { sessionId: request.sessionId } : {},
4422
+ ...answer.lifetime === "once" ? { requestId: request.requestId } : {}
4423
+ }, options);
4424
+ }
4425
+ options.commit(next);
4426
+ } catch {
4427
+ return { status: "unavailable" };
4428
+ }
4429
+ return answer.effect === "deny" ? { status: "denied" } : void 0;
4430
+ }
4431
+ function run(principal, sessionId, requirements3, isCurrent, execute, lifetimes = ["once", "session", "persistent"], signal) {
4432
+ if (disposed || signal?.aborted) return Promise.resolve({ status: "cancelled" });
4433
+ if (reserved >= maxPending) return Promise.resolve({ status: "busy" });
4434
+ let request;
4435
+ try {
4436
+ request = snapshot4(principal, sessionId, requirements3);
4437
+ } catch {
4438
+ return Promise.resolve({ status: "denied" });
4439
+ }
4440
+ const allowLifetimes = Object.freeze(lifetimes.filter((lifetime) => principal.kind === "verified" || lifetime !== "persistent"));
4441
+ const controller = options.createCancellation();
4442
+ const entry = { sessionId, controller };
4443
+ pending.add(entry);
4444
+ reserved++;
4445
+ const current = () => !controller.signal.aborted && !disposed && isCurrent();
4446
+ const key = JSON.stringify([
4447
+ permissionPrincipalKey(request.principal),
4448
+ sessionId,
4449
+ request.requirements.map((item) => JSON.stringify(item)).sort()
4450
+ ]);
4451
+ const previous = groups.get(key) ?? Promise.resolve();
4452
+ let clearDeadline;
4453
+ let onAbort;
4454
+ const cancelled3 = new Promise((resolve) => {
4455
+ onAbort = () => resolve({ status: "cancelled" });
4456
+ controller.signal.addEventListener("abort", onAbort, { once: true });
4457
+ clearDeadline = options.schedule(() => controller.abort(), timeoutMs);
4458
+ });
4459
+ const abortRequest = () => controller.abort();
4460
+ signal?.addEventListener("abort", abortRequest, { once: true });
4461
+ if (signal?.aborted) abortRequest();
4462
+ const operation = previous.then(async () => {
4463
+ const failure4 = await approve(request, entry, current, allowLifetimes);
4464
+ if (failure4) return failure4;
4465
+ if (!current()) return { status: "cancelled" };
4466
+ const state = options.getState();
4467
+ const consumed = consumePermissionGrants(state, request, options);
4468
+ if (consumed.decision.decision !== "allow") return { status: "denied" };
4613
4469
  try {
4614
- persistence?.persist("");
4470
+ if (consumed.state.grants.length !== state.grants.length) options.commit(consumed.state);
4615
4471
  } catch {
4472
+ return { status: "unavailable" };
4616
4473
  }
4617
- }
4618
- };
4619
- }
4620
- function defaultRateLimitConfig() {
4621
- return {
4622
- capacity: 60,
4623
- windowMs: 6e4,
4624
- action: "flag",
4625
- unfocusedMultiplier: 0.25,
4626
- burst: { windowMs: 3e3, maxOperations: 20, action: "block" }
4627
- };
4628
- }
4629
- function defaultPromptRateLimitConfig() {
4474
+ if (!current()) return { status: "cancelled" };
4475
+ const spent = state.grants.filter((grant2) => grant2.lifetime === "once" && consumed.decision.grantIds.includes(grant2.id));
4476
+ const value = await execute(controller.signal);
4477
+ if (!current()) return { status: "cancelled" };
4478
+ const latest = options.getState();
4479
+ const continuation = evaluatePermissions({ version: 1, grants: [...latest.grants, ...spent] }, request, options);
4480
+ return continuation.decision === "allow" ? { status: "executed", value } : { status: "cancelled" };
4481
+ });
4482
+ const settled = Promise.race([operation, cancelled3]).finally(() => {
4483
+ clearDeadline();
4484
+ controller.signal.removeEventListener("abort", onAbort);
4485
+ signal?.removeEventListener("abort", abortRequest);
4486
+ pending.delete(entry);
4487
+ });
4488
+ const completed2 = settled.then(() => void 0, () => void 0);
4489
+ const tail = previous.then(() => completed2).finally(() => {
4490
+ reserved--;
4491
+ if (groups.get(key) === tail) groups.delete(key);
4492
+ });
4493
+ groups.set(key, tail);
4494
+ return settled;
4495
+ }
4630
4496
  return {
4631
- capacity: 12,
4632
- windowMs: 6e4,
4633
- action: "block",
4634
- unfocusedMultiplier: 1,
4635
- burst: { windowMs: 3e3, maxOperations: 8, action: "block" }
4497
+ run,
4498
+ cancel,
4499
+ dispose() {
4500
+ disposed = true;
4501
+ cancel();
4502
+ },
4503
+ get pendingCount() {
4504
+ return pending.size;
4505
+ }
4636
4506
  };
4637
4507
  }
4638
- function createRateLimitState() {
4639
- return { buckets: {}, bursts: {} };
4640
- }
4641
- function positive(value) {
4642
- return Number.isFinite(value) && value > 0;
4643
- }
4644
- function validAction(value) {
4645
- return value === "flag" || value === "block" || value === "ignore";
4646
- }
4647
- function assertRateLimitConfig(config) {
4648
- const { burst } = config;
4649
- if (!positive(config.capacity) || !positive(config.windowMs) || !positive(config.unfocusedMultiplier) || !Number.isFinite(burst.windowMs) || burst.windowMs < 0 || !Number.isSafeInteger(burst.maxOperations) || burst.maxOperations < 0 || !validAction(config.action) || !validAction(burst.action)) {
4650
- throw new RangeError("Rate limits require finite budgets in range and valid actions");
4651
- }
4652
- }
4653
- function validate(config, observation) {
4654
- assertRateLimitConfig(config);
4655
- if (!observation.subject || !observation.operation || !observation.lifecycle || !Number.isFinite(observation.now) || !Number.isFinite(observation.elapsedSinceStartMs) || observation.elapsedSinceStartMs < 0 || typeof observation.focused !== "boolean") {
4656
- throw new RangeError("Rate observations require a subject, operation, lifecycle and finite clock");
4657
- }
4658
- }
4659
- function verdict(state, reason, action) {
4660
- return { allowed: action !== "block", action, reason, state };
4661
- }
4662
- function evaluateRateLimit(config, state, observation) {
4663
- validate(config, observation);
4664
- const { subject, operation, lifecycle, now: now2 } = observation;
4665
- if (observation.elapsedSinceStartMs < config.burst.windowMs) {
4666
- const key2 = JSON.stringify([subject, lifecycle]);
4667
- const previous2 = state.bursts[key2];
4668
- const active = previous2 && now2 - previous2.startedAt < config.burst.windowMs ? previous2 : void 0;
4669
- const burst = { count: (active?.count ?? 0) + 1, startedAt: active?.startedAt ?? now2 };
4670
- state = { ...state, bursts: { ...state.bursts, [key2]: burst } };
4671
- if (burst.count > config.burst.maxOperations) return verdict(state, "burst-exceeded", config.burst.action);
4672
- }
4673
- const key = JSON.stringify([subject, operation]);
4674
- const capacity = config.capacity * (observation.focused ? 1 : config.unfocusedMultiplier);
4675
- const previous = state.buckets[key];
4676
- const updatedAt = Math.max(now2, previous?.updatedAt ?? now2);
4677
- const elapsed = updatedAt - (previous?.updatedAt ?? updatedAt);
4678
- const tokens = Math.min(capacity, (previous?.tokens ?? capacity) + elapsed * (capacity / config.windowMs));
4679
- const exceeded = tokens < 1;
4680
- const bucket = { tokens: exceeded ? tokens : tokens - 1, updatedAt };
4681
- state = { ...state, buckets: { ...state.buckets, [key]: bucket } };
4682
- return verdict(state, exceeded ? "rate-exceeded" : "within-budget", exceeded ? config.action : "ignore");
4683
- }
4684
- function retireRateLimitLifecycle(state, subject, lifecycle) {
4685
- const key = JSON.stringify([subject, lifecycle]);
4686
- if (!Object.hasOwn(state.bursts, key)) return state;
4687
- const bursts = { ...state.bursts };
4688
- delete bursts[key];
4689
- return { ...state, bursts };
4690
- }
4691
4508
  function createManifestCache(persistence) {
4692
4509
  const cache2 = /* @__PURE__ */ new Map();
4693
4510
  const verificationCache = /* @__PURE__ */ new Map();
@@ -5191,13 +5008,14 @@ function createLegacyIgnoredWarning() {
5191
5008
  return () => {
5192
5009
  if (warned2) return;
5193
5010
  warned2 = true;
5194
- console.warn("FW-RUNTIME-LEGACY-IGNORED-001: onFirewallEvent, firewallPersistence and firewallState mutators have no effect when RuntimeAdapter.permissions is configured; use permissions.onRateLimit, permissions.persistence and runtime.permissions.setRateLimit instead (warns once per runtime instance).");
5011
+ console.warn("FW-RUNTIME-LEGACY-IGNORED-001: onFirewallEvent and legacyFirewall have no effect when RuntimeAdapter.permissions is configured; use permissions.onRateLimit, permissions.persistence and an explicit permissions.rateLimiter instead (warns once per runtime instance).");
5195
5012
  };
5196
5013
  }
5197
5014
  function createFirewallGate(config) {
5198
5015
  const { firewallState, sessionRegistry: sessionRegistry2, hooks, fireConsent } = config;
5199
5016
  let warned2 = false;
5200
5017
  return function firewallGate(windowId, envelope, senderCap, respond = true) {
5018
+ if (!firewallState) return "dispatch";
5201
5019
  if (!warned2) {
5202
5020
  warned2 = true;
5203
5021
  console.warn("FW-RUNTIME-LEGACY-GATE-001: the legacy temporal Firewall gate is active; configure RuntimeAdapter.permissions for scoped Firewall approvals and independent rate limits (warns once per runtime instance; retained through the next minor release).");
@@ -5266,155 +5084,6 @@ function createDenialResponse(envelope, error) {
5266
5084
  const type = denialResponseType(envelope);
5267
5085
  return type ? { type, id, error } : null;
5268
5086
  }
5269
- function createApprovalCoordinator(options) {
5270
- const maxPending = options.maxPending ?? 64;
5271
- const timeoutMs = options.timeoutMs ?? 6e4;
5272
- if (!Number.isSafeInteger(maxPending) || maxPending < 1 || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2147483647) {
5273
- throw new RangeError("Invalid approval queue limits");
5274
- }
5275
- const pending = /* @__PURE__ */ new Set();
5276
- const groups = /* @__PURE__ */ new Map();
5277
- let reserved = 0;
5278
- let disposed = false;
5279
- function cancel(sessionId) {
5280
- for (const entry of pending) {
5281
- if (sessionId === void 0 || entry.sessionId === sessionId) entry.controller.abort();
5282
- }
5283
- }
5284
- function snapshot3(principal, sessionId, requirements3) {
5285
- const request = {
5286
- principal: Object.freeze({ ...principal }),
5287
- sessionId,
5288
- requestId: options.createId(),
5289
- requirements: requirements3
5290
- };
5291
- const normalized = evaluatePermissions(createPermissionState(), request, options).missing;
5292
- return Object.freeze({ ...request, requirements: normalized });
5293
- }
5294
- async function approve(request, entry, current, allowLifetimes) {
5295
- if (!current()) return { status: "cancelled" };
5296
- const state = options.getState();
5297
- const decision = evaluatePermissions(state, request, options);
5298
- if (decision.decision === "deny") return { status: "denied" };
5299
- if (decision.decision === "allow") return void 0;
5300
- if (!options.prompt) return { status: "unavailable" };
5301
- try {
5302
- if (options.beforePrompt && !options.beforePrompt(request)) return { status: "busy" };
5303
- } catch {
5304
- return { status: "unavailable" };
5305
- }
5306
- let answer;
5307
- try {
5308
- answer = await options.prompt(Object.freeze({ request, missing: decision.missing, signal: entry.controller.signal, allowLifetimes }));
5309
- } catch {
5310
- return { status: current() ? "unavailable" : "cancelled" };
5311
- }
5312
- if (!current()) return { status: "cancelled" };
5313
- if (answer?.effect === "cancel") return { status: "cancelled" };
5314
- const latest = options.getState();
5315
- const rechecked = evaluatePermissions(latest, request, options);
5316
- if (rechecked.decision === "deny") return { status: "denied" };
5317
- const shown = new Set(decision.missing.map((requirement) => JSON.stringify(requirement)));
5318
- if (rechecked.missing.some((requirement) => !shown.has(JSON.stringify(requirement)))) return { status: "cancelled" };
5319
- if (!answer || answer.effect !== "allow" && answer.effect !== "deny" || !["once", "session", "persistent"].includes(answer.lifetime)) return { status: "unavailable" };
5320
- if (answer.effect === "allow" && !allowLifetimes.includes(answer.lifetime)) return { status: "unavailable" };
5321
- if (answer.effect === "deny" && answer.lifetime === "once") return { status: "denied" };
5322
- try {
5323
- let next = latest;
5324
- for (const [index, permission] of decision.missing.entries()) {
5325
- next = putPermissionGrant(next, {
5326
- id: `${request.requestId}-${index}`,
5327
- principal: request.principal,
5328
- permission,
5329
- effect: answer.effect,
5330
- lifetime: answer.lifetime,
5331
- ...answer.lifetime !== "persistent" ? { sessionId: request.sessionId } : {},
5332
- ...answer.lifetime === "once" ? { requestId: request.requestId } : {}
5333
- }, options);
5334
- }
5335
- options.commit(next);
5336
- } catch {
5337
- return { status: "unavailable" };
5338
- }
5339
- return answer.effect === "deny" ? { status: "denied" } : void 0;
5340
- }
5341
- function run(principal, sessionId, requirements3, isCurrent, execute, lifetimes = ["once", "session", "persistent"], signal) {
5342
- if (disposed || signal?.aborted) return Promise.resolve({ status: "cancelled" });
5343
- if (reserved >= maxPending) return Promise.resolve({ status: "busy" });
5344
- let request;
5345
- try {
5346
- request = snapshot3(principal, sessionId, requirements3);
5347
- } catch {
5348
- return Promise.resolve({ status: "denied" });
5349
- }
5350
- const allowLifetimes = Object.freeze(lifetimes.filter((lifetime) => principal.kind === "verified" || lifetime !== "persistent"));
5351
- const controller = options.createCancellation();
5352
- const entry = { sessionId, controller };
5353
- pending.add(entry);
5354
- reserved++;
5355
- const current = () => !controller.signal.aborted && !disposed && isCurrent();
5356
- const key = JSON.stringify([
5357
- permissionPrincipalKey(request.principal),
5358
- sessionId,
5359
- request.requirements.map((item) => JSON.stringify(item)).sort()
5360
- ]);
5361
- const previous = groups.get(key) ?? Promise.resolve();
5362
- let clearDeadline;
5363
- let onAbort;
5364
- const cancelled3 = new Promise((resolve) => {
5365
- onAbort = () => resolve({ status: "cancelled" });
5366
- controller.signal.addEventListener("abort", onAbort, { once: true });
5367
- clearDeadline = options.schedule(() => controller.abort(), timeoutMs);
5368
- });
5369
- const abortRequest = () => controller.abort();
5370
- signal?.addEventListener("abort", abortRequest, { once: true });
5371
- if (signal?.aborted) abortRequest();
5372
- const operation = previous.then(async () => {
5373
- const failure4 = await approve(request, entry, current, allowLifetimes);
5374
- if (failure4) return failure4;
5375
- if (!current()) return { status: "cancelled" };
5376
- const state = options.getState();
5377
- const consumed = consumePermissionGrants(state, request, options);
5378
- if (consumed.decision.decision !== "allow") return { status: "denied" };
5379
- try {
5380
- if (consumed.state.grants.length !== state.grants.length) options.commit(consumed.state);
5381
- } catch {
5382
- return { status: "unavailable" };
5383
- }
5384
- if (!current()) return { status: "cancelled" };
5385
- const spent = state.grants.filter((grant2) => grant2.lifetime === "once" && consumed.decision.grantIds.includes(grant2.id));
5386
- const value = await execute(controller.signal);
5387
- if (!current()) return { status: "cancelled" };
5388
- const latest = options.getState();
5389
- const continuation = evaluatePermissions({ version: 1, grants: [...latest.grants, ...spent] }, request, options);
5390
- return continuation.decision === "allow" ? { status: "executed", value } : { status: "cancelled" };
5391
- });
5392
- const settled = Promise.race([operation, cancelled3]).finally(() => {
5393
- clearDeadline();
5394
- controller.signal.removeEventListener("abort", onAbort);
5395
- signal?.removeEventListener("abort", abortRequest);
5396
- pending.delete(entry);
5397
- });
5398
- const completed2 = settled.then(() => void 0, () => void 0);
5399
- const tail = previous.then(() => completed2).finally(() => {
5400
- reserved--;
5401
- if (groups.get(key) === tail) groups.delete(key);
5402
- });
5403
- groups.set(key, tail);
5404
- return settled;
5405
- }
5406
- return {
5407
- run,
5408
- cancel,
5409
- dispose() {
5410
- disposed = true;
5411
- cancel();
5412
- },
5413
- get pendingCount() {
5414
- return pending.size;
5415
- }
5416
- };
5417
- }
5418
5087
  function createPermissionStore(options) {
5419
5088
  let state = createPermissionState();
5420
5089
  let healthy = true;
@@ -5579,10 +5248,6 @@ function createPermissionRuntime(context) {
5579
5248
  const { adapter } = context;
5580
5249
  const lifetimes = /* @__PURE__ */ new Map();
5581
5250
  const retiredSources = /* @__PURE__ */ new WeakSet();
5582
- let rates = createRateLimitState();
5583
- let promptRates = createRateLimitState();
5584
- let rateLimitOverride;
5585
- const currentRateLimit = () => rateLimitOverride ?? adapter.rateLimit ?? defaultRateLimitConfig();
5586
5251
  let disposed = false;
5587
5252
  let globalAdmissionRevision = 0;
5588
5253
  const sourceAdmissionRevisions = /* @__PURE__ */ new WeakMap();
@@ -5627,8 +5292,9 @@ function createPermissionRuntime(context) {
5627
5292
  const source = [...lifetimes].find(([, lifetime2]) => lifetime2.id === request.sessionId);
5628
5293
  if (!source) return false;
5629
5294
  const [windowId, lifetime] = source;
5295
+ if (!adapter.promptRateLimiter) return true;
5630
5296
  const now2 = adapter.now();
5631
- const rate = evaluateRateLimit(adapter.promptRateLimit ?? defaultPromptRateLimitConfig(), promptRates, {
5297
+ const rate = adapter.promptRateLimiter.evaluate({
5632
5298
  subject: lifetime.subject,
5633
5299
  operation: "permission.prompt",
5634
5300
  lifecycle: lifetime.id,
@@ -5636,7 +5302,6 @@ function createPermissionRuntime(context) {
5636
5302
  focused: context.focused(windowId),
5637
5303
  now: now2
5638
5304
  });
5639
- promptRates = rate.state;
5640
5305
  if (rate.reason !== "within-budget") {
5641
5306
  try {
5642
5307
  adapter.onRateLimit?.({ windowId, operation: "permission.prompt", action: rate.action, reason: rate.reason });
@@ -5649,22 +5314,16 @@ function createPermissionRuntime(context) {
5649
5314
  const lifetime = lifetimes.get(windowId);
5650
5315
  if (disposed || !store2.available || !lifetime || retiredSources.has(lifetime.entry) || context.getSession(windowId) !== lifetime.entry) return "unavailable";
5651
5316
  try {
5317
+ if (!adapter.rateLimiter) return void 0;
5652
5318
  const now2 = adapter.now();
5653
- const configured = currentRateLimit();
5654
- const config = mode === "observe" ? {
5655
- ...configured,
5656
- action: configured.action === "block" ? "flag" : configured.action,
5657
- burst: { ...configured.burst, action: configured.burst.action === "block" ? "flag" : configured.burst.action }
5658
- } : configured;
5659
- const rate = evaluateRateLimit(config, rates, {
5319
+ const rate = adapter.rateLimiter.evaluate({
5660
5320
  subject: lifetime.subject,
5661
5321
  operation,
5662
5322
  lifecycle: lifetime.id,
5663
5323
  elapsedSinceStartMs: Math.max(0, now2 - lifetime.started),
5664
5324
  focused: context.focused(windowId),
5665
5325
  now: now2
5666
- });
5667
- rates = rate.state;
5326
+ }, mode);
5668
5327
  if (rate.reason !== "within-budget") {
5669
5328
  try {
5670
5329
  adapter.onRateLimit?.({ windowId, operation, action: rate.action, reason: rate.reason });
@@ -5682,8 +5341,12 @@ function createPermissionRuntime(context) {
5682
5341
  retiredSources.add(lifetime.entry);
5683
5342
  lifetimes.delete(windowId);
5684
5343
  store2.retire(lifetime.id);
5685
- rates = retireRateLimitLifecycle(rates, lifetime.subject, lifetime.id);
5686
- promptRates = retireRateLimitLifecycle(promptRates, lifetime.subject, lifetime.id);
5344
+ for (const limiter of [adapter.rateLimiter, adapter.promptRateLimiter]) {
5345
+ try {
5346
+ limiter?.retire(lifetime.subject, lifetime.id);
5347
+ } catch {
5348
+ }
5349
+ }
5687
5350
  }
5688
5351
  function run(windowId, operation, requirements3, isCurrent, execute, phase = "operation", signal) {
5689
5352
  if (disposed || signal?.aborted) return Promise.resolve({ status: "cancelled" });
@@ -5759,13 +5422,6 @@ function createPermissionRuntime(context) {
5759
5422
  return () => {
5760
5423
  invalidationListeners.delete(listener);
5761
5424
  };
5762
- },
5763
- get rateLimit() {
5764
- return currentRateLimit();
5765
- },
5766
- setRateLimit(config) {
5767
- assertRateLimitConfig(config);
5768
- rateLimitOverride = Object.freeze({ ...config, burst: Object.freeze({ ...config.burst }) });
5769
5425
  }
5770
5426
  };
5771
5427
  return {
@@ -7310,7 +6966,7 @@ function createRuntimeInstance(context) {
7310
6966
  for (const name of attachedServices.keys()) detachService(name);
7311
6967
  manifestCache2.persist();
7312
6968
  aclState.persist();
7313
- firewallState.persist();
6969
+ firewallState?.persist();
7314
6970
  replayDetector.clear();
7315
6971
  subscriptions.clear();
7316
6972
  incRuntime.clear();
@@ -7356,7 +7012,7 @@ function createRuntimeInstance(context) {
7356
7012
  get aclState() {
7357
7013
  return aclState;
7358
7014
  },
7359
- get firewallState() {
7015
+ get legacyFirewall() {
7360
7016
  return firewallState;
7361
7017
  },
7362
7018
  get permissions() {
@@ -7399,12 +7055,12 @@ function createRuntime(hooks) {
7399
7055
  const serviceRegistry = { ...hooks.services };
7400
7056
  const registeredServices = createRegisteredServices(serviceRegistry);
7401
7057
  const warnLegacyIgnored = hooks.permissions ? createLegacyIgnoredWarning() : void 0;
7402
- if (hooks.onFirewallEvent || hooks.firewallPersistence) warnLegacyIgnored?.();
7403
- const firewallState = createFirewallState(hooks.firewallPersistence, warnLegacyIgnored);
7058
+ if (hooks.onFirewallEvent || hooks.legacyFirewall) warnLegacyIgnored?.();
7059
+ const firewallState = hooks.permissions ? void 0 : hooks.legacyFirewall;
7404
7060
  let extensions;
7405
7061
  let permissions;
7406
7062
  const sessionRegistry2 = createSessionRegistry(hooks.onPendingUpdate, (windowId) => {
7407
- firewallState.resetInitBudget(windowId);
7063
+ firewallState?.resetInitBudget(windowId);
7408
7064
  extensions?.destroyWindow(windowId);
7409
7065
  permissions?.retire(windowId);
7410
7066
  if (hooks.permissions) notifyServiceWindowDestroyed(windowId, serviceRegistry);
@@ -7441,8 +7097,8 @@ function createRuntime(hooks) {
7441
7097
  napplet,
7442
7098
  pubkey: "",
7443
7099
  resolve: (allowed2) => {
7444
- firewallState.setPolicy(napplet, allowed2 ? "allow" : "deny");
7445
- firewallState.persist();
7100
+ firewallState?.setPolicy(napplet, allowed2 ? "allow" : "deny");
7101
+ firewallState?.persist();
7446
7102
  }
7447
7103
  });
7448
7104
  };
@@ -7487,7 +7143,7 @@ function createRuntime(hooks) {
7487
7143
  hooks.getConfigOverrides ? () => hooks.getConfigOverrides().ringBufferSize ?? RING_BUFFER_SIZE : void 0
7488
7144
  );
7489
7145
  aclState.load();
7490
- firewallState.load();
7146
+ firewallState?.load();
7491
7147
  manifestCache2.load();
7492
7148
  const domainHandlers = createRuntimeDomainHandlers({ hooks, serviceRegistry, sessionRegistry: sessionRegistry2, aclState });
7493
7149
  const napHandlers = {
@@ -16172,7 +15828,7 @@ function delay(signal) {
16172
15828
  if (signal.aborted) done();
16173
15829
  });
16174
15830
  }
16175
- async function pumpAudio(source, element4, reader, mime, signal) {
15831
+ async function pumpAudio(source, element3, reader, mime, signal) {
16176
15832
  await waitEvent(source, "sourceopen", signal);
16177
15833
  const buffer = source.addSourceBuffer(mime);
16178
15834
  while (!signal.aborted) {
@@ -16183,10 +15839,10 @@ async function pumpAudio(source, element4, reader, mime, signal) {
16183
15839
  }
16184
15840
  if (item.value.byteLength > 1024 * 1024) throw new Error("live audio chunk too large");
16185
15841
  for (let offset = 0; offset < item.value.byteLength; offset += 64 * 1024) {
16186
- while (!signal.aborted && buffer.buffered.length && buffer.buffered.end(buffer.buffered.length - 1) - element4.currentTime > 30) {
15842
+ while (!signal.aborted && buffer.buffered.length && buffer.buffered.end(buffer.buffered.length - 1) - element3.currentTime > 30) {
16187
15843
  await delay(signal);
16188
15844
  }
16189
- const cutoff = element4.currentTime - 15;
15845
+ const cutoff = element3.currentTime - 15;
16190
15846
  if (buffer.buffered.length && cutoff > buffer.buffered.start(0) + 5) {
16191
15847
  await waitEvent(buffer, "updateend", signal, () => buffer.remove(0, cutoff));
16192
15848
  }
@@ -16195,7 +15851,7 @@ async function pumpAudio(source, element4, reader, mime, signal) {
16195
15851
  }
16196
15852
  }
16197
15853
  }
16198
- function createMediaStream(response, element4, controller, urls) {
15854
+ function createMediaStream(response, element3, controller, urls) {
16199
15855
  const mime = response.headers.get("content-type") ?? "";
16200
15856
  if (!response.body || typeof MediaSource === "undefined" || !MediaSource.isTypeSupported(mime)) {
16201
15857
  void response.body?.cancel().catch(() => {
@@ -16211,11 +15867,11 @@ function createMediaStream(response, element4, controller, urls) {
16211
15867
  });
16212
15868
  };
16213
15869
  controller.signal.addEventListener("abort", cancel, { once: true });
16214
- void pumpAudio(source, element4, reader, mime, controller.signal).catch(() => {
15870
+ void pumpAudio(source, element3, reader, mime, controller.signal).catch(() => {
16215
15871
  if (!controller.signal.aborted) {
16216
15872
  controller.abort();
16217
- element4.pause();
16218
- element4.dispatchEvent(new Event("error"));
15873
+ element3.pause();
15874
+ element3.dispatchEvent(new Event("error"));
16219
15875
  }
16220
15876
  }).finally(() => {
16221
15877
  controller.signal.removeEventListener("abort", cancel);
@@ -16277,12 +15933,12 @@ function sourceUrl(options) {
16277
15933
  if (typeof source?.blossomHash === "string" && /^[a-f0-9]{64}$/i.test(source.blossomHash)) return `blossom:${source.blossomHash}`;
16278
15934
  throw new Error("unsupported source");
16279
15935
  }
16280
- function loadMedia(element4, url, signal) {
15936
+ function loadMedia(element3, url, signal) {
16281
15937
  return new Promise((resolve, reject2) => {
16282
15938
  const cleanup = () => {
16283
15939
  clearTimeout(timer);
16284
- element4.removeEventListener("loadedmetadata", loaded);
16285
- element4.removeEventListener("error", failed2);
15940
+ element3.removeEventListener("loadedmetadata", loaded);
15941
+ element3.removeEventListener("error", failed2);
16286
15942
  signal.removeEventListener("abort", failed2);
16287
15943
  };
16288
15944
  const loaded = () => {
@@ -16294,36 +15950,36 @@ function loadMedia(element4, url, signal) {
16294
15950
  reject2(new Error("media decoding failed or cancelled"));
16295
15951
  };
16296
15952
  const timer = setTimeout(failed2, 5e3);
16297
- element4.addEventListener("loadedmetadata", loaded, { once: true });
16298
- element4.addEventListener("error", failed2, { once: true });
15953
+ element3.addEventListener("loadedmetadata", loaded, { once: true });
15954
+ element3.addEventListener("error", failed2, { once: true });
16299
15955
  signal.addEventListener("abort", failed2, { once: true });
16300
15956
  if (signal.aborted) return failed2();
16301
15957
  try {
16302
- element4.src = url;
16303
- element4.load();
15958
+ element3.src = url;
15959
+ element3.load();
16304
15960
  } catch {
16305
15961
  failed2();
16306
15962
  }
16307
15963
  });
16308
15964
  }
16309
- function attachPlayback(element4, live, release, changed) {
15965
+ function attachPlayback(element3, live, release, changed) {
16310
15966
  let retired = false;
16311
15967
  let generation2 = 0;
16312
- let state = { status: "paused", position: 0, volume: element4.volume };
15968
+ let state = { status: "paused", position: 0, volume: element3.volume };
16313
15969
  const actions = () => [
16314
15970
  "play",
16315
15971
  "pause",
16316
15972
  "stop",
16317
15973
  "volume",
16318
- ...!live && Number.isFinite(element4.duration) && element4.duration > 0 ? ["seek"] : []
15974
+ ...!live && Number.isFinite(element3.duration) && element3.duration > 0 ? ["seek"] : []
16319
15975
  ];
16320
15976
  const publish = (status = state.status, reason) => {
16321
15977
  if (retired) return;
16322
15978
  state = {
16323
15979
  status,
16324
- position: element4.currentTime,
16325
- volume: element4.volume,
16326
- ...Number.isFinite(element4.duration) ? { duration: element4.duration } : {},
15980
+ position: element3.currentTime,
15981
+ volume: element3.volume,
15982
+ ...Number.isFinite(element3.duration) ? { duration: element3.duration } : {},
16327
15983
  ...reason ? { reason } : {}
16328
15984
  };
16329
15985
  changed({ ...state }, actions());
@@ -16348,9 +16004,9 @@ function attachPlayback(element4, live, release, changed) {
16348
16004
  volumechange: () => publish(),
16349
16005
  seeked: () => publish()
16350
16006
  };
16351
- for (const [event, handler] of Object.entries(handlers)) element4.addEventListener(event, handler);
16007
+ for (const [event, handler] of Object.entries(handlers)) element3.addEventListener(event, handler);
16352
16008
  return {
16353
- element: element4,
16009
+ element: element3,
16354
16010
  get state() {
16355
16011
  return { ...state };
16356
16012
  },
@@ -16362,28 +16018,28 @@ function attachPlayback(element4, live, release, changed) {
16362
16018
  const token = ++generation2;
16363
16019
  switch (command.action) {
16364
16020
  case "play":
16365
- if (live && element4.buffered.length && (element4.ended || element4.currentTime < element4.buffered.start(0))) element4.currentTime = element4.buffered.start(0);
16366
- void element4.play().then(() => {
16021
+ if (live && element3.buffered.length && (element3.ended || element3.currentTime < element3.buffered.start(0))) element3.currentTime = element3.buffered.start(0);
16022
+ void element3.play().then(() => {
16367
16023
  if (!retired && token === generation2) publish("playing", command.reason);
16368
16024
  }).catch(() => {
16369
16025
  if (!retired && token === generation2) publish("paused", "error");
16370
16026
  });
16371
16027
  break;
16372
16028
  case "pause":
16373
- element4.pause();
16029
+ element3.pause();
16374
16030
  publish("paused", command.reason);
16375
16031
  break;
16376
16032
  case "stop":
16377
- element4.pause();
16378
- if (!live) element4.currentTime = 0;
16033
+ element3.pause();
16034
+ if (!live) element3.currentTime = 0;
16379
16035
  publish("stopped", command.reason);
16380
16036
  break;
16381
16037
  case "seek":
16382
- element4.currentTime = Math.min(command.value, element4.duration);
16038
+ element3.currentTime = Math.min(command.value, element3.duration);
16383
16039
  publish();
16384
16040
  break;
16385
16041
  case "volume":
16386
- element4.volume = command.value;
16042
+ element3.volume = command.value;
16387
16043
  publish();
16388
16044
  break;
16389
16045
  }
@@ -16392,11 +16048,11 @@ function attachPlayback(element4, live, release, changed) {
16392
16048
  if (retired) return;
16393
16049
  retired = true;
16394
16050
  generation2++;
16395
- for (const [event, handler] of Object.entries(handlers)) element4.removeEventListener(event, handler);
16396
- element4.pause();
16397
- element4.removeAttribute("src");
16398
- element4.load();
16399
- element4.remove();
16051
+ for (const [event, handler] of Object.entries(handlers)) element3.removeEventListener(event, handler);
16052
+ element3.pause();
16053
+ element3.removeAttribute("src");
16054
+ element3.load();
16055
+ element3.remove();
16400
16056
  release();
16401
16057
  }
16402
16058
  };
@@ -16410,17 +16066,17 @@ function createBrowserMediaPlayback(options) {
16410
16066
  const blob = await readSource(options.resource, windowId, sourceUrl(request), signal);
16411
16067
  if (signal.aborted) throw new Error("media source cancelled");
16412
16068
  if (!/^(audio|video)\//.test(blob.type)) throw new Error("unsupported media type");
16413
- const element4 = doc.createElement(blob.type.startsWith("video/") ? "video" : "audio");
16414
- if (!element4.canPlayType(blob.type)) throw new Error("unsupported media type");
16415
- element4.preload = "metadata";
16416
- if (element4.tagName === "VIDEO") element4.playsInline = true;
16069
+ const element3 = doc.createElement(blob.type.startsWith("video/") ? "video" : "audio");
16070
+ if (!element3.canPlayType(blob.type)) throw new Error("unsupported media type");
16071
+ element3.preload = "metadata";
16072
+ if (element3.tagName === "VIDEO") element3.playsInline = true;
16417
16073
  const url = urls.createObjectURL(blob);
16418
- const playback = attachPlayback(element4, request.live === true, () => urls.revokeObjectURL(url), changed);
16074
+ const playback = attachPlayback(element3, request.live === true, () => urls.revokeObjectURL(url), changed);
16419
16075
  const abort = () => playback.destroy();
16420
16076
  signal.addEventListener("abort", abort, { once: true });
16421
16077
  try {
16422
- await loadMedia(element4, url, signal);
16423
- if (request.autoplay) await element4.play();
16078
+ await loadMedia(element3, url, signal);
16079
+ if (request.autoplay) await element3.play();
16424
16080
  if (signal.aborted) throw new Error("media source cancelled");
16425
16081
  return playback;
16426
16082
  } catch (error) {
@@ -16445,12 +16101,12 @@ async function openLive(windowId, request, signal, changed, options, doc, urls)
16445
16101
  await response.body?.cancel();
16446
16102
  throw new Error("media source cancelled");
16447
16103
  }
16448
- const element4 = doc.createElement("audio");
16449
- element4.preload = "auto";
16450
- const stream = createMediaStream(response, element4, controller, urls);
16451
- playback = attachPlayback(element4, true, stream.destroy, changed);
16452
- await loadMedia(element4, stream.url, controller.signal);
16453
- if (request.autoplay) await element4.play();
16104
+ const element3 = doc.createElement("audio");
16105
+ element3.preload = "auto";
16106
+ const stream = createMediaStream(response, element3, controller, urls);
16107
+ playback = attachPlayback(element3, true, stream.destroy, changed);
16108
+ await loadMedia(element3, stream.url, controller.signal);
16109
+ if (request.autoplay) await element3.play();
16454
16110
  if (controller.signal.aborted) throw new Error("media source cancelled");
16455
16111
  return playback;
16456
16112
  } catch (error) {
@@ -16611,8 +16267,8 @@ function updateRow(row, session, service) {
16611
16267
  row.volume.disabled = !session.actions.includes("volume");
16612
16268
  if (row.seek.getRootNode() instanceof ShadowRoot && row.seek.getRootNode().activeElement !== row.seek) row.seek.value = String(state?.position ?? 0);
16613
16269
  if (row.volume.getRootNode() instanceof ShadowRoot && row.volume.getRootNode().activeElement !== row.volume) row.volume.value = String(state?.volume ?? 1);
16614
- const element4 = service.getElement(session.sessionId);
16615
- if (element4 && element4.parentElement !== row.media) row.media.append(element4);
16270
+ const element3 = service.getElement(session.sessionId);
16271
+ if (element3 && element3.parentElement !== row.media) row.media.append(element3);
16616
16272
  }
16617
16273
  function mountMediaPlayer(service, container = document.body) {
16618
16274
  const doc = container.ownerDocument;
@@ -18772,45 +18428,149 @@ function createPajaResourceSettings(getStorage = () => localStorage) {
18772
18428
  status = "Saved resource servers could not be restored. Save to use a new list; unavailable storage means session-only changes.";
18773
18429
  }
18774
18430
  return {
18775
- getServers: () => servers,
18776
- getStatus: () => status,
18777
- save(draft) {
18778
- let next;
18779
- try {
18780
- next = normalizeDraft(draft);
18781
- } catch (error) {
18782
- return { ok: false, message: error.message };
18783
- }
18784
- servers = next;
18785
- try {
18786
- const storage = getStorage();
18787
- if (servers.length) storage.setItem(STORAGE_KEY, JSON.stringify(servers));
18788
- else storage.removeItem(STORAGE_KEY);
18789
- status = servers.length ? "Resource servers saved for this host origin." : "Extra resource servers cleared from this host origin.";
18790
- } catch {
18791
- status = "Resource servers applied session-only. Storage is unavailable; any previously saved list may return after reload.";
18792
- }
18793
- return { ok: true, message: status };
18431
+ getServers: () => servers,
18432
+ getStatus: () => status,
18433
+ save(draft) {
18434
+ let next;
18435
+ try {
18436
+ next = normalizeDraft(draft);
18437
+ } catch (error) {
18438
+ return { ok: false, message: error.message };
18439
+ }
18440
+ servers = next;
18441
+ try {
18442
+ const storage = getStorage();
18443
+ if (servers.length) storage.setItem(STORAGE_KEY, JSON.stringify(servers));
18444
+ else storage.removeItem(STORAGE_KEY);
18445
+ status = servers.length ? "Resource servers saved for this host origin." : "Extra resource servers cleared from this host origin.";
18446
+ } catch {
18447
+ status = "Resource servers applied session-only. Storage is unavailable; any previously saved list may return after reload.";
18448
+ }
18449
+ return { ok: true, message: status };
18450
+ }
18451
+ };
18452
+ }
18453
+ function installPajaResourceSettings() {
18454
+ const settings = createPajaResourceSettings();
18455
+ const form = document.getElementById("paja-resource-servers-form");
18456
+ const input = document.getElementById("paja-resource-servers-input");
18457
+ const status = document.getElementById("paja-resource-servers-status");
18458
+ input.value = settings.getServers().join("\n");
18459
+ status.textContent = settings.getStatus();
18460
+ const submit = (event) => {
18461
+ event.preventDefault();
18462
+ const result2 = settings.save(input.value);
18463
+ input.setAttribute("aria-invalid", String(!result2.ok));
18464
+ status.textContent = result2.message;
18465
+ if (result2.ok) input.value = settings.getServers().join("\n");
18466
+ };
18467
+ form?.addEventListener("submit", submit);
18468
+ return { getServers: settings.getServers, dispose: () => form?.removeEventListener("submit", submit) };
18469
+ }
18470
+
18471
+ // ../rate-limit/dist/chunk-ACC3QLIN.js
18472
+ function defaultRateLimitConfig() {
18473
+ return {
18474
+ capacity: 60,
18475
+ windowMs: 6e4,
18476
+ action: "flag",
18477
+ unfocusedMultiplier: 0.25,
18478
+ burst: { windowMs: 3e3, maxOperations: 20, action: "block" }
18479
+ };
18480
+ }
18481
+ function defaultPromptRateLimitConfig() {
18482
+ return {
18483
+ capacity: 12,
18484
+ windowMs: 6e4,
18485
+ action: "block",
18486
+ unfocusedMultiplier: 1,
18487
+ burst: { windowMs: 3e3, maxOperations: 8, action: "block" }
18488
+ };
18489
+ }
18490
+ function createRateLimitState() {
18491
+ return { buckets: {}, bursts: {} };
18492
+ }
18493
+ function positive(value) {
18494
+ return Number.isFinite(value) && value > 0;
18495
+ }
18496
+ function validAction(value) {
18497
+ return value === "flag" || value === "block" || value === "ignore";
18498
+ }
18499
+ function assertRateLimitConfig(config) {
18500
+ const { burst } = config;
18501
+ if (!Number.isFinite(config.capacity) || config.capacity < 0 || !positive(config.windowMs) || !positive(config.unfocusedMultiplier) || !Number.isFinite(burst.windowMs) || burst.windowMs < 0 || !Number.isSafeInteger(burst.maxOperations) || burst.maxOperations < 0 || !validAction(config.action) || !validAction(burst.action)) {
18502
+ throw new RangeError("Rate limits require finite budgets in range and valid actions");
18503
+ }
18504
+ }
18505
+ function validate(config, observation) {
18506
+ assertRateLimitConfig(config);
18507
+ if (!observation.subject || !observation.operation || !observation.lifecycle || !Number.isFinite(observation.now) || !Number.isFinite(observation.elapsedSinceStartMs) || observation.elapsedSinceStartMs < 0 || typeof observation.focused !== "boolean") {
18508
+ throw new RangeError("Rate observations require a subject, operation, lifecycle and finite clock");
18509
+ }
18510
+ }
18511
+ function verdict(state, reason, action) {
18512
+ return { allowed: action !== "block", action, reason, state };
18513
+ }
18514
+ function evaluateRateLimit(config, state, observation) {
18515
+ validate(config, observation);
18516
+ const { subject, operation, lifecycle, now: now2 } = observation;
18517
+ if (observation.elapsedSinceStartMs < config.burst.windowMs) {
18518
+ const key2 = JSON.stringify([subject, lifecycle]);
18519
+ const previous2 = state.bursts[key2];
18520
+ const active = previous2 && now2 - previous2.startedAt < config.burst.windowMs ? previous2 : void 0;
18521
+ const burst = { count: (active?.count ?? 0) + 1, startedAt: active?.startedAt ?? now2 };
18522
+ state = { ...state, bursts: { ...state.bursts, [key2]: burst } };
18523
+ if (burst.count > config.burst.maxOperations) return verdict(state, "burst-exceeded", config.burst.action);
18524
+ }
18525
+ const key = JSON.stringify([subject, operation]);
18526
+ const capacity = config.capacity * (observation.focused ? 1 : config.unfocusedMultiplier);
18527
+ const previous = state.buckets[key];
18528
+ const updatedAt = Math.max(now2, previous?.updatedAt ?? now2);
18529
+ const elapsed = updatedAt - (previous?.updatedAt ?? updatedAt);
18530
+ const tokens = Math.min(capacity, (previous?.tokens ?? capacity) + elapsed * (capacity / config.windowMs));
18531
+ const exceeded = tokens < 1;
18532
+ const bucket = { tokens: exceeded ? tokens : tokens - 1, updatedAt };
18533
+ state = { ...state, buckets: { ...state.buckets, [key]: bucket } };
18534
+ return verdict(state, exceeded ? "rate-exceeded" : "within-budget", exceeded ? config.action : "ignore");
18535
+ }
18536
+ function retireRateLimitLifecycle(state, subject, lifecycle) {
18537
+ const key = JSON.stringify([subject, lifecycle]);
18538
+ if (!Object.hasOwn(state.bursts, key)) return state;
18539
+ const bursts = { ...state.bursts };
18540
+ delete bursts[key];
18541
+ return { ...state, bursts };
18542
+ }
18543
+
18544
+ // ../rate-limit/dist/index.js
18545
+ function snapshot3(config) {
18546
+ assertRateLimitConfig(config);
18547
+ return Object.freeze({ ...config, burst: Object.freeze({ ...config.burst }) });
18548
+ }
18549
+ function createRateLimiter(initial) {
18550
+ let config = snapshot3(initial);
18551
+ let state = createRateLimitState();
18552
+ return {
18553
+ get config() {
18554
+ return config;
18555
+ },
18556
+ setConfig(next) {
18557
+ config = snapshot3(next);
18558
+ },
18559
+ evaluate(observation, mode = "enforce") {
18560
+ const effective = mode === "observe" ? {
18561
+ ...config,
18562
+ action: config.action === "block" ? "flag" : config.action,
18563
+ burst: { ...config.burst, action: config.burst.action === "block" ? "flag" : config.burst.action }
18564
+ } : config;
18565
+ const result2 = evaluateRateLimit(effective, state, observation);
18566
+ state = result2.state;
18567
+ return result2;
18568
+ },
18569
+ retire(subject, lifecycle) {
18570
+ state = retireRateLimitLifecycle(state, subject, lifecycle);
18794
18571
  }
18795
18572
  };
18796
18573
  }
18797
- function installPajaResourceSettings() {
18798
- const settings = createPajaResourceSettings();
18799
- const form = document.getElementById("paja-resource-servers-form");
18800
- const input = document.getElementById("paja-resource-servers-input");
18801
- const status = document.getElementById("paja-resource-servers-status");
18802
- input.value = settings.getServers().join("\n");
18803
- status.textContent = settings.getStatus();
18804
- const submit = (event) => {
18805
- event.preventDefault();
18806
- const result2 = settings.save(input.value);
18807
- input.setAttribute("aria-invalid", String(!result2.ok));
18808
- status.textContent = result2.message;
18809
- if (result2.ok) input.value = settings.getServers().join("\n");
18810
- };
18811
- form?.addEventListener("submit", submit);
18812
- return { getServers: settings.getServers, dispose: () => form?.removeEventListener("submit", submit) };
18813
- }
18814
18574
 
18815
18575
  // ../shell/dist/index.js
18816
18576
  function randomUUID() {
@@ -19144,7 +18904,7 @@ function adaptHooks(shellHooks, deps) {
19144
18904
  shellSecretPersistence: createShellSecretPersistence(),
19145
18905
  guidPersistence: createGuidPersistence(),
19146
18906
  onAclCheck: shellHooks.onAclCheck,
19147
- firewallPersistence: shellHooks.firewallPersistence,
18907
+ legacyFirewall: shellHooks.legacyFirewall,
19148
18908
  onFirewallEvent: shellHooks.onFirewallEvent,
19149
18909
  getFocusContext: shellHooks.getFocusContext,
19150
18910
  onHashMismatch: shellHooks.onHashMismatch,
@@ -20837,11 +20597,11 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2, frameLock) {
20837
20597
  post({ type: "shell.ready" });
20838
20598
  return shell2;
20839
20599
  }
20840
- function domainEventHandle(eventType, callback, select2 = (message3) => message3.event) {
20600
+ function domainEventHandle(eventType, callback, select22 = (message3) => message3.event) {
20841
20601
  const off = listen((event) => {
20842
20602
  if (!isShellMessage(event)) return;
20843
20603
  const msg = event.data;
20844
- if (typeof msg === "object" && msg !== null && msg.type === eventType) callback(select2(msg));
20604
+ if (typeof msg === "object" && msg !== null && msg.type === eventType) callback(select22(msg));
20845
20605
  });
20846
20606
  return subscriptionHandle(off);
20847
20607
  }
@@ -21996,9 +21756,9 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2, frameLock) {
21996
21756
  const incoming = event.data;
21997
21757
  if (!incoming || incoming.type !== "gamepad.state" || "id" in incoming || !valid(incoming)) return;
21998
21758
  state = copy(incoming);
21999
- const snapshot3 = copy(state);
21759
+ const snapshot4 = copy(state);
22000
21760
  const recipients = Array.from(handlers);
22001
- for (const entry of recipients) if (handlers.has(entry)) entry.handler(copy(snapshot3));
21761
+ for (const entry of recipients) if (handlers.has(entry)) entry.handler(copy(snapshot4));
22002
21762
  });
22003
21763
  const api = {
22004
21764
  get available() {
@@ -22457,109 +22217,266 @@ async function admitBrowserDocument(request) {
22457
22217
  return failed2("invalid");
22458
22218
  }
22459
22219
  }
22460
- var MAX_PENDING_PROMPTS = 64;
22461
- function element(document2, tag, text2) {
22220
+ var LIFETIME_LABELS = Object.freeze({
22221
+ once: "Just this once",
22222
+ session: "Until it closes",
22223
+ persistent: "Always"
22224
+ });
22225
+ var RULE_ACTION_LABELS = Object.freeze({
22226
+ allow: "Allow",
22227
+ ask: "Ask",
22228
+ deny: "Block"
22229
+ });
22230
+ var OPERATION_LABELS = Object.freeze({
22231
+ "link.open": "Open link",
22232
+ "keys.registerAction": "Register shortcut",
22233
+ "resource.bytes": "Fetch",
22234
+ "upload.upload": "Upload to",
22235
+ "intent.invoke": "Invoke intent",
22236
+ "serial.open": "Open serial port",
22237
+ "serial.write": "Write to serial port",
22238
+ "webrtc.open": "Open peer connection"
22239
+ });
22240
+ var PROMPT_TITLES = Object.freeze({
22241
+ "link.open": "Open an external link?",
22242
+ "upload.upload": "Upload a file?",
22243
+ "intent.invoke": "Hand off to another napplet?"
22244
+ });
22245
+ function principalIdentity(principal) {
22246
+ return principal.kind === "verified" ? `Verified manifest ${principal.manifestKey}; artifact SHA-256 ${principal.artifactHash}` : `Development target ${principal.target}; artifact SHA-256 ${principal.artifactHash}`;
22247
+ }
22248
+ function shorten(value, head = 8, tail = 6) {
22249
+ return value.length > head + tail + 1 ? `${value.slice(0, head)}\u2026${value.slice(-tail)}` : value;
22250
+ }
22251
+ function principalSummary(principal) {
22252
+ const artifact = `artifact ${shorten(principal.artifactHash)}`;
22253
+ if (principal.kind === "development") return `${principal.target} \xB7 ${artifact}`;
22254
+ const parts = principal.manifestKey.split(":");
22255
+ const manifest = parts.length >= 3 ? `${parts[1]}:${shorten(parts[2])}${parts.length > 3 ? `:${parts.slice(3).join(":")}` : ""}` : principal.manifestKey;
22256
+ return `${manifest} \xB7 ${artifact}`;
22257
+ }
22258
+ function describeRequirement(requirement) {
22259
+ if (requirement.category === "interface") return { action: `Use the ${requirement.domain} interface` };
22260
+ const value = requirement.scope.value;
22261
+ if (requirement.category === "network" && requirement.operation.startsWith("network.")) {
22262
+ return { action: `Connect directly (${requirement.operation.slice("network.".length)})`, target: value };
22263
+ }
22264
+ const action = OPERATION_LABELS[requirement.operation] ?? requirement.operation;
22265
+ if (requirement.category === "network") return { action: `${action} \u2014 contact origin`, target: value };
22266
+ if (requirement.scope.kind === "directory") return { action: `${action} \u2014 folder`, target: value };
22267
+ const prefix = `${requirement.domain}:`;
22268
+ return { action, target: value.startsWith(prefix) ? value.slice(prefix.length).replace(":", " ") : value };
22269
+ }
22270
+ function distinct(values) {
22271
+ return [...new Set(values)];
22272
+ }
22273
+ var DIRECT = "network.";
22274
+ function describeRequirements(missing) {
22275
+ const rows = [];
22276
+ const direct = /* @__PURE__ */ new Map();
22277
+ for (const item of missing) {
22278
+ if (item.category !== "network" || !item.operation.startsWith(DIRECT)) {
22279
+ rows.push(describeRequirement(item));
22280
+ continue;
22281
+ }
22282
+ const directives = direct.get(item.scope.value);
22283
+ if (directives) directives.push(item.operation.slice(DIRECT.length));
22284
+ else direct.set(item.scope.value, [item.operation.slice(DIRECT.length)]);
22285
+ }
22286
+ return [...rows, ...[...direct].map(([target, directives]) => ({ action: `Connect directly (${distinct(directives).join(", ")})`, target }))];
22287
+ }
22288
+ function promptTitle(missing) {
22289
+ const operations = distinct(missing.filter((item) => item.category !== "interface").map((item) => item.operation));
22290
+ if (operations.length && operations.every((operation) => operation.startsWith(DIRECT))) return "Allow direct network access?";
22291
+ if (operations.length === 1) return PROMPT_TITLES[operations[0]] ?? `Allow ${operations[0]}?`;
22292
+ if (operations.length > 1) return `Allow ${operations.length} operations?`;
22293
+ const domains = distinct(missing.map((item) => item.domain));
22294
+ return domains.length === 1 ? `Allow access to ${domains[0]}?` : `Allow access to ${domains.length} interfaces?`;
22295
+ }
22296
+ function ruleTargetFor(missing) {
22297
+ const domains = distinct(missing.map((item) => item.domain));
22298
+ if (domains.length !== 1) return void 0;
22299
+ const operations = distinct(missing.filter((item) => item.category !== "interface").map((item) => item.operation));
22300
+ if (operations.length === 1 && missing.every((item) => item.category !== "interface")) return { operation: operations[0] };
22301
+ return { domain: domains[0] };
22302
+ }
22303
+ function isRuleGrant(grant2) {
22304
+ return grant2.id.startsWith(DEFAULT_RULE_GRANT_PREFIX);
22305
+ }
22306
+ function groupGrants(grants) {
22307
+ const groups = /* @__PURE__ */ new Map();
22308
+ for (const grant2 of grants) {
22309
+ const key = `${permissionRuleSubject(grant2.principal)}#${grant2.principal.artifactHash}`;
22310
+ let group = groups.get(key);
22311
+ if (!group) groups.set(key, group = { principal: grant2.principal, decided: /* @__PURE__ */ new Map(), byRule: [] });
22312
+ if (isRuleGrant(grant2)) {
22313
+ group.byRule.push(grant2);
22314
+ continue;
22315
+ }
22316
+ const domain = group.decided.get(grant2.permission.domain);
22317
+ if (domain) domain.push(grant2);
22318
+ else group.decided.set(grant2.permission.domain, [grant2]);
22319
+ }
22320
+ return [...groups].map(([key, group]) => ({
22321
+ key,
22322
+ principal: group.principal,
22323
+ byRule: group.byRule,
22324
+ decided: [...group.decided].map(([domain, list]) => ({ domain, grants: list }))
22325
+ }));
22326
+ }
22327
+ function parseCapability(text2) {
22328
+ const value = text2.trim();
22329
+ if (/^[a-z][a-z0-9-]*$/.test(value)) return { domain: value };
22330
+ if (/^[a-z][a-z0-9-]*\.[A-Za-z0-9][A-Za-z0-9._-]*$/.test(value)) return { operation: value };
22331
+ return void 0;
22332
+ }
22333
+ function element(document2, tag, text2, className) {
22462
22334
  const node = document2.createElement(tag);
22463
22335
  if (text2 !== void 0) node.textContent = text2;
22336
+ if (className) node.className = className;
22464
22337
  return node;
22465
22338
  }
22466
- function principalIdentity(principal) {
22467
- return principal.kind === "verified" ? `Verified manifest ${principal.manifestKey}; artifact SHA-256 ${principal.artifactHash}` : `Development target ${principal.target}; artifact SHA-256 ${principal.artifactHash}`;
22339
+ function select2(document2, label, options, value) {
22340
+ const node = element(document2, "select");
22341
+ node.setAttribute("aria-label", label);
22342
+ for (const [optionValue, text2] of options) {
22343
+ const option = element(document2, "option", text2);
22344
+ option.value = optionValue;
22345
+ node.append(option);
22346
+ }
22347
+ node.value = value;
22348
+ return node;
22468
22349
  }
22469
- function createBrowserApprovalPrompt(document2, labelForPrincipal) {
22470
- const dialog = element(document2, "dialog");
22350
+ var MAX_PENDING_PROMPTS = 64;
22351
+ var NETWORK_NOTE = "Direct browser traffic to these origins is outside parent mediation and rate limits. Browser rules may also allow HTTP to HTTPS upgrades and WebSocket origins to match HTTP(S); hosts and port restrictions still apply, but default ports may upgrade with the scheme.";
22352
+ var CANCELLED2 = Object.freeze({ answer: Object.freeze({ effect: "cancel" }), asRule: false, userGesture: false });
22353
+ function buildDialog(document2) {
22354
+ const dialog = element(document2, "dialog", void 0, "kehto-approval-dialog");
22471
22355
  dialog.setAttribute("aria-labelledby", "kehto-approval-title");
22472
22356
  dialog.setAttribute("aria-describedby", "kehto-approval-description");
22473
- const title = element(document2, "h2", "Permission request");
22357
+ const eyebrow = element(document2, "p", void 0, "kehto-approval-eyebrow");
22358
+ const title = element(document2, "h2");
22474
22359
  title.id = "kehto-approval-title";
22475
- const description = element(document2, "p");
22360
+ const description = element(document2, "p", void 0, "kehto-approval-who");
22476
22361
  description.id = "kehto-approval-description";
22477
- const identity = element(document2, "p");
22478
- const requirements3 = element(document2, "ul");
22479
- const mediation = element(document2, "p");
22480
- const lifetimeLabel = element(document2, "label", "Allow for");
22481
- const lifetime = element(document2, "select");
22482
- lifetimeLabel.append(lifetime);
22483
- const actions = element(document2, "div");
22362
+ const requirements3 = element(document2, "ul", void 0, "kehto-approval-scopes");
22363
+ const mediation = element(document2, "p", void 0, "kehto-approval-note");
22364
+ const identity = element(document2, "details", void 0, "kehto-approval-identity");
22365
+ const identityText = element(document2, "p");
22366
+ identity.append(element(document2, "summary", "Technical identity"), identityText);
22367
+ const remember = element(document2, "div", void 0, "kehto-approval-remember");
22368
+ remember.setAttribute("role", "group");
22369
+ remember.setAttribute("aria-label", "Remember this decision");
22370
+ const rule = element(document2, "label", void 0, "kehto-approval-rule");
22371
+ const ruleBox = element(document2, "input");
22372
+ ruleBox.type = "checkbox";
22373
+ const ruleText = element(document2, "span");
22374
+ rule.append(ruleBox, ruleText);
22375
+ const actions = element(document2, "div", void 0, "kehto-approval-actions");
22484
22376
  const deny = element(document2, "button", "Deny");
22485
22377
  deny.type = "button";
22486
- const cancel = element(document2, "button", "Cancel");
22487
- cancel.type = "button";
22488
- const allow = element(document2, "button", "Allow");
22378
+ const allow = element(document2, "button", "Allow", "kehto-approval-primary");
22489
22379
  allow.type = "button";
22490
- actions.append(deny, cancel, allow);
22491
- dialog.append(title, description, identity, requirements3, mediation, lifetimeLabel, actions);
22380
+ actions.append(deny, allow);
22381
+ dialog.append(eyebrow, title, description, requirements3, mediation, identity, remember, rule, actions);
22382
+ return { dialog, eyebrow, title, description, requirements: requirements3, mediation, identityText, remember, rule, ruleBox, ruleText, deny, allow };
22383
+ }
22384
+ function createBrowserApprovalPrompt(document2, labelForPrincipal, offersRule = () => false) {
22385
+ const view = buildDialog(document2);
22386
+ const { dialog, deny, allow } = view;
22492
22387
  const queue = [];
22493
22388
  let finishActive;
22494
22389
  let destroyed = false;
22390
+ function showQueue() {
22391
+ view.eyebrow.textContent = queue.length ? `Permission request \xB7 ${queue.length} more waiting` : "Permission request";
22392
+ }
22393
+ function fill(request) {
22394
+ const principal = request.request.principal;
22395
+ view.title.textContent = promptTitle(request.missing);
22396
+ view.description.replaceChildren(
22397
+ element(document2, "strong", labelForPrincipal(principal)),
22398
+ element(document2, "span", principal.kind === "verified" ? "verified" : "development", "kehto-approval-badge"),
22399
+ element(document2, "span", " is asking to:")
22400
+ );
22401
+ view.identityText.textContent = principalIdentity(principal);
22402
+ view.requirements.replaceChildren(...describeRequirements(request.missing).map((text2) => {
22403
+ const row = element(document2, "li");
22404
+ row.append(element(document2, "span", text2.action));
22405
+ if (text2.target !== void 0) row.append(element(document2, "code", text2.target));
22406
+ return row;
22407
+ }));
22408
+ view.mediation.textContent = request.missing.some((item) => item.category === "network" && item.operation.startsWith("network.")) ? NETWORK_NOTE : "The parent mediates and limits this operation.";
22409
+ const target = offersRule() ? ruleTargetFor(request.missing) : void 0;
22410
+ view.rule.hidden = !target;
22411
+ view.ruleBox.checked = false;
22412
+ view.ruleText.textContent = target ? `Do this for every future ${target.operation ?? `${target.domain} interface`} request from this napplet` : "";
22413
+ }
22495
22414
  function present(request) {
22496
- description.textContent = `Requested by ${labelForPrincipal(request.request.principal)}.`;
22497
- identity.textContent = principalIdentity(request.request.principal);
22498
- requirements3.replaceChildren(...request.missing.map((item) => element(
22499
- document2,
22500
- "li",
22501
- `${item.category} ${item.operation} ${item.scope.kind}:${item.scope.value}`
22502
- )));
22503
- mediation.textContent = request.missing.some((item) => item.category === "network" && item.operation.startsWith("network.")) ? "Direct browser traffic to these origins is outside parent mediation and rate limits. Browser rules may also allow HTTP to HTTPS upgrades and WebSocket origins to match HTTP(S); hosts and port restrictions still apply, but default ports may upgrade with the scheme." : "The parent mediates and limits this operation.";
22504
- lifetime.replaceChildren(element(document2, "option", "Choose a lifetime"));
22505
- lifetime.options[0].value = "";
22506
- for (const offered of request.allowLifetimes) {
22507
- const choice = element(document2, "option", offered);
22508
- choice.value = offered;
22509
- lifetime.append(choice);
22510
- }
22511
- lifetime.value = "";
22512
- allow.disabled = true;
22415
+ fill(request);
22416
+ showQueue();
22417
+ let selected = request.allowLifetimes[0];
22418
+ const choices = request.allowLifetimes.map((lifetime) => {
22419
+ const choice = element(document2, "button", LIFETIME_LABELS[lifetime]);
22420
+ choice.type = "button";
22421
+ choice.value = lifetime;
22422
+ return choice;
22423
+ });
22424
+ const mark = () => {
22425
+ for (const choice of choices) {
22426
+ choice.setAttribute("aria-pressed", String(choice.value === selected));
22427
+ choice.disabled = view.ruleBox.checked;
22428
+ }
22429
+ };
22430
+ view.remember.replaceChildren(element(document2, "span", "Remember"), ...choices);
22431
+ view.remember.hidden = choices.length === 0;
22432
+ allow.disabled = selected === void 0;
22433
+ mark();
22513
22434
  const priorFocus = document2.activeElement;
22514
22435
  return new Promise((resolve) => {
22515
22436
  let settled = false;
22516
- const finish = (answer) => {
22437
+ const listeners = [];
22438
+ const listen = (target, type, listener) => {
22439
+ target.addEventListener(type, listener);
22440
+ listeners.push(() => target.removeEventListener(type, listener));
22441
+ };
22442
+ const finish = (result2) => {
22517
22443
  if (settled) return;
22518
22444
  settled = true;
22519
22445
  finishActive = void 0;
22520
- request.signal.removeEventListener("abort", onAbort);
22521
- deny.removeEventListener("click", onDeny);
22522
- cancel.removeEventListener("click", onCancel);
22523
- allow.removeEventListener("click", onAllow);
22524
- lifetime.removeEventListener("change", onLifetime);
22525
- dialog.removeEventListener("cancel", onDialogCancel);
22526
- dialog.removeEventListener("close", onDialogClose);
22446
+ for (const remove of listeners.splice(0)) remove();
22527
22447
  if (dialog.open) dialog.close();
22528
22448
  if (priorFocus && "focus" in priorFocus && priorFocus.isConnected) {
22529
22449
  priorFocus.focus();
22530
22450
  }
22531
- resolve(answer);
22532
- };
22533
- const onAbort = () => finish({ effect: "cancel" });
22534
- const onDeny = () => finish({ effect: "deny", lifetime: "once" });
22535
- const onCancel = () => finish({ effect: "cancel" });
22536
- const onAllow = () => {
22537
- const selected = request.allowLifetimes.find((item) => item === lifetime.value);
22538
- if (selected) finish({ effect: "allow", lifetime: selected });
22539
- };
22540
- const onLifetime = () => {
22541
- allow.disabled = !request.allowLifetimes.includes(lifetime.value);
22542
- };
22543
- const onDialogCancel = (event) => {
22544
- event.preventDefault();
22545
- finish({ effect: "cancel" });
22546
- };
22547
- const onDialogClose = () => {
22548
- if (!dialog.open) finish({ effect: "cancel" });
22451
+ resolve(result2);
22549
22452
  };
22550
22453
  finishActive = finish;
22454
+ const onAbort = () => finish(CANCELLED2);
22551
22455
  request.signal.addEventListener("abort", onAbort, { once: true });
22552
- deny.addEventListener("click", onDeny);
22553
- cancel.addEventListener("click", onCancel);
22554
- allow.addEventListener("click", onAllow);
22555
- lifetime.addEventListener("change", onLifetime);
22556
- dialog.addEventListener("cancel", onDialogCancel);
22557
- dialog.addEventListener("close", onDialogClose);
22456
+ listeners.push(() => request.signal.removeEventListener("abort", onAbort));
22457
+ listen(deny, "click", (event) => finish({ answer: { effect: "deny", lifetime: "once" }, asRule: view.ruleBox.checked, userGesture: event.isTrusted }));
22458
+ listen(allow, "click", (event) => {
22459
+ const asRule = view.ruleBox.checked;
22460
+ const lifetime = asRule && request.allowLifetimes.includes("session") ? "session" : selected;
22461
+ if (lifetime) finish({ answer: { effect: "allow", lifetime }, asRule, userGesture: event.isTrusted });
22462
+ });
22463
+ for (const choice of choices) listen(choice, "click", () => {
22464
+ selected = choice.value;
22465
+ mark();
22466
+ });
22467
+ listen(view.ruleBox, "change", mark);
22468
+ listen(dialog, "cancel", (event) => {
22469
+ event.preventDefault();
22470
+ finish(CANCELLED2);
22471
+ });
22472
+ listen(dialog, "close", () => {
22473
+ if (!dialog.open) finish(CANCELLED2);
22474
+ });
22558
22475
  try {
22559
22476
  dialog.showModal();
22560
22477
  deny.focus();
22561
22478
  } catch {
22562
- finish({ effect: "cancel" });
22479
+ finish(CANCELLED2);
22563
22480
  }
22564
22481
  });
22565
22482
  }
@@ -22569,99 +22486,346 @@ function createBrowserApprovalPrompt(document2, labelForPrincipal) {
22569
22486
  if (!next) return;
22570
22487
  next.request.signal.removeEventListener("abort", next.onAbort);
22571
22488
  if (next.request.signal.aborted) {
22572
- next.resolve({ effect: "cancel" });
22489
+ next.resolve(CANCELLED2);
22573
22490
  pump();
22574
22491
  return;
22575
22492
  }
22576
- void present(next.request).then((answer) => {
22577
- next.resolve(answer);
22493
+ void present(next.request).then((result2) => {
22494
+ next.resolve(result2);
22578
22495
  pump();
22579
22496
  });
22580
22497
  }
22581
22498
  function prompt(request) {
22582
22499
  if (destroyed || request.signal.aborted || queue.length + Number(!!finishActive) >= MAX_PENDING_PROMPTS) {
22583
- return Promise.resolve({ effect: "cancel" });
22500
+ return Promise.resolve(CANCELLED2);
22584
22501
  }
22585
22502
  return new Promise((resolve) => {
22586
- const onAbort = () => {
22587
- const index = queue.findIndex((item) => item.onAbort === onAbort);
22588
- if (index < 0) return;
22589
- queue.splice(index, 1);
22590
- resolve({ effect: "cancel" });
22503
+ const queued = {
22504
+ request,
22505
+ resolve,
22506
+ onAbort: () => {
22507
+ const index = queue.indexOf(queued);
22508
+ if (index < 0) return;
22509
+ queue.splice(index, 1);
22510
+ showQueue();
22511
+ resolve(CANCELLED2);
22512
+ }
22591
22513
  };
22592
- request.signal.addEventListener("abort", onAbort, { once: true });
22593
- queue.push({ request, resolve, onAbort });
22514
+ request.signal.addEventListener("abort", queued.onAbort, { once: true });
22515
+ queue.push(queued);
22516
+ showQueue();
22594
22517
  pump();
22595
22518
  });
22596
22519
  }
22597
22520
  function destroy() {
22598
22521
  destroyed = true;
22599
- finishActive?.({ effect: "cancel" });
22600
- for (const next of queue.splice(0)) {
22601
- next.request.signal.removeEventListener("abort", next.onAbort);
22602
- next.resolve({ effect: "cancel" });
22522
+ finishActive?.(CANCELLED2);
22523
+ for (const queued of queue.splice(0)) {
22524
+ queued.request.signal.removeEventListener("abort", queued.onAbort);
22525
+ queued.resolve(CANCELLED2);
22603
22526
  }
22604
22527
  }
22605
22528
  return { dialog, prompt, destroy };
22606
22529
  }
22607
- function element2(document2, tag, text2) {
22608
- const node = document2.createElement(tag);
22609
- if (text2 !== void 0) node.textContent = text2;
22610
- return node;
22530
+ var SHORT_LIFETIME = Object.freeze({
22531
+ once: "once",
22532
+ session: "session",
22533
+ persistent: "always"
22534
+ });
22535
+ function createGrantList(document2, options) {
22536
+ const root = element(document2, "div", void 0, "kehto-fw-grants");
22537
+ const closedNapplets = /* @__PURE__ */ new Set();
22538
+ const openRows = /* @__PURE__ */ new Set();
22539
+ function icon(glyph, label, grants) {
22540
+ const node = element(document2, "button", glyph, "kehto-fw-icon");
22541
+ node.type = "button";
22542
+ node.title = label;
22543
+ node.setAttribute("aria-label", label);
22544
+ node.addEventListener("click", (event) => {
22545
+ event.preventDefault();
22546
+ event.stopPropagation();
22547
+ options.revoke(grants);
22548
+ });
22549
+ return node;
22550
+ }
22551
+ function track(details, key, open, invert2) {
22552
+ details.open = open.has(key) !== invert2;
22553
+ details.addEventListener("toggle", () => {
22554
+ if (details.open !== invert2) open.add(key);
22555
+ else open.delete(key);
22556
+ });
22557
+ }
22558
+ function dot(effect) {
22559
+ const node = element(document2, "span", void 0, `kehto-fw-dot kehto-fw-${effect}`);
22560
+ node.setAttribute("aria-hidden", "true");
22561
+ return node;
22562
+ }
22563
+ function effectOf(grants) {
22564
+ const denied2 = grants.filter((grant2) => grant2.effect === "deny").length;
22565
+ return denied2 === 0 ? "allow" : denied2 === grants.length ? "deny" : "mixed";
22566
+ }
22567
+ function grantRow(group, grant2) {
22568
+ const text2 = describeRequirement(grant2.permission);
22569
+ const scope = grant2.permission.scope;
22570
+ const details = element(document2, "details", void 0, "kehto-fw-grant");
22571
+ track(details, `${group.key}#${grant2.id}`, openRows, false);
22572
+ const row = element(document2, "summary", void 0, "kehto-fw-row");
22573
+ row.append(dot(grant2.effect), element(document2, "span", text2.action, "kehto-fw-name"));
22574
+ if (text2.target !== void 0) row.append(element(document2, "code", text2.target));
22575
+ row.append(
22576
+ element(document2, "small", SHORT_LIFETIME[grant2.lifetime]),
22577
+ icon("\xD7", `Revoke ${grant2.permission.operation} ${scope.kind}:${scope.value}`, [grant2])
22578
+ );
22579
+ const more = element(document2, "p", void 0, "kehto-fw-more");
22580
+ more.append(
22581
+ element(document2, "span", `${grant2.effect === "allow" ? "Allowed" : "Blocked"} \xB7 ${LIFETIME_LABELS[grant2.lifetime]}`),
22582
+ element(document2, "code", `${grant2.permission.operation} ${scope.kind}:${scope.value}`)
22583
+ );
22584
+ details.append(row, more);
22585
+ return details;
22586
+ }
22587
+ function nappletGroup(group) {
22588
+ const label = options.labelForPrincipal(group.principal);
22589
+ const all = [...group.decided.flatMap((domain) => domain.grants), ...group.byRule];
22590
+ const details = element(document2, "details", void 0, "kehto-fw-napplet");
22591
+ track(details, group.key, closedNapplets, true);
22592
+ const summary = element(document2, "summary", void 0, "kehto-fw-row");
22593
+ summary.append(
22594
+ dot(effectOf(all)),
22595
+ element(document2, "strong", label, "kehto-fw-name"),
22596
+ element(document2, "span", group.principal.kind === "verified" ? "verified" : "dev", "kehto-approval-badge"),
22597
+ element(document2, "small", String(all.length)),
22598
+ icon("\xD7", `Revoke every grant for ${label}`, all)
22599
+ );
22600
+ const identity = element(document2, "p", principalSummary(group.principal), "kehto-fw-identity");
22601
+ identity.title = principalIdentity(group.principal);
22602
+ details.append(summary, identity);
22603
+ if (group.byRule.length) {
22604
+ const byRule = element(document2, "div", void 0, "kehto-fw-row kehto-fw-by-rule");
22605
+ byRule.append(
22606
+ dot("allow"),
22607
+ element(document2, "span", `${group.byRule.length} allowed by default rules`, "kehto-fw-name"),
22608
+ element(document2, "small", "session"),
22609
+ icon("\u21BA", `Reset default-rule grants for ${label}`, group.byRule)
22610
+ );
22611
+ details.append(byRule);
22612
+ }
22613
+ for (const domain of group.decided) {
22614
+ const section = element(document2, "details", void 0, "kehto-fw-domain");
22615
+ track(section, `${group.key}#${domain.domain}`, openRows, false);
22616
+ const heading = element(document2, "summary", void 0, "kehto-fw-row");
22617
+ heading.append(
22618
+ dot(effectOf(domain.grants)),
22619
+ element(document2, "code", domain.domain, "kehto-fw-name"),
22620
+ element(document2, "small", String(domain.grants.length)),
22621
+ icon("\xD7", `Revoke all ${domain.domain} decisions for ${label}`, domain.grants)
22622
+ );
22623
+ section.append(heading, ...domain.grants.map((grant2) => grantRow(group, grant2)));
22624
+ details.append(section);
22625
+ }
22626
+ return details;
22627
+ }
22628
+ function render(grants) {
22629
+ const groups = groupGrants(grants);
22630
+ root.replaceChildren(...groups.length ? groups.map(nappletGroup) : [element(document2, "p", "No grants yet.", "kehto-fw-hint")]);
22631
+ }
22632
+ return { root, render };
22633
+ }
22634
+ var ACTIONS = ["allow", "ask", "deny"].map((action) => [action, RULE_ACTION_LABELS[action]]);
22635
+ var EVERY_NAPPLET = "";
22636
+ function scopeRows(scope, napplet) {
22637
+ const base = napplet === void 0 ? {} : { napplet };
22638
+ return [
22639
+ ...napplet !== void 0 && scope.default !== void 0 ? [{ target: base, action: scope.default }] : [],
22640
+ ...Object.entries(scope.domains).map(([domain, action]) => ({ target: { ...base, domain }, action })),
22641
+ ...Object.entries(scope.operations).map(([operation, action]) => ({ target: { ...base, operation }, action }))
22642
+ ];
22643
+ }
22644
+ function capabilityText(target) {
22645
+ return target.operation ?? (target.domain !== void 0 ? `${target.domain}.*` : "Everything");
22646
+ }
22647
+ function createRulesEditor(document2, options) {
22648
+ const root = element(document2, "section", void 0, "kehto-fw-rules");
22649
+ root.setAttribute("aria-label", "Default rules");
22650
+ const head = element(document2, "div", void 0, "kehto-fw-head");
22651
+ const title = element(document2, "h3", "Default rules");
22652
+ title.title = "Used when no grant covers a request. The most specific rule wins. Tightening a rule stops napplets that relied on it.";
22653
+ const list = element(document2, "ul", void 0, "kehto-fw-rule-list");
22654
+ const form = element(document2, "form", void 0, "kehto-fw-rule-add");
22655
+ const scope = element(document2, "select");
22656
+ scope.setAttribute("aria-label", "Rule applies to");
22657
+ const capability = element(document2, "input");
22658
+ capability.type = "text";
22659
+ capability.setAttribute("aria-label", "Interface or operation");
22660
+ capability.setAttribute("placeholder", "link or link.open");
22661
+ capability.setAttribute("list", "kehto-fw-capabilities");
22662
+ capability.setAttribute("autocomplete", "off");
22663
+ capability.setAttribute("spellcheck", "false");
22664
+ const suggestions = element(document2, "datalist");
22665
+ suggestions.id = "kehto-fw-capabilities";
22666
+ const action = select2(document2, "Rule action", ACTIONS, "ask");
22667
+ const add = element(document2, "button", "+", "kehto-fw-icon");
22668
+ add.type = "submit";
22669
+ add.title = "Add rule";
22670
+ add.setAttribute("aria-label", "Add rule");
22671
+ form.append(capability, suggestions, scope, action, add);
22672
+ const error = element(document2, "p", void 0, "kehto-fw-error");
22673
+ error.setAttribute("role", "alert");
22674
+ const restore = element(document2, "button", "\u21BA", "kehto-fw-icon");
22675
+ restore.type = "button";
22676
+ restore.title = "Restore defaults";
22677
+ restore.setAttribute("aria-label", "Restore defaults");
22678
+ head.append(title, restore);
22679
+ root.append(head, list, form, error);
22680
+ function apply(next) {
22681
+ try {
22682
+ options.rules.set(next());
22683
+ error.textContent = "";
22684
+ } catch {
22685
+ error.textContent = "That rule could not be saved.";
22686
+ }
22687
+ options.onChange();
22688
+ }
22689
+ function row(label, capabilityLabel, entry, removable) {
22690
+ const item = element(document2, "li", void 0, "kehto-fw-row");
22691
+ const state = element(document2, "span", void 0, `kehto-fw-dot kehto-fw-${entry.action}`);
22692
+ state.setAttribute("aria-hidden", "true");
22693
+ const name = element(document2, "span", void 0, "kehto-fw-name");
22694
+ name.append(element(document2, "code", capabilityLabel), element(document2, "small", label));
22695
+ const choice = select2(document2, `Action for ${capabilityLabel}, ${label}`, ACTIONS, entry.action);
22696
+ choice.addEventListener("change", () => {
22697
+ apply(() => setPermissionRule(options.rules.get(), entry.target, choice.value));
22698
+ });
22699
+ item.append(state, name, choice);
22700
+ if (removable) {
22701
+ const remove = element(document2, "button", "\xD7", "kehto-fw-icon");
22702
+ remove.type = "button";
22703
+ remove.title = "Remove rule";
22704
+ remove.setAttribute("aria-label", `Remove rule for ${capabilityLabel}, ${label}`);
22705
+ remove.addEventListener("click", () => apply(() => setPermissionRule(options.rules.get(), entry.target, void 0)));
22706
+ item.append(remove);
22707
+ }
22708
+ return item;
22709
+ }
22710
+ function refresh() {
22711
+ const rules = options.rules.get();
22712
+ const subjects = options.subjects();
22713
+ const labelFor2 = (subject) => subjects.find((item) => item.subject === subject)?.label ?? subject;
22714
+ list.replaceChildren(
22715
+ row("all", "Everything else", { target: {}, action: rules.default }, false),
22716
+ ...scopeRows(rules).map((entry) => row("all", capabilityText(entry.target), entry, true)),
22717
+ ...Object.entries(rules.napplets).flatMap(([subject, napplet]) => scopeRows(napplet, subject).map((entry) => row(labelFor2(subject), capabilityText(entry.target), entry, true)))
22718
+ );
22719
+ const chosen = scope.value;
22720
+ const known = new Map([...subjects, ...Object.keys(rules.napplets).map((subject) => ({ subject, label: labelFor2(subject) }))].map((item) => [item.subject, item.label]));
22721
+ scope.replaceChildren(...[[EVERY_NAPPLET, "All napplets"], ...known].map(([value, text2]) => {
22722
+ const option = element(document2, "option", text2);
22723
+ option.value = value;
22724
+ return option;
22725
+ }));
22726
+ scope.value = known.has(chosen) ? chosen : EVERY_NAPPLET;
22727
+ suggestions.replaceChildren(...[...new Set(options.suggestions())].sort().map((value) => {
22728
+ const option = element(document2, "option");
22729
+ option.value = value;
22730
+ return option;
22731
+ }));
22732
+ restore.hidden = !options.rules.defaults;
22733
+ }
22734
+ form.addEventListener("submit", (event) => {
22735
+ event.preventDefault();
22736
+ const target = parseCapability(capability.value);
22737
+ if (!target) {
22738
+ error.textContent = "Enter an interface such as link, or an operation such as link.open.";
22739
+ return;
22740
+ }
22741
+ const napplet = scope.value === EVERY_NAPPLET ? {} : { napplet: scope.value };
22742
+ apply(() => setPermissionRule(options.rules.get(), { ...napplet, ...target }, action.value));
22743
+ if (!error.textContent) capability.value = "";
22744
+ });
22745
+ restore.addEventListener("click", () => {
22746
+ const defaults = options.rules.defaults;
22747
+ if (defaults) apply(() => defaults());
22748
+ });
22749
+ return { root, refresh };
22611
22750
  }
22612
22751
  function createBrowserApprovalUi(options) {
22613
22752
  const document2 = options.mount.ownerDocument;
22614
- const root = element2(document2, "section");
22615
- root.className = "kehto-approval-ui";
22616
- const presenter = createBrowserApprovalPrompt(document2, options.labelForPrincipal);
22617
- const management = element2(document2, "section");
22753
+ const root = element(document2, "section", void 0, "kehto-approval-ui");
22754
+ const promptRoot = options.promptMount ? element(document2, "section", void 0, "kehto-approval-ui") : root;
22755
+ const presenter = createBrowserApprovalPrompt(document2, options.labelForPrincipal, () => !!options.rules);
22756
+ let destroyed = false;
22757
+ const management = element(document2, "section", void 0, "kehto-fw-management");
22618
22758
  management.setAttribute("aria-label", "Firewall grants");
22619
- const heading = element2(document2, "h2", "Firewall grants");
22620
- const status = element2(document2, "p");
22759
+ const status = element(document2, "p", void 0, "kehto-fw-error");
22621
22760
  status.setAttribute("role", "alert");
22622
22761
  status.setAttribute("aria-live", "assertive");
22623
- const list = element2(document2, "ul");
22624
- const clear = element2(document2, "button", "Clear all grants");
22762
+ const clear = element(document2, "button", "\xD7", "kehto-fw-icon");
22625
22763
  clear.type = "button";
22626
- const retry = element2(document2, "button", "Retry permission storage");
22764
+ clear.title = "Clear all grants";
22765
+ clear.setAttribute("aria-label", "Clear all grants");
22766
+ const retry = element(document2, "button", "Retry permission storage");
22627
22767
  retry.type = "button";
22628
- management.append(heading, status, list, clear, retry);
22629
- root.append(presenter.dialog, management);
22768
+ const head = element(document2, "div", void 0, "kehto-fw-head");
22769
+ head.append(element(document2, "h3", "Firewall grants"), clear);
22770
+ function revoke2(grants) {
22771
+ const live = options.getPermissions();
22772
+ if (!live) return;
22773
+ const results = grants.map((grant2) => [grant2, live.revoke(grant2.id)]);
22774
+ for (const [grant2, durable] of results) options.onGrantRevoked?.(grant2, durable);
22775
+ if (results.some(([, durable]) => !durable)) reportStorageError("save-failed");
22776
+ refresh();
22777
+ }
22778
+ function subjects() {
22779
+ const seen = /* @__PURE__ */ new Map();
22780
+ for (const grant2 of options.getPermissions()?.grants ?? []) {
22781
+ const subject = permissionRuleSubject(grant2.principal);
22782
+ if (!seen.has(subject)) seen.set(subject, options.labelForPrincipal(grant2.principal));
22783
+ }
22784
+ return [...seen].map(([subject, label]) => ({ subject, label }));
22785
+ }
22786
+ function resetStaleRuleGrants() {
22787
+ const rules = options.rules?.get();
22788
+ const grants = options.getPermissions()?.grants ?? [];
22789
+ if (!rules) return;
22790
+ const stale = grants.filter((grant2) => isRuleGrant(grant2) && resolvePermissionRule(rules, grant2.principal, grant2.permission) !== "allow");
22791
+ if (stale.length) revoke2(stale);
22792
+ else refresh();
22793
+ }
22794
+ const grantList = createGrantList(document2, { labelForPrincipal: options.labelForPrincipal, revoke: revoke2 });
22795
+ const rulesEditor = options.rules ? createRulesEditor(document2, {
22796
+ rules: options.rules,
22797
+ subjects,
22798
+ onChange: resetStaleRuleGrants,
22799
+ suggestions: () => (options.getPermissions()?.grants ?? []).flatMap((grant2) => [
22800
+ grant2.permission.domain,
22801
+ ...grant2.permission.category === "interface" ? [] : [grant2.permission.operation]
22802
+ ])
22803
+ }) : void 0;
22804
+ management.append(head, status, retry, grantList.root);
22805
+ promptRoot.append(presenter.dialog);
22806
+ if (rulesEditor) root.append(rulesEditor.root);
22807
+ root.append(management);
22630
22808
  options.mount.append(root);
22631
- let destroyed = false;
22809
+ options.promptMount?.append(promptRoot);
22632
22810
  function refresh() {
22633
22811
  if (destroyed) return;
22812
+ rulesEditor?.refresh();
22634
22813
  const permissions = options.getPermissions();
22635
- list.replaceChildren();
22636
22814
  if (!permissions) {
22815
+ grantList.render([]);
22637
22816
  status.textContent = "Firewall permission runtime is unavailable.";
22638
22817
  clear.disabled = true;
22639
22818
  retry.disabled = true;
22819
+ retry.hidden = true;
22640
22820
  options.onStorageStateChanged?.(false);
22641
22821
  return;
22642
22822
  }
22643
22823
  clear.disabled = permissions.grants.length === 0;
22644
22824
  retry.disabled = permissions.available;
22825
+ retry.hidden = permissions.available;
22645
22826
  if (permissions.available && !status.dataset.storageFailure) status.textContent = "";
22646
22827
  if (!permissions.available) status.textContent ||= "Permission storage is unavailable; new grants are blocked. Retry storage.";
22647
- for (const grant2 of permissions.grants) {
22648
- const row = element2(document2, "li");
22649
- const scope = grant2.permission.scope;
22650
- const detail = element2(document2, "span", `${options.labelForPrincipal(grant2.principal)} \u2014 ${principalIdentity(grant2.principal)} \u2014 ${grant2.effect} ${grant2.permission.operation} ${scope.kind}:${scope.value} (${grant2.lifetime})`);
22651
- const revoke2 = element2(document2, "button", "Revoke");
22652
- revoke2.type = "button";
22653
- revoke2.setAttribute("aria-label", `Revoke ${grant2.permission.operation} ${scope.kind}:${scope.value}`);
22654
- revoke2.addEventListener("click", () => {
22655
- const live = options.getPermissions();
22656
- if (!live) return;
22657
- const durable = live.revoke(grant2.id);
22658
- options.onGrantRevoked?.(grant2, durable);
22659
- if (!durable) reportStorageError("save-failed");
22660
- refresh();
22661
- });
22662
- row.append(detail, revoke2);
22663
- list.append(row);
22664
- }
22828
+ grantList.render(permissions.grants);
22665
22829
  options.onStorageStateChanged?.(permissions.available);
22666
22830
  }
22667
22831
  function reportStorageError(failure4) {
@@ -22688,14 +22852,29 @@ function createBrowserApprovalUi(options) {
22688
22852
  } else reportStorageError("save-failed");
22689
22853
  refresh();
22690
22854
  });
22855
+ function rememberAsRule(request, effect) {
22856
+ const target = ruleTargetFor(request.missing);
22857
+ if (!options.rules || !target) return;
22858
+ try {
22859
+ const napplet = permissionRuleSubject(request.request.principal);
22860
+ options.rules.set(setPermissionRule(options.rules.get(), { napplet, ...target }, effect));
22861
+ } catch {
22862
+ }
22863
+ }
22691
22864
  async function prompt(request) {
22692
- const answer = await presenter.prompt(request);
22865
+ const { answer, asRule, userGesture } = await presenter.prompt(request);
22866
+ try {
22867
+ options.onAnswer?.(answer, userGesture);
22868
+ } catch {
22869
+ }
22870
+ if (asRule && answer.effect !== "cancel") rememberAsRule(request, answer.effect);
22693
22871
  queueMicrotask(() => queueMicrotask(refresh));
22694
22872
  return answer;
22695
22873
  }
22696
22874
  function destroy() {
22697
22875
  destroyed = true;
22698
22876
  presenter.destroy();
22877
+ if (promptRoot !== root) promptRoot.remove();
22699
22878
  root.remove();
22700
22879
  }
22701
22880
  refresh();
@@ -22712,14 +22891,14 @@ var FRAME_ELEMENTS = /* @__PURE__ */ new Set([
22712
22891
  ]);
22713
22892
  var FRAME_TAG = /<\/?(?:iframe|frame|frameset|object|embed|portal|fencedframe)(?=[\s/>]|$)/i;
22714
22893
  function subtreeHasFrame(root) {
22715
- for (const element32 of Array.from(root.querySelectorAll("*"))) {
22716
- const local = (element32.localName || "").toLowerCase();
22717
- if (element32.namespaceURI === "http://www.w3.org/1999/xhtml" && FRAME_ELEMENTS.has(local)) {
22894
+ for (const element22 of Array.from(root.querySelectorAll("*"))) {
22895
+ const local = (element22.localName || "").toLowerCase();
22896
+ if (element22.namespaceURI === "http://www.w3.org/1999/xhtml" && FRAME_ELEMENTS.has(local)) {
22718
22897
  return true;
22719
22898
  }
22720
- const template = element32;
22899
+ const template = element22;
22721
22900
  if (local === "template" && template.content && subtreeHasFrame(template.content)) return true;
22722
- if (element32.shadowRoot && subtreeHasFrame(element32.shadowRoot)) return true;
22901
+ if (element22.shadowRoot && subtreeHasFrame(element22.shadowRoot)) return true;
22723
22902
  }
22724
22903
  return false;
22725
22904
  }
@@ -22742,6 +22921,72 @@ function assertNappletHasNoFrame(html) {
22742
22921
  }
22743
22922
  }
22744
22923
 
22924
+ // src/browser-link.ts
22925
+ var APPROVAL_CLICK_WINDOW_MS = 1e3;
22926
+ var approvalClickAt = Number.NEGATIVE_INFINITY;
22927
+ function notePajaApprovalClick(now2 = performance.now()) {
22928
+ approvalClickAt = now2;
22929
+ }
22930
+ function hasPajaApprovalClick(now2 = performance.now()) {
22931
+ if (now2 - approvalClickAt > APPROVAL_CLICK_WINDOW_MS) return false;
22932
+ return typeof navigator !== "undefined" && navigator.userActivation?.isActive === true;
22933
+ }
22934
+ async function confirmPajaExternalLink(context, confirm, getIdentity, open, userActivation, isActivated = hasPajaApprovalClick) {
22935
+ const { windowId, url, options, signal } = context;
22936
+ if (signal?.aborted) return { status: "denied" };
22937
+ const fallback = { dTag: "dev-target", aggregateHash: "paja" };
22938
+ const identity = getIdentity?.(windowId) ?? fallback;
22939
+ const isCurrent = () => {
22940
+ const current = getIdentity?.(windowId) ?? fallback;
22941
+ return !signal?.aborted && (identity.isCurrent?.() ?? true) && current.dTag === identity.dTag && current.aggregateHash === identity.aggregateHash;
22942
+ };
22943
+ const request = {
22944
+ action: "link",
22945
+ windowId,
22946
+ napplet: identity,
22947
+ url: url.href,
22948
+ ...options?.label ? { label: options.label.slice(0, 256) } : {},
22949
+ isCurrent
22950
+ };
22951
+ const openCurrent = () => isCurrent() && open(url);
22952
+ if (signal && isActivated() && openCurrent()) return { status: "opened" };
22953
+ try {
22954
+ const opened = userActivation ? await userActivation.run(request, openCurrent) : await confirm(request) && openCurrent();
22955
+ return { status: opened ? "opened" : "denied" };
22956
+ } catch {
22957
+ return { status: "denied" };
22958
+ }
22959
+ }
22960
+
22961
+ // src/browser-permission-rules.ts
22962
+ var PAJA_PERMISSION_RULES_STORAGE_KEY = "kehto:paja:firewall-rules:v1";
22963
+ function pajaDefaultPermissionRules() {
22964
+ return createPermissionRules({ default: "allow", operations: { "link.open": "ask" } });
22965
+ }
22966
+ function createPajaPermissionRuleStore(storage) {
22967
+ let rules = pajaDefaultPermissionRules();
22968
+ try {
22969
+ const raw = storage?.getItem(PAJA_PERMISSION_RULES_STORAGE_KEY);
22970
+ const loaded = raw ? deserializePermissionRules(raw) : void 0;
22971
+ if (loaded?.ok) rules = loaded.rules;
22972
+ } catch {
22973
+ }
22974
+ return {
22975
+ get: () => rules,
22976
+ set(next) {
22977
+ const validated = createPermissionRules(next);
22978
+ storage?.setItem(PAJA_PERMISSION_RULES_STORAGE_KEY, serializePermissionRules(validated));
22979
+ rules = validated;
22980
+ },
22981
+ defaults: pajaDefaultPermissionRules,
22982
+ decide(request, missing) {
22983
+ const actions = missing.map((requirement) => resolvePermissionRule(rules, request.principal, requirement));
22984
+ if (actions.includes("deny")) return "deny";
22985
+ return actions.every((action) => action === "allow") ? "allow" : "ask";
22986
+ }
22987
+ };
22988
+ }
22989
+
22745
22990
  // src/browser-permission-adapter.ts
22746
22991
  var PAJA_PERMISSION_STORAGE_KEY = "kehto:paja:firewall-permissions:v1";
22747
22992
  function readStorage() {
@@ -22753,20 +22998,44 @@ function readStorage() {
22753
22998
  }
22754
22999
  function createPajaPermissionAdapter(options) {
22755
23000
  const storage = options.storage === void 0 ? readStorage() : options.storage;
23001
+ const rules = createPajaPermissionRuleStore(storage);
22756
23002
  const ui = createBrowserApprovalUi({
22757
23003
  mount: options.mount,
23004
+ // A modal inside collapsed details/display:none still blocks the page,
23005
+ // but cannot show the decision admission is waiting for.
23006
+ promptMount: options.mount.ownerDocument.body,
22758
23007
  getPermissions: options.getPermissions,
22759
23008
  labelForPrincipal: options.labelForPrincipal ?? ((principal) => principal.kind === "verified" ? "Verified napplet" : "Development target"),
22760
- onGrantRevoked: options.onGrantRevoked
23009
+ onGrantRevoked: options.onGrantRevoked,
23010
+ rules,
23011
+ onAnswer(answer, userGesture) {
23012
+ if (answer.effect === "allow" && userGesture) notePajaApprovalClick();
23013
+ }
22761
23014
  });
23015
+ let refreshPending = false;
23016
+ const scheduleRefresh = () => {
23017
+ if (refreshPending) return;
23018
+ refreshPending = true;
23019
+ window.setTimeout(() => {
23020
+ refreshPending = false;
23021
+ ui.refresh();
23022
+ }, 0);
23023
+ };
22762
23024
  const adapter = {
22763
23025
  now: Date.now,
23026
+ rateLimiter: createRateLimiter(defaultRateLimitConfig()),
23027
+ promptRateLimiter: createRateLimiter(defaultPromptRateLimitConfig()),
22764
23028
  createCancellation: () => new AbortController(),
22765
23029
  schedule(callback, delayMs) {
22766
23030
  const timer = window.setTimeout(callback, delayMs);
22767
23031
  return () => window.clearTimeout(timer);
22768
23032
  },
22769
23033
  prompt: ui.prompt,
23034
+ defaultDecision(request, missing) {
23035
+ const decision = rules.decide(request, missing);
23036
+ if (decision === "allow") scheduleRefresh();
23037
+ return decision;
23038
+ },
22770
23039
  onStorageError: ui.reportStorageError,
22771
23040
  ...storage ? { persistence: {
22772
23041
  load: () => storage.getItem(PAJA_PERMISSION_STORAGE_KEY),
@@ -22774,7 +23043,7 @@ function createPajaPermissionAdapter(options) {
22774
23043
  } } : {}
22775
23044
  };
22776
23045
  if (!storage) ui.reportStorageError("storage-unavailable");
22777
- return { adapter, ui, destroy: () => ui.destroy() };
23046
+ return { adapter, ui, rules, destroy: () => ui.destroy() };
22778
23047
  }
22779
23048
 
22780
23049
  // src/local-target.ts
@@ -22951,20 +23220,20 @@ function createPajaSecuritySettings(getStorage = () => localStorage) {
22951
23220
  }
22952
23221
  function installPajaSecuritySettings() {
22953
23222
  const settings = createPajaSecuritySettings();
22954
- const select2 = document.getElementById("paja-nested-context-lock");
23223
+ const select3 = document.getElementById("paja-nested-context-lock");
22955
23224
  const status = document.getElementById("paja-nested-context-lock-status");
22956
- if (!select2 || !status) return { getSetting: settings.getSetting, dispose: () => {
23225
+ if (!select3 || !status) return { getSetting: settings.getSetting, dispose: () => {
22957
23226
  } };
22958
- select2.value = settings.getSetting() ?? "";
23227
+ select3.value = settings.getSetting() ?? "";
22959
23228
  status.textContent = settings.getStatus();
22960
23229
  const onChange = () => {
22961
- const result2 = settings.save(select2.value);
22962
- select2.setAttribute("aria-invalid", String(!result2.ok));
23230
+ const result2 = settings.save(select3.value);
23231
+ select3.setAttribute("aria-invalid", String(!result2.ok));
22963
23232
  status.textContent = result2.message;
22964
- if (!result2.ok) select2.value = settings.getSetting() ?? "";
23233
+ if (!result2.ok) select3.value = settings.getSetting() ?? "";
22965
23234
  };
22966
- select2.addEventListener("change", onChange);
22967
- return { getSetting: settings.getSetting, dispose: () => select2.removeEventListener("change", onChange) };
23235
+ select3.addEventListener("change", onChange);
23236
+ return { getSetting: settings.getSetting, dispose: () => select3.removeEventListener("change", onChange) };
22968
23237
  }
22969
23238
 
22970
23239
  // src/browser-target-frame.ts
@@ -23209,6 +23478,15 @@ function revokedPajaTabIds(config, tabs, grant2) {
23209
23478
  return principal && permissionPrincipalKey(principal) === revoked;
23210
23479
  }).map((tab) => tab.id);
23211
23480
  }
23481
+ function pajaPrincipalLabel(config, tabs, principal) {
23482
+ const key = permissionPrincipalKey(principal);
23483
+ const tab = tabs.find((candidate) => {
23484
+ const open = getTargetOriginIdentity(config, candidate.resolvedTarget).permissionPrincipal;
23485
+ return open && permissionPrincipalKey(open) === key;
23486
+ });
23487
+ if (tab?.title) return tab.title;
23488
+ return principal.kind === "verified" ? "Verified napplet" : principal.target;
23489
+ }
23212
23490
 
23213
23491
  // src/browser-llm-models.ts
23214
23492
  var PajaLlmModelsError = class extends Error {
@@ -23425,7 +23703,7 @@ function meets(record3, requirements3) {
23425
23703
  if (requirements3.tools === true && record3.tools !== true) return false;
23426
23704
  return !(requirements3.json === true && !record3.json);
23427
23705
  }
23428
- function describeRequirements(requirements3) {
23706
+ function describeRequirements2(requirements3) {
23429
23707
  const parts = [
23430
23708
  requirements3.model ? `model ${requirements3.model}` : "any model",
23431
23709
  requirements3.images ? "image input" : null,
@@ -23479,12 +23757,12 @@ function createPajaLlmHost(options) {
23479
23757
  }
23480
23758
  return credential;
23481
23759
  }
23482
- async function select2(context, requirements3, prompt) {
23760
+ async function select3(context, requirements3, prompt) {
23483
23761
  const signal = prompt?.signal;
23484
23762
  const napplet = getIdentity(context.windowId);
23485
23763
  const candidates = store2.list().filter((record3) => meets(record3, requirements3));
23486
23764
  if (candidates.length === 0) {
23487
- const configure = await confirm({ action: "llm-configure", windowId: context.windowId, napplet, requirements: describeRequirements(requirements3), configured: store2.list().length, ...signal ? { signal } : {} });
23765
+ const configure = await confirm({ action: "llm-configure", windowId: context.windowId, napplet, requirements: describeRequirements2(requirements3), configured: store2.list().length, ...signal ? { signal } : {} });
23488
23766
  if (!configure) return null;
23489
23767
  options.openPanel();
23490
23768
  throw new LlmServiceError("unsupported", "No compatible language model connection is configured yet. Add one in Paja's Language models panel, then select again.");
@@ -23496,7 +23774,7 @@ function createPajaLlmHost(options) {
23496
23774
  }
23497
23775
  return {
23498
23776
  isConfigured: () => store2.list().length > 0,
23499
- select: select2,
23777
+ select: select3,
23500
23778
  describe(_context, connectionId) {
23501
23779
  const record3 = store2.get(connectionId);
23502
23780
  return record3 ? toConnection(record3) : null;
@@ -23696,8 +23974,8 @@ function createPajaLlmVault(options = {}) {
23696
23974
 
23697
23975
  // src/browser-llm-panel.ts
23698
23976
  function byId(id, ctor) {
23699
- const element4 = document.getElementById(id);
23700
- return element4 instanceof ctor ? element4 : null;
23977
+ const element3 = document.getElementById(id);
23978
+ return element3 instanceof ctor ? element3 : null;
23701
23979
  }
23702
23980
  function presetById(id) {
23703
23981
  return LLM_PROVIDER_PRESETS.find((preset) => preset.id === id);
@@ -23779,10 +24057,10 @@ function createPasswordDialog() {
23779
24057
  function createChooserDialog() {
23780
24058
  const dialog = byId("paja-llm-select-dialog", HTMLDialogElement);
23781
24059
  const copy = byId("paja-llm-select-copy", HTMLElement);
23782
- const select2 = byId("paja-llm-select-options", HTMLSelectElement);
24060
+ const select3 = byId("paja-llm-select-options", HTMLSelectElement);
23783
24061
  const use = byId("paja-llm-select-use", HTMLButtonElement);
23784
24062
  const deny = byId("paja-llm-select-deny", HTMLButtonElement);
23785
- if (!dialog || !copy || !select2 || !use || !deny) return { choose: async () => null, dispose: () => void 0 };
24063
+ if (!dialog || !copy || !select3 || !use || !deny) return { choose: async () => null, dispose: () => void 0 };
23786
24064
  let settle4 = null;
23787
24065
  const finish = (value) => {
23788
24066
  const current = settle4;
@@ -23790,7 +24068,7 @@ function createChooserDialog() {
23790
24068
  if (dialog.open) dialog.close();
23791
24069
  current?.(value);
23792
24070
  };
23793
- const onUse = () => finish(select2.value || null);
24071
+ const onUse = () => finish(select3.value || null);
23794
24072
  const onDeny = (event) => {
23795
24073
  event.preventDefault();
23796
24074
  finish(null);
@@ -23804,13 +24082,13 @@ function createChooserDialog() {
23804
24082
  if (context.signal?.aborted) return Promise.resolve(null);
23805
24083
  const wanted = [context.requirements.model ? `model ${context.requirements.model}` : null, context.requirements.images ? "image input" : null, context.requirements.json ? "JSON output" : null, context.requirements.tools ? "tool calling" : null].filter(Boolean).join(", ");
23806
24084
  copy.textContent = `${context.napplet.dTag} (${context.windowId}) asks to use a language model${wanted ? ` with ${wanted}` : ""}. Selecting does not send anything yet; each generation asks for consent.`;
23807
- select2.replaceChildren(...candidates.map((record3) => {
24085
+ select3.replaceChildren(...candidates.map((record3) => {
23808
24086
  const option = document.createElement("option");
23809
24087
  option.value = record3.id;
23810
24088
  option.textContent = `${record3.name} \u2014 ${record3.model} (${new URL(record3.baseUrl).origin})`;
23811
24089
  return option;
23812
24090
  }));
23813
- select2.selectedIndex = candidates.length > 0 ? 0 : -1;
24091
+ select3.selectedIndex = candidates.length > 0 ? 0 : -1;
23814
24092
  return new Promise((resolve) => {
23815
24093
  const mine = (value) => {
23816
24094
  detach();
@@ -23821,7 +24099,7 @@ function createChooserDialog() {
23821
24099
  });
23822
24100
  settle4 = mine;
23823
24101
  dialog.showModal();
23824
- select2.focus();
24102
+ select3.focus();
23825
24103
  });
23826
24104
  },
23827
24105
  dispose() {
@@ -26928,30 +27206,13 @@ function readAuthors(candidates) {
26928
27206
  }
26929
27207
  return [...authors];
26930
27208
  }
26931
- async function getSignerRelayUrls(signerProvider, direction) {
26932
- const signer = signerProvider?.getSigner();
26933
- if (!signer?.getRelays) return [];
26934
- try {
26935
- const relays = await signer.getRelays();
26936
- return dedupeRelayUrls(Object.entries(relays).flatMap(([url, permissions]) => {
26937
- if (direction === "read" && permissions.read) return [url];
26938
- if (direction === "write" && permissions.write) return [url];
26939
- return [];
26940
- }));
26941
- } catch {
26942
- return [];
26943
- }
26944
- }
26945
- async function getPajaBootstrapRelayUrls(getSimulation, signerProvider, getHostRelayUrls) {
26946
- return dedupeRelayUrls([
26947
- ...getHostRelayUrls?.() ?? getPajaRelayUrls(getSimulation()),
26948
- ...await getSignerRelayUrls(signerProvider, "read")
26949
- ]);
27209
+ function getPajaBootstrapRelayUrls(getSimulation, getHostRelayUrls) {
27210
+ return dedupeRelayUrls(getHostRelayUrls?.() ?? getPajaRelayUrls(getSimulation()));
26950
27211
  }
26951
- function createPajaContactListLoader(backend, getSimulation, signerProvider, getHostRelayUrls) {
27212
+ function createPajaContactListLoader(backend, getSimulation, getHostRelayUrls) {
26952
27213
  return async (pubkey2, signal) => {
26953
27214
  if (!/^[0-9a-fA-F]{64}$/.test(pubkey2) || signal?.aborted) return [];
26954
- const relayUrls2 = await getPajaBootstrapRelayUrls(getSimulation, signerProvider, getHostRelayUrls);
27215
+ const relayUrls2 = getPajaBootstrapRelayUrls(getSimulation, getHostRelayUrls);
26955
27216
  if (signal?.aborted) return [];
26956
27217
  const filters = [{
26957
27218
  kinds: [PAJA_CONTACT_LIST_KIND],
@@ -26967,15 +27228,14 @@ function createPajaContactListLoader(backend, getSimulation, signerProvider, get
26967
27228
  function latestEvent(events, kind, pubkey2) {
26968
27229
  return events.filter((event) => event.kind === kind && event.pubkey === pubkey2).sort((a, b) => b.created_at - a.created_at)[0];
26969
27230
  }
26970
- function createPajaRelayListLoader(backend, getSimulation, signerProvider, getHostRelayUrls) {
27231
+ function createPajaRelayListLoader(backend, getSimulation, getHostRelayUrls) {
26971
27232
  const registry2 = createNip65Registry();
26972
27233
  return async (pubkeys) => {
26973
27234
  const uniquePubkeys = [...new Set(pubkeys.filter((pubkey2) => /^[0-9a-fA-F]{64}$/.test(pubkey2)))];
26974
27235
  const missing = uniquePubkeys.filter((pubkey2) => !registry2.has(pubkey2));
26975
27236
  if (missing.length > 0) {
26976
- const events = await backend.query(await getPajaBootstrapRelayUrls(
27237
+ const events = await backend.query(getPajaBootstrapRelayUrls(
26977
27238
  getSimulation,
26978
- signerProvider,
26979
27239
  getHostRelayUrls
26980
27240
  ), [{
26981
27241
  kinds: [PAJA_NIP65_RELAY_LIST_KIND],
@@ -27432,7 +27692,6 @@ function createOutboxRouter(backend, getSimulation, relayConfig, confirmRequest,
27432
27692
  loadRelayLists: createPajaRelayListLoader(
27433
27693
  backend,
27434
27694
  getSimulation,
27435
- signerProvider,
27436
27695
  () => relayConfig.getRelayUrls(["discovery", "super"])
27437
27696
  ),
27438
27697
  fallbackRelays: relayConfig.outboxRelays,
@@ -27527,9 +27786,9 @@ function createPajaUploadRuntime(options) {
27527
27786
  if (simulation.upload.mimeTypes && (!mimeType || !simulation.upload.mimeTypes.includes(mimeType))) {
27528
27787
  throw new Error("unsupported media type");
27529
27788
  }
27530
- const snapshot3 = identity;
27531
- if (!snapshot3) throw new Error("no signer available");
27532
- const selectedIdentity = snapshot3;
27789
+ const snapshot4 = identity;
27790
+ if (!snapshot4) throw new Error("no signer available");
27791
+ const selectedIdentity = snapshot4;
27533
27792
  const server = effectiveServers(simulation, selectedIdentity.pubkey, discovered)[0];
27534
27793
  if (!server) throw new Error("no server configured");
27535
27794
  const selectedGeneration = generation2;
@@ -27567,12 +27826,12 @@ function createPajaUploadRuntime(options) {
27567
27826
  };
27568
27827
  function uploadInfo() {
27569
27828
  const simulation = options.getSimulation();
27570
- const snapshot3 = identity;
27571
- const server = snapshot3 ? effectiveServers(simulation, snapshot3.pubkey, discovered)[0] : void 0;
27829
+ const snapshot4 = identity;
27830
+ const server = snapshot4 ? effectiveServers(simulation, snapshot4.pubkey, discovered)[0] : void 0;
27572
27831
  return {
27573
27832
  rails: [{
27574
27833
  rail: "blossom",
27575
- enabled: simulation.upload.mode === "blossom" && Boolean(snapshot3 && server),
27834
+ enabled: simulation.upload.mode === "blossom" && Boolean(snapshot4 && server),
27576
27835
  ...server ? { returns: [new URL(server).protocol.slice(0, -1)] } : {}
27577
27836
  }],
27578
27837
  ...simulation.upload.maxBytes !== void 0 ? { maxBytes: simulation.upload.maxBytes } : {},
@@ -28062,8 +28321,8 @@ function createPajaSocialCache(options) {
28062
28321
  try {
28063
28322
  const follows = await verifiedFollows(capturedPubkey, isStillCurrent, controller.signal);
28064
28323
  if (!isStillCurrent()) return;
28065
- const snapshot3 = { follows, profiles: /* @__PURE__ */ new Map() };
28066
- snapshots.set(capturedPubkey, snapshot3);
28324
+ const snapshot4 = { follows, profiles: /* @__PURE__ */ new Map() };
28325
+ snapshots.set(capturedPubkey, snapshot4);
28067
28326
  for (let index = 0; index < follows.length; index += 1) {
28068
28327
  if (!isStillCurrent()) return;
28069
28328
  const author = follows[index];
@@ -28078,7 +28337,7 @@ function createPajaSocialCache(options) {
28078
28337
  if (!isStillCurrent()) return;
28079
28338
  if (warmed) {
28080
28339
  const profile = profileResult(warmed, author);
28081
- if (profile) snapshot3.profiles.set(author, profile);
28340
+ if (profile) snapshot4.profiles.set(author, profile);
28082
28341
  }
28083
28342
  if ((index + 1) % PROFILE_WARM_YIELD_EVERY === 0 && index + 1 < follows.length) {
28084
28343
  if (!isStillCurrent()) return;
@@ -28099,10 +28358,10 @@ function createPajaSocialCache(options) {
28099
28358
  async function augmentQuery(filters, queryOptions, execute, signal) {
28100
28359
  const canAugmentAtStart = canReadIdentity?.() ?? true;
28101
28360
  const activePubkey = normalizePubkey2(options.getActivePubkey() ?? "");
28102
- const snapshot3 = canAugmentAtStart && activePubkey ? snapshots.get(activePubkey) : void 0;
28361
+ const snapshot4 = canAugmentAtStart && activePubkey ? snapshots.get(activePubkey) : void 0;
28103
28362
  const base = await execute();
28104
28363
  if (signal?.aborted || !canAugmentAtStart || !(canReadIdentity?.() ?? true)) return base;
28105
- return mergeResult(base, matchingCachedProfiles(snapshot3?.profiles, filters), filters, queryOptions);
28364
+ return mergeResult(base, matchingCachedProfiles(snapshot4?.profiles, filters), filters, queryOptions);
28106
28365
  }
28107
28366
  return {
28108
28367
  ...router.getEvent ? { getEvent: router.getEvent.bind(router) } : {},
@@ -29195,33 +29454,6 @@ function waitForIceGathering(connection) {
29195
29454
  });
29196
29455
  }
29197
29456
 
29198
- // src/browser-link.ts
29199
- async function confirmPajaExternalLink(context, confirm, getIdentity, open, userActivation) {
29200
- const { windowId, url, options, signal } = context;
29201
- if (signal?.aborted) return { status: "denied" };
29202
- const fallback = { dTag: "dev-target", aggregateHash: "paja" };
29203
- const identity = getIdentity?.(windowId) ?? fallback;
29204
- const isCurrent = () => {
29205
- const current = getIdentity?.(windowId) ?? fallback;
29206
- return !signal?.aborted && (identity.isCurrent?.() ?? true) && current.dTag === identity.dTag && current.aggregateHash === identity.aggregateHash;
29207
- };
29208
- const request = {
29209
- action: "link",
29210
- windowId,
29211
- napplet: identity,
29212
- url: url.href,
29213
- ...options?.label ? { label: options.label.slice(0, 256) } : {},
29214
- isCurrent
29215
- };
29216
- const openCurrent = () => isCurrent() && open(url);
29217
- try {
29218
- const opened = userActivation ? await userActivation.run(request, openCurrent) : await confirm(request) && openCurrent();
29219
- return { status: opened ? "opened" : "denied" };
29220
- } catch {
29221
- return { status: "denied" };
29222
- }
29223
- }
29224
-
29225
29457
  // src/browser-fs-support.ts
29226
29458
  var MAX_READ_BYTES = 1024 * 1024;
29227
29459
  var MAX_WRITE_BYTES = 1024 * 1024;
@@ -29526,22 +29758,22 @@ async function createPajaBrowserFsBackend(options) {
29526
29758
  }
29527
29759
  }
29528
29760
  async function snapshotEntry(entry, recursive) {
29529
- const snapshot3 = /* @__PURE__ */ new Map();
29761
+ const snapshot4 = /* @__PURE__ */ new Map();
29530
29762
  async function visit(path, handle, descend) {
29531
29763
  if (handle.kind === "file") {
29532
29764
  const file = await handle.getFile();
29533
- snapshot3.set(path, `file:${file.size}:${file.lastModified}`);
29765
+ snapshot4.set(path, `file:${file.size}:${file.lastModified}`);
29534
29766
  return;
29535
29767
  }
29536
- snapshot3.set(path, "directory");
29768
+ snapshot4.set(path, "directory");
29537
29769
  for await (const [name, childHandle] of handle.entries()) {
29538
29770
  const childPath = `${path}/${name.normalize("NFC")}`;
29539
29771
  if (childHandle.kind === "file" || descend) await visit(childPath, childHandle, descend);
29540
- else snapshot3.set(childPath, "directory");
29772
+ else snapshot4.set(childPath, "directory");
29541
29773
  }
29542
29774
  }
29543
29775
  await visit(entry.path, entry.handle, recursive);
29544
- return snapshot3;
29776
+ return snapshot4;
29545
29777
  }
29546
29778
  function covered(watch, path) {
29547
29779
  if (!watch.directory) return path === watch.path;
@@ -29814,7 +30046,7 @@ async function createPajaBrowserFsBackend(options) {
29814
30046
  const entry = await resolveExisting(windowId, path);
29815
30047
  assertPendingWatch(pending);
29816
30048
  requirePermission(entry, "watch");
29817
- const snapshot3 = await snapshotEntry(entry, watchOptions?.recursive === true);
30049
+ const snapshot4 = await snapshotEntry(entry, watchOptions?.recursive === true);
29818
30050
  assertPendingWatch(pending);
29819
30051
  const callback = onChange ?? (() => void 0);
29820
30052
  const record3 = {
@@ -29823,7 +30055,7 @@ async function createPajaBrowserFsBackend(options) {
29823
30055
  directory: entry.handle.kind === "directory",
29824
30056
  recursive: watchOptions?.recursive === true,
29825
30057
  onChange: callback,
29826
- snapshot: snapshot3,
30058
+ snapshot: snapshot4,
29827
30059
  closed: false
29828
30060
  };
29829
30061
  backendWatches.add(record3);
@@ -29913,22 +30145,6 @@ function createDevServices(backend, getSimulation, relayConfig, onThemeService,
29913
30145
  const getReadRelays = () => relayConfig.getRelayUrls(["discovery", "super"]);
29914
30146
  const getWriteRelays = () => relayConfig.getRelayUrls(["outbox"]);
29915
30147
  const getAllRelays = () => relayConfig.getRelayUrls();
29916
- const signerBootstrapRelays = [];
29917
- let signerBootstrapGeneration = 0;
29918
- const refreshSignerBootstrapRelays = () => {
29919
- const generation2 = ++signerBootstrapGeneration;
29920
- signerBootstrapRelays.splice(0);
29921
- const signer = signerProvider?.getSigner();
29922
- if (!signer?.getRelays) return;
29923
- void Promise.resolve().then(() => signer.getRelays()).then((relays) => {
29924
- if (generation2 !== signerBootstrapGeneration || !relays || typeof relays !== "object") return;
29925
- for (const [url, permissions] of Object.entries(relays)) {
29926
- if (permissions?.read && typeof url === "string") signerBootstrapRelays.push(url);
29927
- }
29928
- }).catch(() => {
29929
- });
29930
- };
29931
- refreshSignerBootstrapRelays();
29932
30148
  const baseOutboxRouter = createOutboxRouter(backend, getSimulation, relayConfig, confirmRequest, signerProvider);
29933
30149
  const queryApprovedResourceRelays = async (relayUrls2, filters, context) => {
29934
30150
  const unique = [...new Set(relayUrls2.filter((relay) => isPajaRelayAllowed(relay, () => relayConfig.getRelayUrls())))];
@@ -29944,14 +30160,7 @@ function createDevServices(backend, getSimulation, relayConfig, onThemeService,
29944
30160
  };
29945
30161
  const discoverBlossomServerList = async (pubkey2, context) => {
29946
30162
  const relayListEvents = await queryApprovedResourceRelays(
29947
- // Resource requests never call an external signer's getRelays hook. The
29948
- // host refreshes signerBootstrapRelays on lifecycle changes, so each URL
29949
- // below is already concrete and can be approved before opening a socket.
29950
- await getPajaBootstrapRelayUrls(
29951
- getSimulation,
29952
- void 0,
29953
- () => [...getReadRelays(), ...signerBootstrapRelays]
29954
- ),
30163
+ getReadRelays(),
29955
30164
  [{ kinds: [10002], authors: [pubkey2], limit: 2 }],
29956
30165
  context
29957
30166
  );
@@ -29977,7 +30186,7 @@ function createDevServices(backend, getSimulation, relayConfig, onThemeService,
29977
30186
  });
29978
30187
  const socialCache = createPajaSocialCache({
29979
30188
  baseRouter: baseOutboxRouter,
29980
- loadContactList: createPajaContactListLoader(backend, getSimulation, signerProvider, getReadRelays),
30189
+ loadContactList: createPajaContactListLoader(backend, getSimulation, getReadRelays),
29981
30190
  verifyEvent: (event) => verifyEvent(event),
29982
30191
  // Background warming is speculative relay traffic, so it only runs for a
29983
30192
  // signer account. `getFollows` still answers on demand for any requested
@@ -30125,7 +30334,9 @@ function createDevServices(backend, getSimulation, relayConfig, onThemeService,
30125
30334
  if (!identitySigner || key !== identitySignerKey) {
30126
30335
  identitySigner = connectedSigner && signerProvider ? {
30127
30336
  getPublicKey: () => signerProvider.getSigner()?.getPublicKey?.() ?? "",
30128
- getRelays: () => signerProvider.getSigner()?.getRelays?.() ?? {}
30337
+ // NAP-IDENTITY permits empty unsupported metadata results.
30338
+ // Host bootstrap URLs are not the user's NIP-65 preferences.
30339
+ getRelays: () => ({})
30129
30340
  } : createRuntimeSigner(getSimulation, confirmRequest, signerProvider);
30130
30341
  identitySignerKey = key;
30131
30342
  }
@@ -30245,7 +30456,6 @@ function createDevServices(backend, getSimulation, relayConfig, onThemeService,
30245
30456
  return {
30246
30457
  services,
30247
30458
  refreshAvailability,
30248
- refreshSignerBootstrapRelays,
30249
30459
  setWindowBlossomServers: blossomEventResolver.setWindowServers
30250
30460
  };
30251
30461
  }
@@ -30314,7 +30524,6 @@ function createPajaAdapter(config, getSimulation, onThemeService, onThemeBroadca
30314
30524
  if (getSimulation().capabilities.domains.fs) queueMicrotask(() => onEnvironmentChanged?.());
30315
30525
  });
30316
30526
  signerProvider?.subscribe?.(() => {
30317
- serviceBundle.refreshSignerBootstrapRelays();
30318
30527
  const availabilityChanged = serviceBundle.refreshAvailability();
30319
30528
  if (uploadRuntime) {
30320
30529
  void uploadRuntime.refreshIdentity().finally(() => onEnvironmentChanged?.());
@@ -30875,6 +31084,12 @@ function renderSignerStatus(state, signerPubkey) {
30875
31084
  clearConsent.textContent = `Forget ${state.signerConsentCount} remembered approval${state.signerConsentCount === 1 ? "" : "s"}`;
30876
31085
  clearConsent.onclick = () => state.clearSignerConsent();
30877
31086
  const previousInput = controls.querySelector("#signer-bunker-uri")?.value ?? "";
31087
+ const noneButton = document.createElement("button");
31088
+ noneButton.type = "button";
31089
+ noneButton.id = "signer-none";
31090
+ noneButton.dataset.active = String(state.signer.method === "none");
31091
+ noneButton.textContent = "None";
31092
+ noneButton.addEventListener("click", () => state.useNoSigner());
30878
31093
  const devButton = document.createElement("button");
30879
31094
  devButton.type = "button";
30880
31095
  devButton.id = "signer-dev";
@@ -30900,7 +31115,7 @@ function renderSignerStatus(state, signerPubkey) {
30900
31115
  bunkerButton.dataset.active = String(state.signer.method === "nip46");
30901
31116
  bunkerButton.textContent = "Bunker";
30902
31117
  bunkerButton.addEventListener("click", () => void state.connectBunker(bunkerInput.value));
30903
- controls.replaceChildren(devButton, nip07Button, bunkerInput, bunkerButton);
31118
+ controls.replaceChildren(noneButton, devButton, nip07Button, bunkerInput, bunkerButton);
30904
31119
  }
30905
31120
 
30906
31121
  // src/browser-nip46-client.ts
@@ -31081,6 +31296,7 @@ function createNip46Client(options) {
31081
31296
  }
31082
31297
 
31083
31298
  // src/browser-signers.ts
31299
+ var SIGNER_METHOD_KEY = "kehto:paja:signer-method:v1";
31084
31300
  function cloneState(state) {
31085
31301
  return { ...state };
31086
31302
  }
@@ -31129,12 +31345,25 @@ function createNip07Adapter(signer) {
31129
31345
  return {
31130
31346
  getPublicKey: signer.getPublicKey?.bind(signer),
31131
31347
  signEvent: signer.signEvent?.bind(signer),
31132
- getRelays: signer.getRelays?.bind(signer),
31133
31348
  nip04: signer.nip04,
31134
31349
  nip44: signer.nip44
31135
31350
  };
31136
31351
  }
31137
31352
  function createPajaSignerController(options) {
31353
+ const readPreference = () => {
31354
+ try {
31355
+ const method = (options.storage ?? localStorage).getItem(SIGNER_METHOD_KEY);
31356
+ if (method === "dev" || method === "nip07" || method === "nip46") return method;
31357
+ } catch {
31358
+ }
31359
+ return "none";
31360
+ };
31361
+ const persist = (method) => {
31362
+ try {
31363
+ (options.storage ?? localStorage).setItem(SIGNER_METHOD_KEY, method);
31364
+ } catch {
31365
+ }
31366
+ };
31138
31367
  let state = {
31139
31368
  method: "none",
31140
31369
  status: "disconnected",
@@ -31144,6 +31373,7 @@ function createPajaSignerController(options) {
31144
31373
  };
31145
31374
  let activeSigner = null;
31146
31375
  let activeClient = null;
31376
+ let generation2 = 0;
31147
31377
  const listeners = /* @__PURE__ */ new Set();
31148
31378
  const update = (next) => {
31149
31379
  state = { ...state, ...next };
@@ -31167,6 +31397,8 @@ function createPajaSignerController(options) {
31167
31397
  return () => listeners.delete(listener);
31168
31398
  },
31169
31399
  useDevSigner() {
31400
+ persist("dev");
31401
+ generation2 += 1;
31170
31402
  closeClient();
31171
31403
  activeSigner = null;
31172
31404
  update({
@@ -31177,7 +31409,16 @@ function createPajaSignerController(options) {
31177
31409
  error: null
31178
31410
  });
31179
31411
  },
31412
+ useNoSigner() {
31413
+ persist("none");
31414
+ generation2 += 1;
31415
+ closeClient();
31416
+ activeSigner = null;
31417
+ update({ method: "none", status: "disconnected", pubkey: null, relay: null, error: null });
31418
+ },
31180
31419
  async connectNip07() {
31420
+ persist("nip07");
31421
+ const current = ++generation2;
31181
31422
  closeClient();
31182
31423
  activeSigner = null;
31183
31424
  update({ method: "nip07", status: "connecting", pubkey: null, relay: null, error: null });
@@ -31185,14 +31426,18 @@ function createPajaSignerController(options) {
31185
31426
  const signer = readNip07Signer();
31186
31427
  if (!signer) throw new Error("NIP-07 signer not found");
31187
31428
  const pubkey2 = await signer.getPublicKey();
31429
+ if (current !== generation2) return;
31188
31430
  activeSigner = createNip07Adapter(signer);
31189
31431
  update({ method: "nip07", status: "connected", pubkey: pubkey2, relay: null, error: null });
31190
31432
  } catch (error) {
31433
+ if (current !== generation2) return;
31191
31434
  activeSigner = null;
31192
31435
  update({ method: "nip07", status: "error", pubkey: null, relay: null, error: toErrorMessage5(error) });
31193
31436
  }
31194
31437
  },
31195
31438
  async connectBunker(uri) {
31439
+ persist("nip46");
31440
+ const current = ++generation2;
31196
31441
  closeClient();
31197
31442
  activeSigner = null;
31198
31443
  const parsed = parseBunkerUri(uri.trim());
@@ -31213,15 +31458,27 @@ function createPajaSignerController(options) {
31213
31458
  bunkerPubkey: parsed.pubkey,
31214
31459
  secret: parsed.secret
31215
31460
  });
31216
- const pubkey2 = await client.connect();
31217
31461
  activeClient = client;
31462
+ const pubkey2 = await client.connect();
31463
+ if (current !== generation2) return;
31218
31464
  activeSigner = client.getSigner();
31219
31465
  update({ method: "nip46", status: "connected", pubkey: pubkey2, relay: parsed.relay, error: null });
31220
31466
  } catch (error) {
31467
+ if (current !== generation2) return;
31221
31468
  closeClient();
31222
31469
  activeSigner = null;
31223
31470
  update({ method: "nip46", status: "error", pubkey: null, relay: parsed.relay, error: toErrorMessage5(error) });
31224
31471
  }
31472
+ },
31473
+ async restorePreference() {
31474
+ const method = readPreference();
31475
+ if (method === "nip07") return this.connectNip07();
31476
+ if (method === "dev") return this.useDevSigner();
31477
+ if (method === "none") return this.useNoSigner();
31478
+ generation2 += 1;
31479
+ closeClient();
31480
+ activeSigner = null;
31481
+ update({ method: "nip46", status: "disconnected", pubkey: null, relay: null, error: null });
31225
31482
  }
31226
31483
  };
31227
31484
  }
@@ -31459,8 +31716,8 @@ function createSignerConsentChoices(consentStore, reportSignerConsentChange, sha
31459
31716
  ["paja-signer-consent-napplet-verb", `Allow all ${request.action === "publish" ? "publishing" : "signing"} from`],
31460
31717
  ["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.`]
31461
31718
  ]) {
31462
- const element4 = document.getElementById(id);
31463
- if (element4) element4.textContent = text2;
31719
+ const element3 = document.getElementById(id);
31720
+ if (element3) element3.textContent = text2;
31464
31721
  }
31465
31722
  };
31466
31723
  const rememberSignerChoice = (request) => {
@@ -31900,10 +32157,6 @@ function createHostSignerController(getState, refreshState, confirmRequest) {
31900
32157
  }
31901
32158
  });
31902
32159
  }
31903
- function hasNip07Signer() {
31904
- const signer = globalThis.nostr;
31905
- return typeof signer === "object" && signer !== null;
31906
- }
31907
32160
 
31908
32161
  // src/browser-host-runtime.ts
31909
32162
  function unregisterSingleFrameWindow(bridge, runtime, windowId) {
@@ -33320,9 +33573,9 @@ function readPersistedRuntimeTabs(config) {
33320
33573
  function persistRuntimeTabs(state) {
33321
33574
  const storage = runtimeTabsStorage(state.config);
33322
33575
  if (!storage) return;
33323
- const snapshot3 = snapshotRuntimeTabs(state);
33576
+ const snapshot4 = snapshotRuntimeTabs(state);
33324
33577
  try {
33325
- if (snapshot3) storage.setItem(PAJA_RUNTIME_TABS_STORAGE_KEY, JSON.stringify(snapshot3));
33578
+ if (snapshot4) storage.setItem(PAJA_RUNTIME_TABS_STORAGE_KEY, JSON.stringify(snapshot4));
33326
33579
  else storage.removeItem(PAJA_RUNTIME_TABS_STORAGE_KEY);
33327
33580
  } catch {
33328
33581
  }
@@ -33643,26 +33896,26 @@ function createPajaIntentLinkController(document2 = window.document, options = {
33643
33896
  }
33644
33897
 
33645
33898
  // src/browser-intent-builder-controls.ts
33646
- function element3(name, className) {
33899
+ function element2(name, className) {
33647
33900
  const result2 = document.createElement(name);
33648
33901
  if (className) result2.className = className;
33649
33902
  return result2;
33650
33903
  }
33651
33904
  function createSelect(label, controlId) {
33652
- const field = element3("label", "config-field");
33653
- const labelText = element3("span", "config-field-label");
33905
+ const field = element2("label", "config-field");
33906
+ const labelText = element2("span", "config-field-label");
33654
33907
  labelText.textContent = label;
33655
- const control = element3("select");
33908
+ const control = element2("select");
33656
33909
  control.id = controlId;
33657
33910
  field.htmlFor = control.id;
33658
33911
  field.append(labelText, control);
33659
33912
  return { field, control };
33660
33913
  }
33661
33914
  function createTextAreaField(label, controlId, readOnly = false) {
33662
- const field = element3("label", "config-field");
33663
- const labelText = element3("span", "config-field-label");
33915
+ const field = element2("label", "config-field");
33916
+ const labelText = element2("span", "config-field-label");
33664
33917
  labelText.textContent = label;
33665
- const control = element3("textarea");
33918
+ const control = element2("textarea");
33666
33919
  control.id = controlId;
33667
33920
  control.rows = readOnly ? 3 : 5;
33668
33921
  control.readOnly = readOnly;
@@ -33672,29 +33925,29 @@ function createTextAreaField(label, controlId, readOnly = false) {
33672
33925
  return { field, control };
33673
33926
  }
33674
33927
  function createIntentLinkBuilderElements(id) {
33675
- const dialog = element3("dialog", "config-dialog");
33928
+ const dialog = element2("dialog", "config-dialog");
33676
33929
  dialog.id = `${id}-dialog`;
33677
33930
  dialog.setAttribute("aria-labelledby", `${id}-title`);
33678
33931
  dialog.setAttribute("aria-describedby", `${id}-status`);
33679
- const form = element3("div", "dialog");
33680
- const title = element3("div", "dialog-title");
33932
+ const form = element2("div", "dialog");
33933
+ const title = element2("div", "dialog-title");
33681
33934
  title.id = `${id}-title`;
33682
33935
  title.textContent = "Create intent link";
33683
- const fields = element3("div", "config-fields");
33684
- const status = element3("div", "config-error");
33936
+ const fields = element2("div", "config-fields");
33937
+ const status = element2("div", "config-error");
33685
33938
  status.id = `${id}-status`;
33686
33939
  status.setAttribute("role", "status");
33687
33940
  status.setAttribute("aria-live", "polite");
33688
- const actions = element3("div", "dialog-actions");
33689
- const cancel = element3("button");
33941
+ const actions = element2("div", "dialog-actions");
33942
+ const cancel = element2("button");
33690
33943
  cancel.type = "button";
33691
33944
  cancel.id = `${id}-cancel`;
33692
33945
  cancel.textContent = "Cancel";
33693
- const copy = element3("button");
33946
+ const copy = element2("button");
33694
33947
  copy.type = "button";
33695
33948
  copy.id = `${id}-copy`;
33696
33949
  copy.textContent = "Copy link";
33697
- const test = element3("button");
33950
+ const test = element2("button");
33698
33951
  test.type = "button";
33699
33952
  test.id = `${id}-test`;
33700
33953
  test.textContent = "Test intent";
@@ -33705,21 +33958,21 @@ function createIntentLinkBuilderElements(id) {
33705
33958
  const convention = createSelect("Convention", `${id}-convention`);
33706
33959
  const routing = createSelect("Routing", `${id}-routing`);
33707
33960
  const payloadMode = createSelect("Payload mode", `${id}-payload-mode`);
33708
- const parameterGroup = element3("fieldset", "config-group");
33709
- const parameterLegend = element3("legend");
33961
+ const parameterGroup = element2("fieldset", "config-group");
33962
+ const parameterLegend = element2("legend");
33710
33963
  parameterLegend.textContent = "Parameters";
33711
- const parameterRows = element3("div");
33964
+ const parameterRows = element2("div");
33712
33965
  parameterRows.id = `${id}-parameters`;
33713
- const addParameter = element3("button");
33966
+ const addParameter = element2("button");
33714
33967
  addParameter.type = "button";
33715
33968
  addParameter.id = `${id}-add-parameter`;
33716
33969
  addParameter.textContent = "Add parameter";
33717
33970
  parameterGroup.append(parameterLegend, parameterRows, addParameter);
33718
33971
  const { field: jsonField, control: json } = createTextAreaField("JSON payload", `${id}-json-payload`);
33719
- const previewField = element3("label", "config-field");
33720
- const previewLabel = element3("span", "config-field-label");
33972
+ const previewField = element2("label", "config-field");
33973
+ const previewLabel = element2("span", "config-field-label");
33721
33974
  previewLabel.textContent = "Decoded preview";
33722
- const preview = element3("output");
33975
+ const preview = element2("output");
33723
33976
  preview.id = `${id}-preview`;
33724
33977
  previewField.append(previewLabel, preview);
33725
33978
  const { field: linkField, control: link } = createTextAreaField("Copyable URL", `${id}-url`, true);
@@ -33751,12 +34004,12 @@ function createIntentLinkBuilderElements(id) {
33751
34004
  link
33752
34005
  };
33753
34006
  }
33754
- function appendIntentLinkBuilderOption(select2, value, label, disabled = false) {
33755
- const option = element3("option");
34007
+ function appendIntentLinkBuilderOption(select3, value, label, disabled = false) {
34008
+ const option = element2("option");
33756
34009
  option.value = value;
33757
34010
  option.textContent = label;
33758
34011
  option.disabled = disabled;
33759
- select2.append(option);
34012
+ select3.append(option);
33760
34013
  }
33761
34014
 
33762
34015
  // src/browser-intent-builder-rows.ts
@@ -34278,11 +34531,11 @@ function originLabel(getIdentity, windowId) {
34278
34531
  return identity?.dTag ? `${identity.dTag} \xB7 ${windowId}` : windowId;
34279
34532
  }
34280
34533
  function button(document2, label, className) {
34281
- const element4 = document2.createElement("button");
34282
- element4.type = "button";
34283
- element4.className = className;
34284
- element4.textContent = label;
34285
- return element4;
34534
+ const element3 = document2.createElement("button");
34535
+ element3.type = "button";
34536
+ element3.className = className;
34537
+ element3.textContent = label;
34538
+ return element3;
34286
34539
  }
34287
34540
  function createPajaNotifyController(options) {
34288
34541
  const document2 = options.document ?? globalThis.document;
@@ -34605,22 +34858,22 @@ function renderObjectFields(document2, parent, schema, values, path, bindings, s
34605
34858
  }
34606
34859
  function createFieldBinding(document2, path, schema, current, required) {
34607
34860
  if (Array.isArray(schema.enum)) {
34608
- const select2 = document2.createElement("select");
34609
- select2.required = required;
34861
+ const select3 = document2.createElement("select");
34862
+ select3.required = required;
34610
34863
  if (!required) {
34611
34864
  const empty = document2.createElement("option");
34612
34865
  empty.value = "";
34613
34866
  empty.textContent = "Not set";
34614
- select2.append(empty);
34867
+ select3.append(empty);
34615
34868
  }
34616
34869
  for (const [index, value] of schema.enum.entries()) {
34617
34870
  const option = document2.createElement("option");
34618
34871
  option.value = JSON.stringify(value);
34619
34872
  option.textContent = Array.isArray(schema.enumDescriptions) && typeof schema.enumDescriptions[index] === "string" ? `${String(value)} \u2014 ${schema.enumDescriptions[index]}` : String(value);
34620
34873
  option.selected = Object.is(value, current);
34621
- select2.append(option);
34874
+ select3.append(option);
34622
34875
  }
34623
- return { element: select2, read: () => select2.value === "" ? void 0 : JSON.parse(select2.value) };
34876
+ return { element: select3, read: () => select3.value === "" ? void 0 : JSON.parse(select3.value) };
34624
34877
  }
34625
34878
  if (schema.type === "boolean") {
34626
34879
  const input2 = document2.createElement("input");
@@ -34926,16 +35179,16 @@ async function loadRuntimePointer(state, context, value, options = {}) {
34926
35179
  appendPajaMessageLog(state, "paja", { type: "paja.pointer.error", error: message3 });
34927
35180
  }
34928
35181
  }
34929
- async function restorePersistedRuntimeTabs(state, context, snapshot3) {
34930
- for (const pointer of snapshot3.pointers) {
35182
+ async function restorePersistedRuntimeTabs(state, context, snapshot4) {
35183
+ for (const pointer of snapshot4.pointers) {
34931
35184
  await loadRuntimePointer(state, context, pointer, { skipDuplicatePrompt: true, persist: false });
34932
35185
  }
34933
- const activeTab = state.tabs[snapshot3.activeIndex] ?? state.tabs[0];
35186
+ const activeTab = state.tabs[snapshot4.activeIndex] ?? state.tabs[0];
34934
35187
  if (activeTab) activateRuntimeTab(state, context, activeTab.id);
34935
35188
  persistRuntimeTabs2(state);
34936
35189
  }
34937
- async function hydratePersistedIntentCatalog(state, context, snapshot3) {
34938
- const pointers = /* @__PURE__ */ new Set([...readPajaIntentCatalogPointers(), ...snapshot3?.pointers ?? []]);
35190
+ async function hydratePersistedIntentCatalog(state, context, snapshot4) {
35191
+ const pointers = /* @__PURE__ */ new Set([...readPajaIntentCatalogPointers(), ...snapshot4?.pointers ?? []]);
34939
35192
  await Promise.all([...pointers].map(async (pointer) => {
34940
35193
  try {
34941
35194
  const resolved = await resolvePajaPointer(pointer, pajaPointerResolverOptions(context));
@@ -35046,6 +35299,9 @@ function createPajaBrowserState(context, relayEventCounts, relayInventory) {
35046
35299
  useDevSigner() {
35047
35300
  signerController.useDevSigner();
35048
35301
  },
35302
+ useNoSigner() {
35303
+ signerController.useNoSigner();
35304
+ },
35049
35305
  connectNip07() {
35050
35306
  return signerController.connectNip07();
35051
35307
  },
@@ -35208,18 +35464,24 @@ async function installPajaHost() {
35208
35464
  const permissionMount = document.getElementById("paja-permission-ui");
35209
35465
  if (!permissionMount) throw new Error("Paja Firewall permission mount is missing");
35210
35466
  let permissionBridge = null;
35467
+ const retiringPrincipals = /* @__PURE__ */ new Set();
35211
35468
  const permissionController = createPajaPermissionAdapter({
35212
35469
  mount: permissionMount,
35213
35470
  getPermissions: () => permissionBridge?.runtime.permissions,
35471
+ labelForPrincipal: (principal) => pajaPrincipalLabel(config, stateRef?.tabs ?? [], principal),
35214
35472
  onGrantRevoked(grant2) {
35215
35473
  if (!stateRef) return;
35216
35474
  const revoked = permissionPrincipalKey(grant2.principal);
35475
+ if (retiringPrincipals.has(revoked)) return;
35476
+ retiringPrincipals.add(revoked);
35477
+ queueMicrotask(() => retiringPrincipals.delete(revoked));
35217
35478
  if (config.target.mode === "runtime-pointer") {
35218
35479
  for (const tabId of revokedPajaTabIds(config, stateRef.tabs, grant2)) stateRef.closeTab(tabId);
35219
35480
  } else {
35220
35481
  const source = frame?.contentWindow;
35221
35482
  const principal = source ? originRegistry.getIdentity(source)?.permissionPrincipal : void 0;
35222
- if (principal && permissionPrincipalKey(principal) === revoked) stateRef.reload();
35483
+ const retired = contextRef?.runtime.currentWindowId === null;
35484
+ if (retired || principal && permissionPrincipalKey(principal) === revoked) stateRef.reload();
35223
35485
  }
35224
35486
  }
35225
35487
  });
@@ -35375,7 +35637,7 @@ async function installPajaHost() {
35375
35637
  startFrameNavigation(state, context);
35376
35638
  void reportTargetCorsDiagnostic(state);
35377
35639
  }
35378
- if (hasNip07Signer()) void state.connectNip07();
35640
+ void signerController.restorePreference();
35379
35641
  }
35380
35642
  if (typeof document !== "undefined") {
35381
35643
  try {