@ultimat3/realtime 31.39.0 → 31.40.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.
package/CLAUDE.md CHANGED
@@ -111,8 +111,9 @@ A rule marked `†` has its full text in [`docs/history/realtime-rules.md`](../.
111
111
  re-lookup (`live-definition-input.test.ts`). A cold window is staled only by a table it reads.
112
112
  - **A WINDOW is per TENANT** (`windowId(queryHash, tenant)`, `live-tenant.ts`); the read runs as a
113
113
  service actor carrying ONLY that org, never the subscriber. †
114
- - **A change's tenant is its entity's `$tenantColumn`, on every producer** (`change-tenant.ts`),
115
- never a property assumed to be `orgId`; a window lists its tenanted tables (`shape.tenantTables`)
114
+ - **A change's tenant is its entity's `$tenantColumn`, on every producer and in `normalize`** (`change-tenant.ts`, `replicator-tenant.test.ts`),
115
+ never a property assumed to be `orgId`; a window's org is its TENANT alone, `null` untenanted —
116
+ never the input's `orgId` (`query-window-tenant.test.ts`; `orgIdOf` is deprecated, unused); a window lists its tenanted tables (`shape.tenantTables`)
116
117
  and `canAffect` refuses a tenant-less insert/update on one for an org-scoped window; a
117
118
  tenant-less DELETE (key-only image) passes, and `bridgeChange` keeps a delete only for an id
118
119
  the window holds (`live-tenant-column.test.ts`, `tenant-less-delete.test.ts`).
@@ -171,6 +172,7 @@ A rule marked `†` has its full text in [`docs/history/realtime-rules.md`](../.
171
172
  - **A channel is a DECLARATION, no primitive** (docs/history/primitive-factories.md):
172
173
  `channel(name, { params, policy, catchUp, records?, events? })`, deny by default; `policy`
173
174
  REQUIRED (`X_CHANNEL_DECLARATION_INVALID`; public: `allow('public')`). Presence: `events`.
175
+ - **A param naming a records entity's `$tenantColumn` is the subscriber's org** (`channel-tenant.ts`, before the policy). †
174
176
  - **A guard that FAILS on re-auth SUSPENDS the seat** (`guardFailures`): kept, silent until a pass.
175
177
  A `null` actor on a `row` channel and a tenancy refusal are DENIALS.
176
178
  - **A seat is decided for the actor ON the socket when the guard resolves** (`#settle`); a denied
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/realtime",
3
- "version": "31.39.0",
3
+ "version": "31.40.1",
4
4
  "description": "Three-tier realtime: channels, live queries, local-first sync — one protocol, one mutator shape",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -52,10 +52,10 @@
52
52
  "test": "bun test"
53
53
  },
54
54
  "dependencies": {
55
- "@ultimat3/core": "31.39.0",
56
- "@ultimat3/entity": "31.39.0",
57
- "@ultimat3/policy": "31.39.0",
58
- "@ultimat3/query": "31.39.0",
55
+ "@ultimat3/core": "31.40.1",
56
+ "@ultimat3/entity": "31.40.1",
57
+ "@ultimat3/policy": "31.40.1",
58
+ "@ultimat3/query": "31.40.1",
59
59
  "nats": "2.29.3"
60
60
  }
61
61
  }
@@ -1,17 +1,21 @@
1
- // A declared channel's policy, asked on subscribe: the params are the input and the row is what
2
- // the channel's own loader answered. Through `@ultimat3/query`'s `guardQuery`, the package's one
3
- // authz seam — the same call `policy-gate.ts` makes for a live query.
1
+ // A declared channel's subscribe decision: the tenant first (`channel-tenant.ts`), then the policy,
2
+ // with the params as input and the row the channel's own loader answered. Through
3
+ // `@ultimat3/query`'s `guardQuery`, the package's one authz seam — the call `policy-gate.ts` makes.
4
4
 
5
5
  import { type Actor, type Ctx, ctxOf, runWithContext } from '@ultimat3/core';
6
6
  import { guardQuery, QueryDeniedError } from '@ultimat3/query';
7
7
  import type { Channel } from './channel-decl';
8
+ import { assertChannelTenant } from './channel-tenant';
8
9
  import { isTenancyDenial, TopicForbiddenError } from './errors';
9
10
 
