@aglyn/tenant-feature-instance 1.22.3 → 1.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/tenant-feature-instance",
3
- "version": "1.22.3",
3
+ "version": "1.23.0",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,12 +25,12 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.22.3",
29
- "@aglyn/shared-data-enums": "1.22.3",
30
- "@aglyn/shared-ui-jsx": "1.22.3",
31
- "@aglyn/shared-util-email": "1.22.3",
32
- "@aglyn/shared-util-http": "1.22.3",
33
- "@aglyn/shared-util-timestamp": "1.22.3",
28
+ "@aglyn/aglyn": "1.23.0",
29
+ "@aglyn/shared-data-enums": "1.23.0",
30
+ "@aglyn/shared-ui-jsx": "1.23.0",
31
+ "@aglyn/shared-util-email": "1.23.0",
32
+ "@aglyn/shared-util-http": "1.23.0",
33
+ "@aglyn/shared-util-timestamp": "1.23.0",
34
34
  "@swc/helpers": "0.5.24",
35
35
  "lodash-es": "^4.18.1",
36
36
  "mobx": "^7.1.6"
@@ -130,6 +130,30 @@ export declare const REFUSED_RETRY_CEILING_MS: number;
130
130
  * term keeps growing for as long as the streak lasts.
131
131
  */
132
132
  export declare function refusedRetryDelayMs(streakStartedAt: number): number;
133
+ /** The longest an arrival is ever held back from reopening a refused listen. */
134
+ export declare const REFUSED_ARRIVAL_CEILING_MS: number;
135
+ /**
136
+ * How soon after a refusal an ARRIVAL (focus, the tab becoming visible) may
137
+ * reopen the listen.
138
+ *
139
+ * It was a flat 2s, on the reasoning that an arrival is a person. It is not
140
+ * always one: a window that is driven rather than used (a second monitor
141
+ * beside a busy app, a browser under automation, a kiosk shell) takes focus
142
+ * events all day, and each reopen that is refused schedules the next, which
143
+ * the next focus event wakes 2s later. A console left open on a session that
144
+ * could read nothing ran every listener on its page that way for 20 hours on
145
+ * 2026-11-15/16: 107,000 refusals, up to 247 a minute, against a normal day
146
+ * of about 100.
147
+ *
148
+ * So the hold grows with the streak's age like the timer does, a twentieth
149
+ * of it up to two minutes. A young fault still answers an arrival in 2s. An
150
+ * old one answers at most every two minutes, which caps a churning window at
151
+ * 30 reopens an hour per listener, and a person coming back to a backed-off
152
+ * page is still served at once in the usual case, because the refusal that
153
+ * scheduled the pending reopen is minutes old by then. A re-authentication
154
+ * never waits on this: the heal broadcast reopens with no hold at all.
155
+ */
156
+ export declare function refusedArrivalDelayMs(streakStartedAt: number): number;
133
157
  /**
134
158
  * Schedule the reopen of a spent refusal streak, and return its cancel.
135
159
  *
@@ -143,9 +167,9 @@ export declare function refusedRetryDelayMs(streakStartedAt: number): number;
143
167
  * A person arriving reopens at once, whatever the cadence: the tab becoming
144
168
  * visible or the window regaining focus. (The heal broadcast is the third
145
169
  * instant road; the hooks subscribe to it themselves.) Arrivals are held to
146
- * one reopen no sooner than {@link SESSION_REFUSED_RETRY_DELAY_MS} after the
147
- * refusal that scheduled this, so focus churn can never run the loop faster
148
- * than the fixed cadence it replaced.
170
+ * one reopen no sooner than {@link refusedArrivalDelayMs} after the refusal
171
+ * that scheduled this, so focus churn can never run the loop faster than 2s,
172
+ * and runs it slower the longer the refusals have lasted.
149
173
  */
150
174
  export declare function scheduleRefusedReopen(reopen: () => void, streakStartedAt: number): () => void;
151
175
  /**
@@ -128,6 +128,32 @@ export const RULES_REFUSED_RETRY_DELAY_MS = 60000;
128
128
  const age = Math.max(0, Date.now() - streakStartedAt);
129
129
  return Math.min(REFUSED_RETRY_CEILING_MS, Math.max(floor, age / REFUSED_RETRY_AGE_DIVISOR));
130
130
  }
131
+ /** The longest an arrival is ever held back from reopening a refused listen. */ export const REFUSED_ARRIVAL_CEILING_MS = 2 * 60000;
132
+ /** An arrival's hold is the streak's age divided by this, floor to ceiling. */ const REFUSED_ARRIVAL_AGE_DIVISOR = 20;
133
+ /**
134
+ * How soon after a refusal an ARRIVAL (focus, the tab becoming visible) may
135
+ * reopen the listen.
136
+ *
137
+ * It was a flat 2s, on the reasoning that an arrival is a person. It is not
138
+ * always one: a window that is driven rather than used (a second monitor
139
+ * beside a busy app, a browser under automation, a kiosk shell) takes focus
140
+ * events all day, and each reopen that is refused schedules the next, which
141
+ * the next focus event wakes 2s later. A console left open on a session that
142
+ * could read nothing ran every listener on its page that way for 20 hours on
143
+ * 2026-11-15/16: 107,000 refusals, up to 247 a minute, against a normal day
144
+ * of about 100.
145
+ *
146
+ * So the hold grows with the streak's age like the timer does, a twentieth
147
+ * of it up to two minutes. A young fault still answers an arrival in 2s. An
148
+ * old one answers at most every two minutes, which caps a churning window at
149
+ * 30 reopens an hour per listener, and a person coming back to a backed-off
150
+ * page is still served at once in the usual case, because the refusal that
151
+ * scheduled the pending reopen is minutes old by then. A re-authentication
152
+ * never waits on this: the heal broadcast reopens with no hold at all.
153
+ */ export function refusedArrivalDelayMs(streakStartedAt) {
154
+ const age = Math.max(0, Date.now() - streakStartedAt);
155
+ return Math.min(REFUSED_ARRIVAL_CEILING_MS, Math.max(SESSION_REFUSED_RETRY_DELAY_MS, age / REFUSED_ARRIVAL_AGE_DIVISOR));
156
+ }
131
157
  /** No `document` (SSR, a worker) counts as visible: nothing to wait for. */ function tabIsHidden() {
132
158
  return typeof document !== 'undefined' && document.visibilityState === 'hidden';
133
159
  }
@@ -144,9 +170,9 @@ export const RULES_REFUSED_RETRY_DELAY_MS = 60000;
144
170
  * A person arriving reopens at once, whatever the cadence: the tab becoming
145
171
  * visible or the window regaining focus. (The heal broadcast is the third
146
172
  * instant road; the hooks subscribe to it themselves.) Arrivals are held to
147
- * one reopen no sooner than {@link SESSION_REFUSED_RETRY_DELAY_MS} after the
148
- * refusal that scheduled this, so focus churn can never run the loop faster
149
- * than the fixed cadence it replaced.
173
+ * one reopen no sooner than {@link refusedArrivalDelayMs} after the refusal
174
+ * that scheduled this, so focus churn can never run the loop faster than 2s,
175
+ * and runs it slower the longer the refusals have lasted.
150
176
  */ export function scheduleRefusedReopen(reopen, streakStartedAt) {
151
177
  const scheduledAt = Date.now();
152
178
  let timer = null;
@@ -174,7 +200,7 @@ export const RULES_REFUSED_RETRY_DELAY_MS = 60000;
174
200
  };
175
201
  const onArrival = ()=>{
176
202
  if (tabIsHidden()) return;
177
- arm(scheduledAt + SESSION_REFUSED_RETRY_DELAY_MS);
203
+ arm(scheduledAt + refusedArrivalDelayMs(streakStartedAt));
178
204
  };
179
205
  // `visibilitychange` fires on the way INTO hidden as well as out of it.