10
11
  /**
11
12
  * A denial is `X_TOPIC_FORBIDDEN`. A loader or a rule that RAISED is not a denial and leaves as it
12
13
  * came, so the caller can tell an outage from a decision — `onActorChange` suspends the topic on one.
13
14
  *
14
- * Two answers are denials before any rule runs, because neither is an outage:
15
+ * Three answers are denials before any rule runs, because none is an outage:
16
+ * - **a param naming a records entity's tenant column that is not the actor's org**
17
+ (`assertChannelTenant`): every frame kind — records, events, presence — rides the seat this
18
+ grants, so the tenant is the mechanism's to check, never a rule's to remember.
15
19
  * - **nobody, on a channel that decides on a row.** A loader runs AS the subscriber; with no actor
16
20
  * it would run as the node, and a row is not something nobody is entitled to.
17
21
  * - **a loader the tenant guard refused** (`TENANCY_DENIAL_CODES`): the actor has no org, or names
@@ -24,6 +28,7 @@ export async function authorizeChannel(
24
28
  topic: string,
25
29
  params: Readonly<Record<string, string>>,
26
30
  ): Promise<void> {
31
+ assertChannelTenant(channel, actor, topic, params, (who) => subscriberContext(ctx, who));
27
32
  const loader = channel.row;
28
33
  if (loader === undefined) return decide(channel, ctx, actor, topic, params, null);
29
34
  if (actor === null) {
@@ -0,0 +1,55 @@
1
+ // The tenant half of a channel subscribe: a param that names a records entity's tenant column must
2
+ // be the subscriber's own org. Decided by `@ultimat3/entity`'s own guard (`assertScoped`), so a
3
+ // socket is held to the rule an HTTP read is — never a second copy of it, and never left to a policy.
4
+
5
+ import { type Actor, type Ctx, isUltimateError, runWithContext } from '@ultimat3/core';
6
+ import { assertScoped, type QueryPlan } from '@ultimat3/entity';
7
+ import { tenantColumnOfTable } from './change-tenant';
8
+ import type { Channel } from './channel-decl';
9
+ import { isTenancyDenial, TopicForbiddenError } from './errors';
10
+
11
+ /**
12
+ * A row is routed to the topic its own params name (`channel-records.ts`), so a topic keyed by the
13
+ * tenant column IS one tenant's stream — of records, and of the events and presence that ride the
14
+ * same seat. Granting it on the policy alone handed org B's rows to any org-A member whose rule
15
+ * forgot to compare the org (`can('post:read')` does not).
16
+ *
17
+ * The verdict is `assertScoped`'s over the plan the subscribe amounts to — `<column> = <param>`
18
+ * under the subscriber's context: the actor's org or `X_TENANCY_ACTOR_MISMATCH`, no org at all
19
+ * `X_TENANCY_ACTOR_ORG_REQUIRED`, a proven `crossTenant()` scope passes. A refusal reaches the
20
+ * socket as `X_TOPIC_FORBIDDEN` naming that code, a denial the hub latches. Anything else the
21
+ * guard raised is not a decision and leaves as it came.
22
+ */
23
+ export function assertChannelTenant(
24
+ channel: Channel,
25
+ actor: Actor | null,
26
+ topic: string,
27
+ params: Readonly<Record<string, string>>,
28
+ contextFor: (actor: Actor) => Ctx,
29
+ ): void {
30
+ let ctx: Ctx | undefined;
31
+ for (const projection of channel.records) {
32
+ const column = tenantColumnOfTable(projection.table);
33
+ if (column === null || !channel.params.includes(column)) continue;
34
+ const refusal = (code: string): TopicForbiddenError =>
35
+ new TopicForbiddenError({
36
+ topic,
37
+ actorId: actor === null ? null : actor.id,
38
+ reason: `channel "${channel.name}" carries "${projection.type}" rows by its tenant column "${column}", and this actor's tenant is not the one the param names (${code})`,
39
+ });
40
+ if (actor === null) throw refusal('X_TENANCY_ACTOR_ORG_REQUIRED');
41
+ const plan: QueryPlan = {
42
+ entity: projection.type,
43
+ where: [{ column, op: 'eq', value: params[column] }],
44
+ orderBy: [],
45
+ limit: 1,
46
+ };
47
+ ctx ??= contextFor(actor);
48
+ try {
49
+ runWithContext(ctx, () => assertScoped(projection.type, column, 'subscribe', plan));
50
+ } catch (error) {
51
+ if (!isTenancyDenial(error) || !isUltimateError(error)) throw error;
52
+ throw refusal(error.code);
53
+ }
54
+ }
55
+ }
@@ -43,12 +43,13 @@ export interface SnapshotArgs {
43
43
 
44
44
  export interface LiveQueryDefinition<R extends LiveRow = LiveRow> {
45
45
  readonly name: string;
46
- /** Dependency set for the pre-filter. `x verify` rejects a `live: true` query without one. */
46
+ /** Dependency set for the pre-filter: required by this type; `@ultimat3/query` refuses an empty `subscribes:`. */
47
47
  readonly entities: readonly string[];
48
48
  /** Read set. Lets the pre-filter skip updates that touch no column this query reads. */
49
49
  readonly columns?: readonly string[];
50
50
  /**
51
- * Bounded read (`orderBy` + `limit`, enforced by `x verify`), unfiltered by policy — and read
51
+ * Bounded read (`orderBy` + `limit`; no limit is `X_QUERY_LIVE_UNBOUNDED`, refused where
52
+ * `@ultimat3/query` builds the source — `live-bounds.ts`), unfiltered by policy — and read
52
53
  * FOR `tenant`: the org of the subscribers this window serves, `null` for subscribers that carry
53
54
  * none. A window is keyed by it (`live-tenant.ts`), so one read is never two orgs' rows.
54
55
  */
@@ -128,9 +128,10 @@ export function queryEntry(
128
128
  shape: {
129
129
  qid,
130
130
  entities,
131
- // The window's own tenant first: a change in another org is dropped before any predicate
132
- // runs, whether or not the query's `where` happens to name one.
133
- orgId: tenant ?? orgIdOf(input),
131
+ // The window's own tenant, and nothing else: a change in another org is dropped before any
132
+ // predicate runs. Never an input property spelled `orgId` — the read runs under `tenant`
133
+ // alone, so filtering by anything else drops changes that read returns (`change-tenant.ts`).
134
+ orgId: tenant,
134
135
  // Resolved once per window, so `canAffect` refuses a tenant-less change on these with a
135
136
  // lookup in a short list rather than a registry walk per change.
136
137
  tenantTables: entities.filter((table) => tenantColumnOfTable(table) !== null),
@@ -387,6 +388,11 @@ async function readSnapshot(entry: QueryEntry, phase: LiveReadPhase): Promise<Sn
387
388
  }
388
389
  }
389
390
 
391
+ /**
392
+ * @deprecated Unused by the framework, and removed at the next major. A window's org is its
393
+ * tenant — pass `tenant` to `queryEntry` — never an input property spelled `orgId`: the read runs
394
+ * under the tenant alone, and a change's own tenant is its entity's `$tenantColumn`.
395
+ */
390
396
  export function orgIdOf(input: JsonValue): string | null {
391
397
  if (typeof input !== 'object' || input === null || Array.isArray(input)) return null;
392
398
  const value = input['orgId'];
@@ -2,6 +2,7 @@
2
2
  // the subject a change is published under, and the normalize step that drops the unusable and
3
3
  // hoists the tenant out of the row. Split from `replicator.ts`, which re-exports both.
4
4
 
5
+ import { tenantColumnOfTable, tenantIn } from './change-tenant';
5
6
  import type { ChangeEvent } from './changefeed';
6
7
 
7
8
  export const CHANGE_SUBJECT_PREFIX = 'x.change';
@@ -14,7 +15,12 @@ export function changeSubject(change: ChangeEvent): string {
14
15
  return `${CHANGE_SUBJECT_PREFIX}.${change.table}.${change.orgId ?? '_'}`;
15
16
  }
16
17
 
17
- /** Drops events the pipeline cannot use and hoists the tenant id out of the row. */
18
+ /**
19
+ * Drops events the pipeline cannot use and hoists the tenant out of the row — from the column the
20
+ * table's ENTITY declares (`change-tenant.ts`), never a property assumed to be `orgId`. It read
21
+ * `row.orgId`, so a key-only DELETE on a `tenant: 'workspaceId'` table whose key holds an `orgId`
22
+ * column was published as that org's change, and the real tenant's windows dropped it.
23
+ */
18
24
  export function normalize(change: ChangeEvent): ChangeEvent | null {
19
25
  // The one change that carries no row by design; nothing to hoist a tenant out of.
20
26
  if (change.op === 'truncate') return change;
@@ -23,6 +29,6 @@ export function normalize(change: ChangeEvent): ChangeEvent | null {
23
29
  if (change.op === 'insert' && change.after === null) return null;
24
30
  if (change.op === 'delete' && change.before === null) return null;
25
31
  if (change.orgId !== null) return change;
26
- const orgId = row['orgId'];
27
- return typeof orgId === 'string' ? { ...change, orgId } : change;
32
+ const orgId = tenantIn(tenantColumnOfTable(change.table), row);
33
+ return orgId === null ? change : { ...change, orgId };
28
34
  }
package/src/server.ts CHANGED
@@ -211,6 +211,7 @@ export {
211
211
  DEFAULT_READ_DEADLINE_MS,
212
212
  type EntryOptions,
213
213
  fillWindow,
214
+ // Deprecated and unused by the framework; kept for semver, removed at the next major.
214
215
  orgIdOf,
215
216
  type PendingRead,
216
217
  type QueryEntry,