180
206
  const onVisibilityChange = ()=>{
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/firestore-denial-reporter.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Let a LISTENER tell the app its reads are being refused (AGL-1066).\n *\n * `session-health` was built around one-shot reads, because that is where\n * AGL-1062 was first noticed. The console is listener-first, so the detector\n * was watching the read style the console barely uses: only four one-shot\n * call sites pass a collection label, one of them fires once per mount and\n * so can never recur inside the 60s window, and none of the pages carrying a\n * stale-write guard issues a labelled read at all. The verdict was\n * unreachable on the surfaces that needed it.\n *\n * Listeners are on every page, and they already know which collection they\n * are reading, so labelling is free rather than something a caller must\n * remember. This is the seam that lets them report without the library\n * importing the app: the console registers `reportDeniedRead` at startup and\n * the hooks call it through here. An unregistered reporter is a no-op, which\n * is what the tenant runtime wants — it has no client Firestore at all.\n *\n * ## Why this cannot fire offline\n *\n * Only `permission-denied` is ever reported. A client that has simply lost\n * the network gets no error callback at all — the listen sits there and the\n * cache keeps answering — and any one-shot it does make fails `unavailable`.\n * That is what keeps the whole mechanism from mistaking a tunnel for a dead\n * session, and it is why callers must NOT relax the code check.\n *\n * The channel runs both ways: see {@link reportFirestoreSessionHeal} at the\n * bottom of this file for the return leg, which is how a refused listener\n * learns the session came back. It lives here rather than in a module of its\n * own because a heal is defined entirely in terms of the denial it reverses —\n * split them and someone broadcasts one without the other's rules.\n */\n\nexport interface FirestoreSessionReporters {\n /** A listen was refused past the budget; names the collection. */\n onDenied: (collection?: string) => void\n /**\n * A listen was answered BY THE SERVER.\n *\n * Reported as well as the denials, and it is what keeps this safe to turn\n * on. A scoped collaborator (AGL-1041) has collections they may not read\n * by design, and with listeners reporting they could otherwise accumulate\n * two denied collections and be told their session is dead. But their\n * other listens keep succeeding against the server, and one server answer\n * clears the evidence outright — a genuinely dead session has no such\n * answer to offer, so it is the discriminator the denial count alone\n * cannot be.\n *\n * A CACHED snapshot must never be passed here; it proves nothing.\n */\n onServerRead: () => void\n}\n\nlet reporters: FirestoreSessionReporters | null = null\n\n/**\n * Register the app's reporters. Called once, by the app that owns\n * `session-health`. Pass `null` to unregister (tests).\n */\nexport function setFirestoreSessionReporters(\n next: FirestoreSessionReporters | null,\n): void {\n reporters = next\n}\n\n/** Report a refused listen. No-op when nothing is registered. */\nexport function reportFirestoreDenial(collection?: string): void {\n reporters?.onDenied(collection)\n}\n\n/** Report a listen the SERVER answered. No-op when nothing is registered. */\nexport function reportFirestoreServerRead(): void {\n noteFirestoreServerRead()\n reporters?.onServerRead()\n}\n\n/**\n * When ANY listener in this tab last got a server-answered snapshot.\n *\n * Library-internal evidence, kept regardless of whether app reporters are\n * registered — `helpers/use-doc` deliberately does not feed `session-health`\n * (its callers are the besigner document family, where a false verdict hurts\n * most) but its server answers are still proof the session can read, and\n * {@link refusedRetryDelayMs} needs that proof from every hook.\n */\nlet lastServerReadAt = 0\n\n/**\n * Record a server-answered snapshot WITHOUT reporting to `session-health`.\n * `reportFirestoreServerRead` calls this; `helpers/use-doc` calls only this.\n */\nexport function noteFirestoreServerRead(): void {\n lastServerReadAt = Date.now()\n}\n\n/** Test seam — the evidence is module scope by design. */\nexport function resetFirestoreServerReadEvidence(): void {\n lastServerReadAt = 0\n}\n\n/**\n * Cadence for a refusal streak that has outlived the retry budget (AGL-1066).\n *\n * A `permission-denied` has two very different causes and the client cannot\n * tell them apart from the error alone:\n *\n * - a SESSION fault — stale token, App Check hiccup, an AGL-1143 SSO\n * session that refuses everything. Every listener in the tab is refused,\n * and the heal is an AGL-664 in-place re-auth or a token that attaches\n * late. A young fault usually heals within seconds, so it starts at 2s.\n *\n * - a RULES denial — the ref itself is one this user may never read (a\n * sentinel id, a scoped collaborator's off-limits collection). Only a\n * rules change (a membership granted mid-session) can end it, so it\n * starts at 60s (AGL-1440).\n *\n * The discriminator is the one this module already trusts for the\n * session-health verdict: A GENUINELY DEAD SESSION HAS NO SERVER ANSWER TO\n * OFFER. If any listener has been answered by the server since this\n * listener's streak began, the session can read and this refusal is about\n * the ref.\n *\n * Either way the delay then grows with the streak's age — a tenth of it, up\n * to five minutes (AGL-2945). A refusal that has lasted ten minutes is\n * unlikely to end in the next two seconds, and refused listens are not free:\n * they bill reads (AGL-2944), so a fixed cadence made every console left open\n * on a dead session a standing cost of 1,800 refusals an hour per listener.\n * Per listener a session fault now costs ~70 in its first hour and 12 an hour\n * after; a rules denial ~35, then 12. The listen is never abandoned.\n *\n * What the fast fixed cadence used to protect is kept as WAKES rather than as\n * a timer — see {@link scheduleRefusedReopen}. The AGL-664 heal broadcast, the\n * tab becoming visible and the window regaining focus all reopen at once, so\n * the slow road only governs a page nobody is touching. The AGL-1358 write\n * guards wait on a save someone clicks, which puts someone at the page.\n */\nexport const SESSION_REFUSED_RETRY_DELAY_MS = 2_000\nexport const RULES_REFUSED_RETRY_DELAY_MS = 60_000\n/** The longest a refused listen ever waits for its next reopen. */\nexport const REFUSED_RETRY_CEILING_MS = 5 * 60_000\n/** The delay is the streak's age divided by this, between floor and ceiling. */\nconst REFUSED_RETRY_AGE_DIVISOR = 10\n\n/**\n * The delay before a spent refusal streak reopens its listen.\n *\n * `streakStartedAt` is when the streak's FIRST refusal landed. Evaluated per\n * retry, not once: evidence that arrives mid-streak (another listener's\n * first server answer) raises the floor from the next reopen on, and the age\n * term keeps growing for as long as the streak lasts.\n */\nexport function refusedRetryDelayMs(streakStartedAt: number): number {\n const floor =\n lastServerReadAt > streakStartedAt\n ? RULES_REFUSED_RETRY_DELAY_MS\n : SESSION_REFUSED_RETRY_DELAY_MS\n // A backwards clock reads as a young streak, never as a negative age.\n const age = Math.max(0, Date.now() - streakStartedAt)\n return Math.min(\n REFUSED_RETRY_CEILING_MS,\n Math.max(floor, age / REFUSED_RETRY_AGE_DIVISOR),\n )\n}\n\n/** No `document` (SSR, a worker) counts as visible: nothing to wait for. */\nfunction tabIsHidden(): boolean {\n return (\n typeof document !== 'undefined' && document.visibilityState === 'hidden'\n )\n}\n\n/**\n * Schedule the reopen of a spent refusal streak, and return its cancel.\n *\n * In a visible tab the reopen waits {@link refusedRetryDelayMs}. A HIDDEN tab\n * sets no timer at all: nobody is there to heal for, and an unattended tab on\n * a dead session was the Aug 20 – Sep 4 storm — 400K–1.7M rules denials a day\n * in ~8-hour blocks, ~$2 of reads the `read_ops_count` metric never showed\n * (AGL-2944). A tab that goes hidden while a reopen is pending drops its\n * timer and waits the same way.\n *\n * A person arriving reopens at once, whatever the cadence: the tab becoming\n * visible or the window regaining focus. (The heal broadcast is the third\n * instant road; the hooks subscribe to it themselves.) Arrivals are held to\n * one reopen no sooner than {@link SESSION_REFUSED_RETRY_DELAY_MS} after the\n * refusal that scheduled this, so focus churn can never run the loop faster\n * than the fixed cadence it replaced.\n */\nexport function scheduleRefusedReopen(\n reopen: () => void,\n streakStartedAt: number,\n): () => void {\n const scheduledAt = Date.now()\n let timer: ReturnType<typeof setTimeout> | null = null\n let dueAt = Number.POSITIVE_INFINITY\n let settled = false\n\n const disarm = () => {\n if (timer !== null) clearTimeout(timer)\n timer = null\n dueAt = Number.POSITIVE_INFINITY\n }\n\n const fire = () => {\n if (settled) return\n cancel()\n reopen()\n }\n\n /** Reopen no later than `atMs`; an earlier due time already set wins. */\n const arm = (atMs: number) => {\n if (settled || atMs >= dueAt) return\n if (atMs <= Date.now()) {\n fire()\n return\n }\n if (timer !== null) clearTimeout(timer)\n dueAt = atMs\n timer = setTimeout(fire, atMs - Date.now())\n }\n\n const onArrival = () => {\n if (tabIsHidden()) return\n arm(scheduledAt + SESSION_REFUSED_RETRY_DELAY_MS)\n }\n\n // `visibilitychange` fires on the way INTO hidden as well as out of it.\n const onVisibilityChange = () => {\n if (tabIsHidden()) disarm()\n else onArrival()\n }\n\n const cancel = () => {\n settled = true\n disarm()\n if (typeof document !== 'undefined') {\n document.removeEventListener('visibilitychange', onVisibilityChange)\n }\n if (typeof window !== 'undefined') {\n window.removeEventListener('focus', onArrival)\n }\n }\n\n if (typeof document !== 'undefined') {\n document.addEventListener('visibilitychange', onVisibilityChange)\n }\n if (typeof window !== 'undefined') {\n window.addEventListener('focus', onArrival)\n }\n if (!tabIsHidden()) arm(scheduledAt + refusedRetryDelayMs(streakStartedAt))\n\n return cancel\n}\n\n/**\n * The same seam in the other direction: the app telling refused listeners\n * that the session came back (AGL-1066).\n *\n * ## Why this has to exist\n *\n * A refused listen recovers today only because the retry loop never stops —\n * every reopen is another chance for the token to have attached. That is also\n * the single reason the AGL-664 in-place re-auth works at all: nothing else\n * re-subscribes. The hooks' effects depend on the query's identity\n * (`[ref.firestore, ref.path]` and each caller's `deps`), and a `stale`-reason\n * re-auth signs the same uid back in, so no dependency changes and no effect\n * re-runs. `AuthenticatedLayout` deliberately holds the tree MOUNTED while a\n * re-auth prompt is pending (AGL-664), which is what makes \"resume exactly\n * where you were\" true — and it is exactly why a remount cannot be relied on\n * to reopen anything.\n *\n * So any change that lets a refusal streak go terminal — the AGL-1066 item-3\n * flip — needs this channel first, or a user who re-authenticates\n * successfully sits in front of an errored console until they reload.\n *\n * ## What may broadcast, and what must not\n *\n * A heal is a RECOVERY FROM DENIAL, not any token event. Firebase refreshes\n * the ID token roughly hourly; broadcasting on that would reopen every\n * listener in the console on a timer for no reason. The console broadcasts\n * from one place — a session fault that has been resolved — see\n * `apps/console/utils/session-heal.ts`.\n *\n * Subscribers gate themselves as well: a listener the server is NOT refusing\n * ignores the broadcast entirely, so even a spurious heal costs nothing.\n * Nothing here clears `serverDenied` or `deniedStreak` — only a snapshot the\n * server answered is evidence, and that invariant does not bend for a\n * hopeful signal from the auth layer.\n */\nconst healListeners = new Set<() => void>()\n\n/**\n * Listen for \"the session may have recovered\". Returns the unsubscribe.\n *\n * The callback runs synchronously inside {@link reportFirestoreSessionHeal},\n * so it must be cheap and must tolerate being called when there is nothing\n * to do.\n */\nexport function subscribeFirestoreSessionHeal(\n listener: () => void,\n): () => void {\n healListeners.add(listener)\n return () => void healListeners.delete(listener)\n}\n\n/**\n * Tell every listener the session may have recovered.\n *\n * Iterates a COPY: a subscriber reopening its listen can unsubscribe (an\n * unmount racing the broadcast) and mutating the set mid-iteration would skip\n * the next one.\n */\nexport function reportFirestoreSessionHeal(): void {\n for (const listener of [...healListeners]) listener()\n}\n\n/**\n * Consecutive refusals before a listener says anything.\n *\n * Matched to `firestore-one-shot-retry`'s budget so both read styles apply\n * the same bar: surviving this many means it is not the AGL-216/217\n * post-sign-in race, which resolves in well under two seconds.\n *\n * The streak this counts is NOT the hook's retry `attempt`. That one is\n * reset by any snapshot, including one served from cache, so under\n * `persistentLocalCache` it never reaches any threshold at all — see\n * `use-firestore-collection-cached-retry.spec.ts`. This one is reset only by\n * a snapshot the SERVER answered, which is the only evidence that actually\n * bears on whether the session can read.\n */\nexport const DENIAL_STREAK_TO_REPORT = 5\n\n/**\n * The collection a listen was against, when it can be known from public API.\n *\n * `DocumentReference` exposes `parent`, and a `CollectionReference` exposes\n * `path`. A filtered `Query` exposes neither, and reaching into `_query` to\n * get one would be reading SDK internals — so those report `undefined` and\n * land in the shared `unknown` bucket. That can only ever fail to reach the\n * two-collection threshold, never trip it falsely, which is the right way\n * for this to degrade.\n */\nexport function denialLabelForQuery(target: unknown): string | undefined {\n const candidate = target as\n | { type?: string; path?: string; parent?: { path?: string } }\n | null\n | undefined\n if (!candidate) return undefined\n // A document listen: name the collection that holds it, not the document,\n // so two docs in one collection stay ONE piece of evidence.\n if (candidate.parent?.path) return candidate.parent.path\n if (candidate.type === 'collection' && candidate.path) return candidate.path\n return undefined\n}\n"],"names":["reporters","setFirestoreSessionReporters","next","reportFirestoreDenial","collection","onDenied","reportFirestoreServerRead","noteFirestoreServerRead","onServerRead","lastServerReadAt","Date","now","resetFirestoreServerReadEvidence","SESSION_REFUSED_RETRY_DELAY_MS","RULES_REFUSED_RETRY_DELAY_MS","REFUSED_RETRY_CEILING_MS","REFUSED_RETRY_AGE_DIVISOR","refusedRetryDelayMs","streakStartedAt","floor","age","Math","max","min","tabIsHidden","document","visibilityState","scheduleRefusedReopen","reopen","scheduledAt","timer","dueAt","Number","POSITIVE_INFINITY","settled","disarm","clearTimeout","fire","cancel","arm","atMs","setTimeout","onArrival","onVisibilityChange","removeEventListener","window","addEventListener","healListeners","Set","subscribeFirestoreSessionHeal","listener","add","delete","reportFirestoreSessionHeal","DENIAL_STREAK_TO_REPORT","denialLabelForQuery","target","candidate","undefined","parent","path","type"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA+BC,GAsBD,IAAIA,YAA8C;AAElD;;;CAGC,GACD,OAAO,SAASC,6BACdC,IAAsC;IAEtCF,YAAYE;AACd;AAEA,+DAA+D,GAC/D,OAAO,SAASC,sBAAsBC,UAAmB;IACvDJ,6BAAAA,UAAWK,QAAQ,CAACD;AACtB;AAEA,2EAA2E,GAC3E,OAAO,SAASE;IACdC;IACAP,6BAAAA,UAAWQ,YAAY;AACzB;AAEA;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IAAI,KAAK,gBAAgBJ,UAAUG,IAAI,EAAE,OAAOH,UAAUG,IAAI;IAC5E,OAAOF;AACT"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/firestore-denial-reporter.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Let a LISTENER tell the app its reads are being refused (AGL-1066).\n *\n * `session-health` was built around one-shot reads, because that is where\n * AGL-1062 was first noticed. The console is listener-first, so the detector\n * was watching the read style the console barely uses: only four one-shot\n * call sites pass a collection label, one of them fires once per mount and\n * so can never recur inside the 60s window, and none of the pages carrying a\n * stale-write guard issues a labelled read at all. The verdict was\n * unreachable on the surfaces that needed it.\n *\n * Listeners are on every page, and they already know which collection they\n * are reading, so labelling is free rather than something a caller must\n * remember. This is the seam that lets them report without the library\n * importing the app: the console registers `reportDeniedRead` at startup and\n * the hooks call it through here. An unregistered reporter is a no-op, which\n * is what the tenant runtime wants — it has no client Firestore at all.\n *\n * ## Why this cannot fire offline\n *\n * Only `permission-denied` is ever reported. A client that has simply lost\n * the network gets no error callback at all — the listen sits there and the\n * cache keeps answering — and any one-shot it does make fails `unavailable`.\n * That is what keeps the whole mechanism from mistaking a tunnel for a dead\n * session, and it is why callers must NOT relax the code check.\n *\n * The channel runs both ways: see {@link reportFirestoreSessionHeal} at the\n * bottom of this file for the return leg, which is how a refused listener\n * learns the session came back. It lives here rather than in a module of its\n * own because a heal is defined entirely in terms of the denial it reverses —\n * split them and someone broadcasts one without the other's rules.\n */\n\nexport interface FirestoreSessionReporters {\n /** A listen was refused past the budget; names the collection. */\n onDenied: (collection?: string) => void\n /**\n * A listen was answered BY THE SERVER.\n *\n * Reported as well as the denials, and it is what keeps this safe to turn\n * on. A scoped collaborator (AGL-1041) has collections they may not read\n * by design, and with listeners reporting they could otherwise accumulate\n * two denied collections and be told their session is dead. But their\n * other listens keep succeeding against the server, and one server answer\n * clears the evidence outright — a genuinely dead session has no such\n * answer to offer, so it is the discriminator the denial count alone\n * cannot be.\n *\n * A CACHED snapshot must never be passed here; it proves nothing.\n */\n onServerRead: () => void\n}\n\nlet reporters: FirestoreSessionReporters | null = null\n\n/**\n * Register the app's reporters. Called once, by the app that owns\n * `session-health`. Pass `null` to unregister (tests).\n */\nexport function setFirestoreSessionReporters(\n next: FirestoreSessionReporters | null,\n): void {\n reporters = next\n}\n\n/** Report a refused listen. No-op when nothing is registered. */\nexport function reportFirestoreDenial(collection?: string): void {\n reporters?.onDenied(collection)\n}\n\n/** Report a listen the SERVER answered. No-op when nothing is registered. */\nexport function reportFirestoreServerRead(): void {\n noteFirestoreServerRead()\n reporters?.onServerRead()\n}\n\n/**\n * When ANY listener in this tab last got a server-answered snapshot.\n *\n * Library-internal evidence, kept regardless of whether app reporters are\n * registered — `helpers/use-doc` deliberately does not feed `session-health`\n * (its callers are the besigner document family, where a false verdict hurts\n * most) but its server answers are still proof the session can read, and\n * {@link refusedRetryDelayMs} needs that proof from every hook.\n */\nlet lastServerReadAt = 0\n\n/**\n * Record a server-answered snapshot WITHOUT reporting to `session-health`.\n * `reportFirestoreServerRead` calls this; `helpers/use-doc` calls only this.\n */\nexport function noteFirestoreServerRead(): void {\n lastServerReadAt = Date.now()\n}\n\n/** Test seam — the evidence is module scope by design. */\nexport function resetFirestoreServerReadEvidence(): void {\n lastServerReadAt = 0\n}\n\n/**\n * Cadence for a refusal streak that has outlived the retry budget (AGL-1066).\n *\n * A `permission-denied` has two very different causes and the client cannot\n * tell them apart from the error alone:\n *\n * - a SESSION fault — stale token, App Check hiccup, an AGL-1143 SSO\n * session that refuses everything. Every listener in the tab is refused,\n * and the heal is an AGL-664 in-place re-auth or a token that attaches\n * late. A young fault usually heals within seconds, so it starts at 2s.\n *\n * - a RULES denial — the ref itself is one this user may never read (a\n * sentinel id, a scoped collaborator's off-limits collection). Only a\n * rules change (a membership granted mid-session) can end it, so it\n * starts at 60s (AGL-1440).\n *\n * The discriminator is the one this module already trusts for the\n * session-health verdict: A GENUINELY DEAD SESSION HAS NO SERVER ANSWER TO\n * OFFER. If any listener has been answered by the server since this\n * listener's streak began, the session can read and this refusal is about\n * the ref.\n *\n * Either way the delay then grows with the streak's age — a tenth of it, up\n * to five minutes (AGL-2945). A refusal that has lasted ten minutes is\n * unlikely to end in the next two seconds, and refused listens are not free:\n * they bill reads (AGL-2944), so a fixed cadence made every console left open\n * on a dead session a standing cost of 1,800 refusals an hour per listener.\n * Per listener a session fault now costs ~70 in its first hour and 12 an hour\n * after; a rules denial ~35, then 12. The listen is never abandoned.\n *\n * What the fast fixed cadence used to protect is kept as WAKES rather than as\n * a timer — see {@link scheduleRefusedReopen}. The AGL-664 heal broadcast, the\n * tab becoming visible and the window regaining focus all reopen at once, so\n * the slow road only governs a page nobody is touching. The AGL-1358 write\n * guards wait on a save someone clicks, which puts someone at the page.\n */\nexport const SESSION_REFUSED_RETRY_DELAY_MS = 2_000\nexport const RULES_REFUSED_RETRY_DELAY_MS = 60_000\n/** The longest a refused listen ever waits for its next reopen. */\nexport const REFUSED_RETRY_CEILING_MS = 5 * 60_000\n/** The delay is the streak's age divided by this, between floor and ceiling. */\nconst REFUSED_RETRY_AGE_DIVISOR = 10\n\n/**\n * The delay before a spent refusal streak reopens its listen.\n *\n * `streakStartedAt` is when the streak's FIRST refusal landed. Evaluated per\n * retry, not once: evidence that arrives mid-streak (another listener's\n * first server answer) raises the floor from the next reopen on, and the age\n * term keeps growing for as long as the streak lasts.\n */\nexport function refusedRetryDelayMs(streakStartedAt: number): number {\n const floor =\n lastServerReadAt > streakStartedAt\n ? RULES_REFUSED_RETRY_DELAY_MS\n : SESSION_REFUSED_RETRY_DELAY_MS\n // A backwards clock reads as a young streak, never as a negative age.\n const age = Math.max(0, Date.now() - streakStartedAt)\n return Math.min(\n REFUSED_RETRY_CEILING_MS,\n Math.max(floor, age / REFUSED_RETRY_AGE_DIVISOR),\n )\n}\n\n/** The longest an arrival is ever held back from reopening a refused listen. */\nexport const REFUSED_ARRIVAL_CEILING_MS = 2 * 60_000\n/** An arrival's hold is the streak's age divided by this, floor to ceiling. */\nconst REFUSED_ARRIVAL_AGE_DIVISOR = 20\n\n/**\n * How soon after a refusal an ARRIVAL (focus, the tab becoming visible) may\n * reopen the listen.\n *\n * It was a flat 2s, on the reasoning that an arrival is a person. It is not\n * always one: a window that is driven rather than used (a second monitor\n * beside a busy app, a browser under automation, a kiosk shell) takes focus\n * events all day, and each reopen that is refused schedules the next, which\n * the next focus event wakes 2s later. A console left open on a session that\n * could read nothing ran every listener on its page that way for 20 hours on\n * 2026-11-15/16: 107,000 refusals, up to 247 a minute, against a normal day\n * of about 100.\n *\n * So the hold grows with the streak's age like the timer does, a twentieth\n * of it up to two minutes. A young fault still answers an arrival in 2s. An\n * old one answers at most every two minutes, which caps a churning window at\n * 30 reopens an hour per listener, and a person coming back to a backed-off\n * page is still served at once in the usual case, because the refusal that\n * scheduled the pending reopen is minutes old by then. A re-authentication\n * never waits on this: the heal broadcast reopens with no hold at all.\n */\nexport function refusedArrivalDelayMs(streakStartedAt: number): number {\n const age = Math.max(0, Date.now() - streakStartedAt)\n return Math.min(\n REFUSED_ARRIVAL_CEILING_MS,\n Math.max(SESSION_REFUSED_RETRY_DELAY_MS, age / REFUSED_ARRIVAL_AGE_DIVISOR),\n )\n}\n\n/** No `document` (SSR, a worker) counts as visible: nothing to wait for. */\nfunction tabIsHidden(): boolean {\n return (\n typeof document !== 'undefined' && document.visibilityState === 'hidden'\n )\n}\n\n/**\n * Schedule the reopen of a spent refusal streak, and return its cancel.\n *\n * In a visible tab the reopen waits {@link refusedRetryDelayMs}. A HIDDEN tab\n * sets no timer at all: nobody is there to heal for, and an unattended tab on\n * a dead session was the Aug 20 – Sep 4 storm — 400K–1.7M rules denials a day\n * in ~8-hour blocks, ~$2 of reads the `read_ops_count` metric never showed\n * (AGL-2944). A tab that goes hidden while a reopen is pending drops its\n * timer and waits the same way.\n *\n * A person arriving reopens at once, whatever the cadence: the tab becoming\n * visible or the window regaining focus. (The heal broadcast is the third\n * instant road; the hooks subscribe to it themselves.) Arrivals are held to\n * one reopen no sooner than {@link refusedArrivalDelayMs} after the refusal\n * that scheduled this, so focus churn can never run the loop faster than 2s,\n * and runs it slower the longer the refusals have lasted.\n */\nexport function scheduleRefusedReopen(\n reopen: () => void,\n streakStartedAt: number,\n): () => void {\n const scheduledAt = Date.now()\n let timer: ReturnType<typeof setTimeout> | null = null\n let dueAt = Number.POSITIVE_INFINITY\n let settled = false\n\n const disarm = () => {\n if (timer !== null) clearTimeout(timer)\n timer = null\n dueAt = Number.POSITIVE_INFINITY\n }\n\n const fire = () => {\n if (settled) return\n cancel()\n reopen()\n }\n\n /** Reopen no later than `atMs`; an earlier due time already set wins. */\n const arm = (atMs: number) => {\n if (settled || atMs >= dueAt) return\n if (atMs <= Date.now()) {\n fire()\n return\n }\n if (timer !== null) clearTimeout(timer)\n dueAt = atMs\n timer = setTimeout(fire, atMs - Date.now())\n }\n\n const onArrival = () => {\n if (tabIsHidden()) return\n arm(scheduledAt + refusedArrivalDelayMs(streakStartedAt))\n }\n\n // `visibilitychange` fires on the way INTO hidden as well as out of it.\n const onVisibilityChange = () => {\n if (tabIsHidden()) disarm()\n else onArrival()\n }\n\n const cancel = () => {\n settled = true\n disarm()\n if (typeof document !== 'undefined') {\n document.removeEventListener('visibilitychange', onVisibilityChange)\n }\n if (typeof window !== 'undefined') {\n window.removeEventListener('focus', onArrival)\n }\n }\n\n if (typeof document !== 'undefined') {\n document.addEventListener('visibilitychange', onVisibilityChange)\n }\n if (typeof window !== 'undefined') {\n window.addEventListener('focus', onArrival)\n }\n if (!tabIsHidden()) arm(scheduledAt + refusedRetryDelayMs(streakStartedAt))\n\n return cancel\n}\n\n/**\n * The same seam in the other direction: the app telling refused listeners\n * that the session came back (AGL-1066).\n *\n * ## Why this has to exist\n *\n * A refused listen recovers today only because the retry loop never stops —\n * every reopen is another chance for the token to have attached. That is also\n * the single reason the AGL-664 in-place re-auth works at all: nothing else\n * re-subscribes. The hooks' effects depend on the query's identity\n * (`[ref.firestore, ref.path]` and each caller's `deps`), and a `stale`-reason\n * re-auth signs the same uid back in, so no dependency changes and no effect\n * re-runs. `AuthenticatedLayout` deliberately holds the tree MOUNTED while a\n * re-auth prompt is pending (AGL-664), which is what makes \"resume exactly\n * where you were\" true — and it is exactly why a remount cannot be relied on\n * to reopen anything.\n *\n * So any change that lets a refusal streak go terminal — the AGL-1066 item-3\n * flip — needs this channel first, or a user who re-authenticates\n * successfully sits in front of an errored console until they reload.\n *\n * ## What may broadcast, and what must not\n *\n * A heal is a RECOVERY FROM DENIAL, not any token event. Firebase refreshes\n * the ID token roughly hourly; broadcasting on that would reopen every\n * listener in the console on a timer for no reason. The console broadcasts\n * from one place — a session fault that has been resolved — see\n * `apps/console/utils/session-heal.ts`.\n *\n * Subscribers gate themselves as well: a listener the server is NOT refusing\n * ignores the broadcast entirely, so even a spurious heal costs nothing.\n * Nothing here clears `serverDenied` or `deniedStreak` — only a snapshot the\n * server answered is evidence, and that invariant does not bend for a\n * hopeful signal from the auth layer.\n */\nconst healListeners = new Set<() => void>()\n\n/**\n * Listen for \"the session may have recovered\". Returns the unsubscribe.\n *\n * The callback runs synchronously inside {@link reportFirestoreSessionHeal},\n * so it must be cheap and must tolerate being called when there is nothing\n * to do.\n */\nexport function subscribeFirestoreSessionHeal(\n listener: () => void,\n): () => void {\n healListeners.add(listener)\n return () => void healListeners.delete(listener)\n}\n\n/**\n * Tell every listener the session may have recovered.\n *\n * Iterates a COPY: a subscriber reopening its listen can unsubscribe (an\n * unmount racing the broadcast) and mutating the set mid-iteration would skip\n * the next one.\n */\nexport function reportFirestoreSessionHeal(): void {\n for (const listener of [...healListeners]) listener()\n}\n\n/**\n * Consecutive refusals before a listener says anything.\n *\n * Matched to `firestore-one-shot-retry`'s budget so both read styles apply\n * the same bar: surviving this many means it is not the AGL-216/217\n * post-sign-in race, which resolves in well under two seconds.\n *\n * The streak this counts is NOT the hook's retry `attempt`. That one is\n * reset by any snapshot, including one served from cache, so under\n * `persistentLocalCache` it never reaches any threshold at all — see\n * `use-firestore-collection-cached-retry.spec.ts`. This one is reset only by\n * a snapshot the SERVER answered, which is the only evidence that actually\n * bears on whether the session can read.\n */\nexport const DENIAL_STREAK_TO_REPORT = 5\n\n/**\n * The collection a listen was against, when it can be known from public API.\n *\n * `DocumentReference` exposes `parent`, and a `CollectionReference` exposes\n * `path`. A filtered `Query` exposes neither, and reaching into `_query` to\n * get one would be reading SDK internals — so those report `undefined` and\n * land in the shared `unknown` bucket. That can only ever fail to reach the\n * two-collection threshold, never trip it falsely, which is the right way\n * for this to degrade.\n */\nexport function denialLabelForQuery(target: unknown): string | undefined {\n const candidate = target as\n | { type?: string; path?: string; parent?: { path?: string } }\n | null\n | undefined\n if (!candidate) return undefined\n // A document listen: name the collection that holds it, not the document,\n // so two docs in one collection stay ONE piece of evidence.\n if (candidate.parent?.path) return candidate.parent.path\n if (candidate.type === 'collection' && candidate.path) return candidate.path\n return undefined\n}\n"],"names":["reporters","setFirestoreSessionReporters","next","reportFirestoreDenial","collection","onDenied","reportFirestoreServerRead","noteFirestoreServerRead","onServerRead","lastServerReadAt","Date","now","resetFirestoreServerReadEvidence","SESSION_REFUSED_RETRY_DELAY_MS","RULES_REFUSED_RETRY_DELAY_MS","REFUSED_RETRY_CEILING_MS","REFUSED_RETRY_AGE_DIVISOR","refusedRetryDelayMs","streakStartedAt","floor","age","Math","max","min","REFUSED_ARRIVAL_CEILING_MS","REFUSED_ARRIVAL_AGE_DIVISOR","refusedArrivalDelayMs","tabIsHidden","document","visibilityState","scheduleRefusedReopen","reopen","scheduledAt","timer","dueAt","Number","POSITIVE_INFINITY","settled","disarm","clearTimeout","fire","cancel","arm","atMs","setTimeout","onArrival","onVisibilityChange","removeEventListener","window","addEventListener","healListeners","Set","subscribeFirestoreSessionHeal","listener","add","delete","reportFirestoreSessionHeal","DENIAL_STREAK_TO_REPORT","denialLabelForQuery","target","candidate","undefined","parent","path","type"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA+BC,GAsBD,IAAIA,YAA8C;AAElD;;;CAGC,GACD,OAAO,SAASC,6BACdC,IAAsC;IAEtCF,YAAYE;AACd;AAEA,+DAA+D,GAC/D,OAAO,SAASC,sBAAsBC,UAAmB;IACvDJ,6BAAAA,UAAWK,QAAQ,CAACD;AACtB;AAEA,2EAA2E,GAC3E,OAAO,SAASE;IACdC;IACAP,6BAAAA,UAAWQ,YAAY;AACzB;AAEA;;;;;;;;CAQC,GACD,IAAIC,mBAAmB;AAEvB;;;CAGC,GACD,OAAO,SAASF;IACdE,mBAAmBC,KAAKC,GAAG;AAC7B;AAEA,wDAAwD,GACxD,OAAO,SAASC;IACdH,mBAAmB;AACrB;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmCC,GACD,OAAO,MAAMI,iCAAiC,KAAK;AACnD,OAAO,MAAMC,+BAA+B,MAAM;AAClD,iEAAiE,GACjE,OAAO,MAAMC,2BAA2B,IAAI,MAAM;AAClD,8EAA8E,GAC9E,MAAMC,4BAA4B;AAElC;;;;;;;CAOC,GACD,OAAO,SAASC,oBAAoBC,eAAuB;IACzD,MAAMC,QACJV,mBAAmBS,kBACfJ,+BACAD;IACN,sEAAsE;IACtE,MAAMO,MAAMC,KAAKC,GAAG,CAAC,GAAGZ,KAAKC,GAAG,KAAKO;IACrC,OAAOG,KAAKE,GAAG,CACbR,0BACAM,KAAKC,GAAG,CAACH,OAAOC,MAAMJ;AAE1B;AAEA,8EAA8E,GA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