@ai-matrx/auth 0.2.0 → 0.2.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.
@@ -143,6 +143,230 @@ declare function setOrganizationFavourite(db: OrganizationsDb, organizationId: s
143
143
  type OrganizationRefusal = "lapsed" | "retry" | null;
144
144
  declare function classifyOrganizationRefusal(status: number, body: unknown): OrganizationRefusal;
145
145
 
146
+ /**
147
+ * Organization-question plumbing that is LOGIC, not store binding (moved from the website's
148
+ * `orgBootstrapGate`, `organizationRefusal`, `childOrganization`, `adminOrganization`).
149
+ * Pure: every host input is injected; no Redux, no Next, no window.
150
+ */
151
+ /** How long a write may wait for the first answer before it is refused anyway. */
152
+ declare const ORGANIZATION_RESOLUTION_TIMEOUT_MS = 10000;
153
+ interface OrganizationBootstrapGate {
154
+ isResolved(): boolean;
155
+ /** The organization question has been answered (with an organization or without). Idempotent. */
156
+ markResolved(): void;
157
+ /** Wait for the answer or the timeout, whichever first. Always resolves; never rejects. */
158
+ whenResolved(timeoutMs?: number): Promise<void>;
159
+ /** Tests and in-place identity swaps only. */
160
+ reset(): void;
161
+ }
162
+ /** "Nobody has looked yet" is a race, not a fact: a held write waits on this, bounded. */
163
+ declare function createOrganizationBootstrapGate(defaultTimeoutMs?: number): OrganizationBootstrapGate;
164
+ /** True when an error body is the server's "you are not a member of the organization you carried". */
165
+ declare function isNotAMemberRefusal(body: unknown): boolean;
166
+ declare const NOT_A_MEMBER_RECHECK_GAP_MS = 30000;
167
+ interface NotAMemberRefusalNotice {
168
+ /** True when a recheck was started (at most one per gap, so a burst reads memberships once). */
169
+ notice(body: unknown, now?: number): boolean;
170
+ reset(): void;
171
+ }
172
+ declare function createNotAMemberRefusalNotice(recheck: () => void, gapMs?: number): NotAMemberRefusalNotice;
173
+ type ParentOrganization = string | {
174
+ organization_id?: string | null;
175
+ } | null | undefined;
176
+ /**
177
+ * A record created as part of an existing parent lives in the PARENT's organization; the explicit
178
+ * one applies only when the parent names none. A disagreement is announced (`onDisagree`,
179
+ * default console.warn), never obeyed.
180
+ */
181
+ declare function resolveChildOrganizationId(parent: ParentOrganization, explicit?: string | null, label?: string, onDisagree?: (message: string) => void): string | null;
182
+ /** What the host knows about the admin lane. */
183
+ interface AdminSeatInput {
184
+ readonly laneOpen: boolean;
185
+ readonly organizationId?: string | null;
186
+ readonly organizationName?: string | null;
187
+ }
188
+ interface AdminSeat {
189
+ readonly id: string;
190
+ readonly name: string | null;
191
+ }
192
+ /** The admin organization in force right now, or null (off the lane, or none set). */
193
+ declare function resolveAdminSeat(input: AdminSeatInput | null | undefined): AdminSeat | null;
194
+ /** True when the admin seat differs from the person's own active organization (scope/project/task never ride across). */
195
+ declare function adminSeatReplacesUserContext(input: AdminSeatInput | null | undefined, personOrganizationId: string | null | undefined): boolean;
196
+
197
+ /**
198
+ * The query key, platform-wide. The server stamps this on every deep link it
199
+ * emits; `features/admin/users/components/OrganizationsAdminClient.tsx` has
200
+ * read it since before this module existed. One spelling, in one place.
201
+ */
202
+ declare const LINK_ORGANIZATION_QUERY_KEY = "org";
203
+ type LinkOrganizationParam =
204
+ /** No link said anything about an organization. The ladder is untouched. */
205
+ {
206
+ kind: "absent";
207
+ }
208
+ /** Something was said and it is neither a uuid nor an address. Refused in words, never used. */
209
+ | {
210
+ kind: "malformed";
211
+ raw: string;
212
+ }
213
+ /** A well-formed organization id. Still has to survive the membership check. */
214
+ | {
215
+ kind: "named";
216
+ organizationId: string;
217
+ }
218
+ /** An organization's address (slug). Survives only by matching a membership's slug. */
219
+ | {
220
+ kind: "addressed";
221
+ slug: string;
222
+ };
223
+ /**
224
+ * Classify one bare `org=` value. The ONE rule for what a value may be, shared
225
+ * by the URL reader below and the boot resolver's bare-value path.
226
+ */
227
+ declare function classifyLinkOrganizationValue(raw: string): LinkOrganizationParam;
228
+ /**
229
+ * Read the key out of a query string, a `URLSearchParams`, or a full URL.
230
+ * Never throws: a URL this cannot parse is `absent`, because a crash on
231
+ * arrival is a worse answer than the ladder's own.
232
+ */
233
+ declare function readLinkOrganizationParam(source: string | URLSearchParams | null | undefined): LinkOrganizationParam;
234
+ interface LinkOrganizationMembership {
235
+ id: string;
236
+ name: string;
237
+ /** The organization's address, so an `addressed` link can be matched. */
238
+ slug?: string | null;
239
+ }
240
+ interface LinkOrganizationDecisionInput {
241
+ param: LinkOrganizationParam;
242
+ /** The person's LIVE memberships. The only authority on what they may open. */
243
+ memberships: ReadonlyArray<LinkOrganizationMembership>;
244
+ /** The organization they are working in right now, or null. */
245
+ currentOrganizationId: string | null;
246
+ currentOrganizationName?: string | null;
247
+ /**
248
+ * The knob `userPreferences.organization.switchOnLinkPrompt` — "switch
249
+ * organization when a link asks". DEFAULT ON, so an omitted value is `true`.
250
+ */
251
+ switchWhenALinkAsks?: boolean;
252
+ /** The account they are signed in as, for the refusal sentence. */
253
+ signedInAs?: string | null;
254
+ /**
255
+ * The link's organization is one this person is not a member of but IS let into
256
+ * by a share they accepted (`lib/organizations/linkOrganizationAdmission.ts`).
257
+ * A share admits and never makes a member, so the answer is `admitted`: nobody
258
+ * is moved, nothing is refused, and the page opens it as that organization's
259
+ * guest. Omitted, the answer is exactly what it was before (VERIFIER-15 H4).
260
+ */
261
+ admittedByAShare?: boolean;
262
+ /** Replace any of the default English sentences (a localising host). */
263
+ messages?: Partial<LinkOrganizationMessages>;
264
+ }
265
+ interface LinkOrganizationMessages {
266
+ notAMember(signedInAs?: string | null): string;
267
+ malformed(raw: string): string;
268
+ switched(toName: string, fromName: string | null): string;
269
+ offer(toName: string, fromName: string | null): string;
270
+ offerAction(toName: string): string;
271
+ }
272
+ type LinkOrganizationDecision =
273
+ /** Nothing to do. No toast, no change. */
274
+ {
275
+ kind: "no-link";
276
+ }
277
+ /** The link names the organization they are already in. Silent no-op. */
278
+ | {
279
+ kind: "already-current";
280
+ organizationId: string;
281
+ }
282
+ /** Use this organization for this session. `announcement` non-null = they moved. */
283
+ | {
284
+ kind: "honoured";
285
+ organizationId: string;
286
+ organizationName: string;
287
+ announcement: string | null;
288
+ }
289
+ /** The knob is off and this would be a real switch. Offer it as a click. */
290
+ | {
291
+ kind: "offered";
292
+ organizationId: string;
293
+ organizationName: string;
294
+ message: string;
295
+ actionLabel: string;
296
+ }
297
+ /**
298
+ * Not a member, but let in by a share they accepted. Silent: nobody is moved
299
+ * (a share never makes a member) and nothing was refused (the page opens it).
300
+ */
301
+ | {
302
+ kind: "admitted";
303
+ organizationId: string;
304
+ }
305
+ /** Malformed, or not theirs. Changes nothing; says so. */
306
+ | {
307
+ kind: "refused";
308
+ reason: "malformed" | "not-a-member";
309
+ message: string;
310
+ };
311
+ /** What a person reads when the link's organization is not theirs to open. */
312
+ declare function linkOrganizationNotAMemberMessage(signedInAs?: string | null): string;
313
+ /** What a person reads when `org=` is not an organization id at all. */
314
+ declare function linkOrganizationMalformedMessage(raw: string): string;
315
+ /** What a person reads when a link actually moved them. Law 4: never silent. */
316
+ declare function linkOrganizationSwitchAnnouncement(toName: string, fromName: string | null): string;
317
+ /** What a person reads with the knob turned off and a link asking to move them. */
318
+ declare function linkOrganizationOfferMessage(toName: string, fromName: string | null): string;
319
+ /**
320
+ * The decision. One function, every branch, no side effects.
321
+ *
322
+ * 🚨 WHY THE KNOB GOVERNS ONLY A REAL SWITCH. The knob protects the
323
+ * organization a person is WORKING IN from being yanked out from under them by
324
+ * a link someone else composed. With `currentOrganizationId === null` there is
325
+ * nothing to protect and nothing to switch away from: the alternative to
326
+ * honouring the link is the picker, which is the very dead end this module was
327
+ * built to end. So the knob turns a SWITCH into an offer; it never turns an
328
+ * arrival into a refusal. This is deliberate and it is not a hidden default —
329
+ * with no link present, a null selection stays null exactly as before.
330
+ */
331
+ declare function decideLinkOrganization(input: LinkOrganizationDecisionInput): LinkOrganizationDecision;
332
+ interface ResolveWithLinkInput<T extends {
333
+ id: string;
334
+ name: string;
335
+ slug?: string | null;
336
+ joinedAt?: string;
337
+ }> {
338
+ readonly memberships: readonly T[];
339
+ /** This tab's held organization (rung 1; a refresh keeps it). */
340
+ readonly held?: string | null;
341
+ readonly readAccount: () => Promise<AccountOrganizationChoices>;
342
+ readonly first?: () => Promise<T | null>;
343
+ /** The raw `?org=` value, a query string, a URL or URLSearchParams. Omitted = no link. */
344
+ readonly link?: string | URLSearchParams | null;
345
+ readonly switchWhenALinkAsks?: boolean | undefined;
346
+ readonly signedInAs?: string | null | undefined;
347
+ readonly messages?: Partial<LinkOrganizationMessages> | undefined;
348
+ /** Asked only when the link already failed the membership check (a share admits, never joins). */
349
+ readonly admittedByAShare?: ((organizationId: string) => Promise<boolean>) | undefined;
350
+ }
351
+ interface ResolvedWithLink<T> {
352
+ readonly organization: T;
353
+ readonly rung: OrganizationRung | "link";
354
+ /** What the link meant, when it said anything — the host SAYS it (refused / announced / offered). */
355
+ readonly link: LinkOrganizationDecision;
356
+ }
357
+ /**
358
+ * The ONE load ladder with the link folded in: held → last active → start-up → first, then the
359
+ * link's own organization wins ONLY when it is a current membership. Every other link outcome
360
+ * (refused, offered, already-current, admitted) leaves the ladder's answer standing. Null when
361
+ * the person has no memberships. A failed read throws through.
362
+ */
363
+ declare function resolveOrganizationWithLink<T extends {
364
+ id: string;
365
+ name: string;
366
+ slug?: string | null;
367
+ joinedAt?: string;
368
+ }>(input: ResolveWithLinkInput<T>): Promise<ResolvedWithLink<T> | null>;
369
+
146
370
  /**
147
371
  * THE ACTIVE ORGANIZATION — one per tab / running app, set once when the app loads, never none
148
372
  * while the person has a membership (Arman, 2026-10-07; organizations STATE rules 10–15).
@@ -181,7 +405,7 @@ interface ActiveOrganizationSnapshot {
181
405
  readonly organization: OrganizationMembership | null;
182
406
  readonly memberships: readonly OrganizationMembership[];
183
407
  /** Which ladder rung answered (or "switched" after a person's click). */
184
- readonly rung: OrganizationRung | "switched" | null;
408
+ readonly rung: OrganizationRung | "switched" | "link" | null;
185
409
  readonly error: string | null;
186
410
  }
187
411
  declare class NoActiveOrganizationError extends Error {
@@ -214,11 +438,37 @@ interface CreateActiveOrganizationOptions {
214
438
  readonly held?: HeldOrganizationStore | undefined;
215
439
  /** An extra first rung (the web's `?org=` link). Kept only if it is a current membership. */
216
440
  readonly linked?: (() => string | null | undefined) | undefined;
441
+ /**
442
+ * The link's own organization (`?org=` uuid or address) as a first-class rung: honoured only when
443
+ * it is a current membership, otherwise the ladder stands and `onDecision` receives the refusal /
444
+ * offer / announcement for the host to SAY. Supersedes `linked` when both are given.
445
+ */
446
+ readonly link?: {
447
+ readonly source: () => string | URLSearchParams | null | undefined;
448
+ readonly switchWhenALinkAsks?: (() => boolean | undefined) | undefined;
449
+ readonly signedInAs?: (() => string | null | undefined) | undefined;
450
+ readonly messages?: Partial<LinkOrganizationMessages> | undefined;
451
+ /** A share admits without making a member (asked only after a not-a-member verdict). */
452
+ readonly admittedByAShare?: ((organizationId: string) => Promise<boolean>) | undefined;
453
+ readonly onDecision?: ((decision: LinkOrganizationDecision) => void) | undefined;
454
+ } | undefined;
455
+ /**
456
+ * THE ADMIN SEAT: while the host's admin lane is open, the admin's own organization IS the active
457
+ * one for every reader (`current()`, `ensureOrgId()`); off the lane the person's own is untouched.
458
+ * Ignored unless the seat is a current membership. The snapshot always keeps the person's own.
459
+ */
460
+ readonly adminSeat?: (() => AdminSeatInput | null | undefined) | undefined;
461
+ /** Marked resolved whenever the ladder settles (organization or none). */
462
+ readonly bootstrapGate?: OrganizationBootstrapGate | undefined;
463
+ /** Minimum gap between ladder re-runs caused by a not-a-member refusal. Default 30 s. */
464
+ readonly refusalRecheckGapMs?: number | undefined;
217
465
  /** Load as soon as it is created (default true). */
218
466
  readonly autoLoad?: boolean | undefined;
219
467
  }
220
468
  /** A held store over a `Storage` (browser `sessionStorage` = per tab), identity-keyed. */
221
- declare function storageHeldOrganization(storage: Pick<Storage, "getItem" | "setItem" | "removeItem">, key?: string): HeldOrganizationStore;
469
+ declare function storageHeldOrganization(storage: Pick<Storage, "getItem" | "setItem" | "removeItem">, key?: string): HeldOrganizationStore & {
470
+ read(userId: string): string | null;
471
+ };
222
472
  /** Held in memory: the running app's own choice (desktop, scripts, tests). */
223
473
  declare function memoryHeldOrganization(): HeldOrganizationStore;
224
474
  declare function createActiveOrganization(options: CreateActiveOrganizationOptions): ActiveOrganization;
@@ -329,4 +579,4 @@ declare function organizationRequiredEnvelope(error: OrganizationRequiredServerE
329
579
  /** The standard `Response` (status 400) a route answers the refusal with — no framework needed. */
330
580
  declare function organizationRequiredResponse(error: OrganizationRequiredServerError): Response;
331
581
 
332
- export { type AccountOrganizationChoices, type ActiveOrganization, type ActiveOrganizationSnapshot, type ActiveOrganizationStatus, type CreateActiveOrganizationOptions, type HeldOrganizationStore, type LadderInput, MEMBERSHIPS_URL, type MembershipReadClient, NoActiveOrganizationError, NotAMemberError, ORGANIZATION_CONTEXT_REQUIRED_CODE, ORGANIZATION_ENTITY_TYPE, ORGANIZATION_REQUIRED_CODE, ORGANIZATION_REQUIRED_WIRE_CODE, type OrganizationHoldDetails, type OrganizationHoldSetOn, type OrganizationMembership, type OrganizationMembershipSummary, type OrganizationRefusal, type OrganizationRequiredEnvelope, OrganizationRequiredServerError, type OrganizationRequiredWireMembership, type OrganizationRung, type OrganizationsDb, type ResolvedOrganization, classifyOrganizationRefusal, createActiveOrganization, extractOrganizationHoldMemberships, isOrganizationRequiredEnvelope, isOrganizationRequiredError, isOrganizationRequiredServerError, memoryHeldOrganization, oldestMembership, orderOrganizations, organizationMatches, organizationRequired, organizationRequiredEnvelope, organizationRequiredResponse, readAccountOrganizationChoices, readCallerMemberships, readMemberships, readOrganizationFavourites, resolveActiveOrganization, resolveActiveOrganizationLazily, setOrganizationFavourite, storageHeldOrganization, toAccountOrganizationChoices, writeLastActiveOrganization, writeStartupOrganization };
582
+ export { type AccountOrganizationChoices, type ActiveOrganization, type ActiveOrganizationSnapshot, type ActiveOrganizationStatus, type AdminSeat, type AdminSeatInput, type CreateActiveOrganizationOptions, type HeldOrganizationStore, LINK_ORGANIZATION_QUERY_KEY, type LadderInput, type LinkOrganizationDecision, type LinkOrganizationDecisionInput, type LinkOrganizationMembership, type LinkOrganizationMessages, type LinkOrganizationParam, MEMBERSHIPS_URL, type MembershipReadClient, NOT_A_MEMBER_RECHECK_GAP_MS, NoActiveOrganizationError, NotAMemberError, type NotAMemberRefusalNotice, ORGANIZATION_CONTEXT_REQUIRED_CODE, ORGANIZATION_ENTITY_TYPE, ORGANIZATION_REQUIRED_CODE, ORGANIZATION_REQUIRED_WIRE_CODE, ORGANIZATION_RESOLUTION_TIMEOUT_MS, type OrganizationBootstrapGate, type OrganizationHoldDetails, type OrganizationHoldSetOn, type OrganizationMembership, type OrganizationMembershipSummary, type OrganizationRefusal, type OrganizationRequiredEnvelope, OrganizationRequiredServerError, type OrganizationRequiredWireMembership, type OrganizationRung, type OrganizationsDb, type ParentOrganization, type ResolveWithLinkInput, type ResolvedOrganization, type ResolvedWithLink, adminSeatReplacesUserContext, classifyLinkOrganizationValue, classifyOrganizationRefusal, createActiveOrganization, createNotAMemberRefusalNotice, createOrganizationBootstrapGate, decideLinkOrganization, extractOrganizationHoldMemberships, isNotAMemberRefusal, isOrganizationRequiredEnvelope, isOrganizationRequiredError, isOrganizationRequiredServerError, linkOrganizationMalformedMessage, linkOrganizationNotAMemberMessage, linkOrganizationOfferMessage, linkOrganizationSwitchAnnouncement, memoryHeldOrganization, oldestMembership, orderOrganizations, organizationMatches, organizationRequired, organizationRequiredEnvelope, organizationRequiredResponse, readAccountOrganizationChoices, readCallerMemberships, readLinkOrganizationParam, readMemberships, readOrganizationFavourites, resolveActiveOrganization, resolveActiveOrganizationLazily, resolveAdminSeat, resolveChildOrganizationId, resolveOrganizationWithLink, setOrganizationFavourite, storageHeldOrganization, toAccountOrganizationChoices, writeLastActiveOrganization, writeStartupOrganization };
@@ -181,6 +181,209 @@ function onSessionChange(client, cb) {
181
181
  return () => data.subscription.unsubscribe();
182
182
  }
183
183
 
184
+ // src/organization-gate.ts
185
+ var ORGANIZATION_RESOLUTION_TIMEOUT_MS = 1e4;
186
+ function createOrganizationBootstrapGate(defaultTimeoutMs = ORGANIZATION_RESOLUTION_TIMEOUT_MS) {
187
+ let settled = false;
188
+ let announce = null;
189
+ let resolution = new Promise((resolve) => {
190
+ announce = resolve;
191
+ });
192
+ return {
193
+ isResolved: () => settled,
194
+ markResolved() {
195
+ if (settled) return;
196
+ settled = true;
197
+ announce?.();
198
+ },
199
+ async whenResolved(timeoutMs = defaultTimeoutMs) {
200
+ if (settled) return;
201
+ let timer;
202
+ await Promise.race([
203
+ resolution,
204
+ new Promise((resolve) => {
205
+ timer = setTimeout(resolve, timeoutMs);
206
+ })
207
+ ]);
208
+ if (timer !== void 0) clearTimeout(timer);
209
+ },
210
+ reset() {
211
+ announce?.();
212
+ settled = false;
213
+ resolution = new Promise((resolve) => {
214
+ announce = resolve;
215
+ });
216
+ }
217
+ };
218
+ }
219
+ var NOT_A_MEMBER_CODES = /* @__PURE__ */ new Set(["organization_forbidden", "organization_not_member"]);
220
+ function isNotAMemberRefusal(body) {
221
+ if (!body || typeof body !== "object") return false;
222
+ const record = body;
223
+ if (typeof record.code === "string" && NOT_A_MEMBER_CODES.has(record.code)) return true;
224
+ const detail = record.detail;
225
+ return !!detail && typeof detail === "object" && typeof detail.code === "string" && NOT_A_MEMBER_CODES.has(detail.code);
226
+ }
227
+ var NOT_A_MEMBER_RECHECK_GAP_MS = 3e4;
228
+ function createNotAMemberRefusalNotice(recheck, gapMs = NOT_A_MEMBER_RECHECK_GAP_MS) {
229
+ let last = Number.NEGATIVE_INFINITY;
230
+ return {
231
+ notice(body, now = Date.now()) {
232
+ if (!isNotAMemberRefusal(body)) return false;
233
+ if (now - last < gapMs) return false;
234
+ last = now;
235
+ recheck();
236
+ return true;
237
+ },
238
+ reset() {
239
+ last = Number.NEGATIVE_INFINITY;
240
+ }
241
+ };
242
+ }
243
+ function resolveChildOrganizationId(parent, explicit, label = "child record", onDisagree = (m) => console.warn(m)) {
244
+ const parentOrg = typeof parent === "string" ? parent : parent?.organization_id ?? null;
245
+ if (parentOrg) {
246
+ if (explicit && explicit !== parentOrg) {
247
+ onDisagree(`[child org] ${label} filed in its parent's organization ${parentOrg}, not ${explicit} \u2014 a child belongs with its parent.`);
248
+ }
249
+ return parentOrg;
250
+ }
251
+ return explicit ?? null;
252
+ }
253
+ function resolveAdminSeat(input) {
254
+ if (!input || input.laneOpen !== true || !input.organizationId) return null;
255
+ return { id: input.organizationId, name: input.organizationName ?? null };
256
+ }
257
+ function adminSeatReplacesUserContext(input, personOrganizationId) {
258
+ const seat = resolveAdminSeat(input);
259
+ return seat !== null && seat.id !== (personOrganizationId ?? null);
260
+ }
261
+
262
+ // src/organization-link.ts
263
+ import { isRfc4122Uuid } from "@ai-matrx/kit/uuid";
264
+ var LINK_ORGANIZATION_QUERY_KEY = "org";
265
+ var SLUG = /^[a-z0-9][a-z0-9-]{0,99}$/i;
266
+ function classifyLinkOrganizationValue(raw) {
267
+ const value = raw.trim();
268
+ if (isRfc4122Uuid(value)) return { kind: "named", organizationId: value };
269
+ if (SLUG.test(value)) return { kind: "addressed", slug: value.toLowerCase() };
270
+ return { kind: "malformed", raw: value };
271
+ }
272
+ function readLinkOrganizationParam(source) {
273
+ if (source == null) return { kind: "absent" };
274
+ let params;
275
+ if (source instanceof URLSearchParams) {
276
+ params = source;
277
+ } else {
278
+ try {
279
+ const q = source.includes("?") ? source.slice(source.indexOf("?")) : source;
280
+ params = new URLSearchParams(q);
281
+ } catch {
282
+ return { kind: "absent" };
283
+ }
284
+ }
285
+ if (!params.has(LINK_ORGANIZATION_QUERY_KEY)) return { kind: "absent" };
286
+ return classifyLinkOrganizationValue(params.get(LINK_ORGANIZATION_QUERY_KEY) ?? "");
287
+ }
288
+ function linkOrganizationNotAMemberMessage(signedInAs) {
289
+ const account = signedInAs ? `You are signed in as ${signedInAs}.` : "Check which account you are signed in as.";
290
+ return `The link you followed is for an organization this account is not a member of, so nothing was opened and you were not moved. ${account} Sign in with the account the link was meant for, or ask whoever sent it to give this account access.`;
291
+ }
292
+ function linkOrganizationMalformedMessage(raw) {
293
+ const quoted = raw.length > 0 ? ` ("${raw}")` : "";
294
+ return `The link you followed names an organization we cannot read${quoted}, so nothing was switched and you were left where you were. Ask whoever sent it for the link again, or pick the organization you are working in from the avatar menu.`;
295
+ }
296
+ function linkOrganizationSwitchAnnouncement(toName, fromName) {
297
+ const from = fromName ? ` You were working in ${fromName}.` : "";
298
+ return `You are now working in ${toName} because the link you followed is filed under it.${from} Switch back any time from the avatar menu.`;
299
+ }
300
+ function linkOrganizationOfferMessage(toName, fromName) {
301
+ const where = fromName ? `, and you are working in ${fromName}` : "";
302
+ return `The link you followed is for ${toName}${where}. "Switch organization when a link asks" is turned off in your settings, so nothing changed \u2014 switch to ${toName} to open it.`;
303
+ }
304
+ function decideLinkOrganization(input) {
305
+ const { param, memberships, currentOrganizationId } = input;
306
+ const switchWhenALinkAsks = input.switchWhenALinkAsks ?? true;
307
+ const say = {
308
+ notAMember: linkOrganizationNotAMemberMessage,
309
+ malformed: linkOrganizationMalformedMessage,
310
+ switched: linkOrganizationSwitchAnnouncement,
311
+ offer: linkOrganizationOfferMessage,
312
+ offerAction: (name) => `Switch to ${name}`,
313
+ ...input.messages
314
+ };
315
+ if (param.kind === "absent") return { kind: "no-link" };
316
+ if (param.kind === "malformed") {
317
+ return {
318
+ kind: "refused",
319
+ reason: "malformed",
320
+ message: say.malformed(param.raw)
321
+ };
322
+ }
323
+ const match = param.kind === "named" ? memberships.find((o) => o.id === param.organizationId) : memberships.find((o) => o.slug?.trim().toLowerCase() === param.slug);
324
+ if (!match && param.kind === "named" && input.admittedByAShare) {
325
+ return { kind: "admitted", organizationId: param.organizationId };
326
+ }
327
+ if (!match) {
328
+ return {
329
+ kind: "refused",
330
+ reason: "not-a-member",
331
+ message: say.notAMember(input.signedInAs)
332
+ };
333
+ }
334
+ if (currentOrganizationId === match.id) {
335
+ return { kind: "already-current", organizationId: match.id };
336
+ }
337
+ const fromName = currentOrganizationId ? input.currentOrganizationName ?? memberships.find((o) => o.id === currentOrganizationId)?.name ?? null : null;
338
+ if (currentOrganizationId && !switchWhenALinkAsks) {
339
+ return {
340
+ kind: "offered",
341
+ organizationId: match.id,
342
+ organizationName: match.name,
343
+ message: say.offer(match.name, fromName),
344
+ actionLabel: say.offerAction(match.name)
345
+ };
346
+ }
347
+ return {
348
+ kind: "honoured",
349
+ organizationId: match.id,
350
+ organizationName: match.name,
351
+ // Nothing to announce on a cold arrival: they were working nowhere, so
352
+ // they were not moved. A move, however, is always announced.
353
+ announcement: currentOrganizationId ? say.switched(match.name, fromName) : null
354
+ };
355
+ }
356
+ async function resolveOrganizationWithLink(input) {
357
+ const ladder = await resolveActiveOrganizationLazily({
358
+ memberships: input.memberships,
359
+ held: input.held ?? null,
360
+ readAccount: input.readAccount,
361
+ ...input.first ? { first: input.first } : {}
362
+ });
363
+ if (!ladder) return null;
364
+ const param = typeof input.link === "string" ? input.link.includes("=") ? readLinkOrganizationParam(input.link) : classifyLinkOrganizationValue(input.link) : readLinkOrganizationParam(input.link ?? null);
365
+ const decisionInput = {
366
+ param,
367
+ memberships: input.memberships.map((o) => ({ id: o.id, name: o.name, slug: o.slug ?? null })),
368
+ currentOrganizationId: ladder.organization.id,
369
+ currentOrganizationName: ladder.organization.name,
370
+ ...input.switchWhenALinkAsks === void 0 ? {} : { switchWhenALinkAsks: input.switchWhenALinkAsks },
371
+ ...input.signedInAs === void 0 ? {} : { signedInAs: input.signedInAs },
372
+ ...input.messages ? { messages: input.messages } : {}
373
+ };
374
+ let link = decideLinkOrganization(decisionInput);
375
+ if (link.kind === "refused" && link.reason === "not-a-member" && param.kind === "named" && input.admittedByAShare) {
376
+ if (await input.admittedByAShare(param.organizationId)) {
377
+ link = decideLinkOrganization({ ...decisionInput, admittedByAShare: true });
378
+ }
379
+ }
380
+ if (link.kind === "honoured") {
381
+ const organization = input.memberships.find((m) => m.id === link.organizationId);
382
+ if (organization) return { organization, rung: "link", link };
383
+ }
384
+ return { organization: ladder.organization, rung: ladder.rung, link };
385
+ }
386
+
184
387
  // src/active-organization.ts
185
388
  var NoActiveOrganizationError = class extends Error {
186
389
  constructor(reason, detail) {
@@ -258,6 +461,7 @@ function createActiveOrganization(options) {
258
461
  const publish = (next) => {
259
462
  current = Object.freeze(next);
260
463
  if (current.status !== "resolving" && current.status !== "idle") {
464
+ options.bootstrapGate?.markResolved();
261
465
  const ready = waiters;
262
466
  waiters = [];
263
467
  for (const w of ready) w();
@@ -275,19 +479,38 @@ function createActiveOrganization(options) {
275
479
  }
276
480
  const memberships = await readMemberships(client, person.id);
277
481
  if (gen !== generation) return current;
278
- const linked = options.linked?.() ?? null;
279
- const heldId = (linked && memberships.some((m) => m.id === linked) ? linked : null) ?? await held.read(person.id);
280
- const resolved = await resolveActiveOrganizationLazily({
281
- memberships,
282
- held: heldId,
283
- readAccount: () => readAccountOrganizationChoices(client, person.id)
284
- });
482
+ const linkOptions = options.link;
483
+ let resolved;
484
+ let linkDecision = null;
485
+ if (linkOptions) {
486
+ const r = await resolveOrganizationWithLink({
487
+ memberships,
488
+ held: await held.read(person.id),
489
+ readAccount: () => readAccountOrganizationChoices(client, person.id),
490
+ link: linkOptions.source() ?? null,
491
+ switchWhenALinkAsks: linkOptions.switchWhenALinkAsks?.(),
492
+ signedInAs: linkOptions.signedInAs?.(),
493
+ messages: linkOptions.messages,
494
+ admittedByAShare: linkOptions.admittedByAShare
495
+ });
496
+ resolved = r;
497
+ linkDecision = r?.link ?? null;
498
+ } else {
499
+ const linked = options.linked?.() ?? null;
500
+ const heldId = (linked && memberships.some((m) => m.id === linked) ? linked : null) ?? await held.read(person.id);
501
+ resolved = await resolveActiveOrganizationLazily({
502
+ memberships,
503
+ held: heldId,
504
+ readAccount: () => readAccountOrganizationChoices(client, person.id)
505
+ });
506
+ }
285
507
  if (gen !== generation) return current;
286
508
  if (!resolved) {
287
509
  publish({ ...IDLE, status: "none", userId: person.id, error: "no-memberships" });
288
510
  return current;
289
511
  }
290
512
  await held.write(person.id, resolved.organization.id);
513
+ if (linkDecision && linkDecision.kind !== "no-link") options.link?.onDecision?.(linkDecision);
291
514
  publish({
292
515
  status: "ready",
293
516
  userId: person.id,
@@ -323,6 +546,11 @@ function createActiveOrganization(options) {
323
546
  const userId = session.user?.id ?? null;
324
547
  if (event === "SIGNED_IN" && userId !== current.userId) void load();
325
548
  });
549
+ const seatFor = (snap) => {
550
+ const seat = resolveAdminSeat(options.adminSeat?.());
551
+ return seat && snap.memberships.some((m) => m.id === seat.id) ? seat.id : null;
552
+ };
553
+ let lastNotAMemberRecheck = Number.NEGATIVE_INFINITY;
326
554
  const settled = async () => {
327
555
  if (current.status === "idle") return load();
328
556
  if (current.status === "resolving") {
@@ -339,11 +567,11 @@ function createActiveOrganization(options) {
339
567
  };
340
568
  },
341
569
  load,
342
- current: () => current.status === "ready" ? current.organizationId : null,
570
+ current: () => current.status === "ready" ? seatFor(current) ?? current.organizationId : null,
343
571
  async ensureOrgId(recordOrganizationId) {
344
572
  if (recordOrganizationId) return recordOrganizationId;
345
573
  const snap = await settled();
346
- if (snap.status === "ready" && snap.organizationId) return snap.organizationId;
574
+ if (snap.status === "ready" && snap.organizationId) return seatFor(snap) ?? snap.organizationId;
347
575
  if (snap.status === "error") throw new NoActiveOrganizationError("unreadable", snap.error ?? void 0);
348
576
  throw new NoActiveOrganizationError(snap.error === "signed-out" ? "signed-out" : "no-memberships");
349
577
  },
@@ -358,7 +586,16 @@ function createActiveOrganization(options) {
358
586
  await writeLastActiveOrganization(client, organizationId);
359
587
  },
360
588
  async handleRefusal(status, body) {
361
- const kind = classifyOrganizationRefusal(status, body);
589
+ let kind = classifyOrganizationRefusal(status, body);
590
+ if (kind === null && isNotAMemberRefusal(body)) {
591
+ const now = Date.now();
592
+ if (now - lastNotAMemberRecheck >= (options.refusalRecheckGapMs ?? NOT_A_MEMBER_RECHECK_GAP_MS)) {
593
+ lastNotAMemberRecheck = now;
594
+ kind = "lapsed";
595
+ } else {
596
+ return null;
597
+ }
598
+ }
362
599
  if (kind === "lapsed") {
363
600
  if (current.userId) await held.clear();
364
601
  await load();
@@ -460,20 +697,33 @@ function organizationRequiredResponse(error) {
460
697
  return Response.json(organizationRequiredEnvelope(error), { status: 400 });
461
698
  }
462
699
  export {
700
+ LINK_ORGANIZATION_QUERY_KEY,
463
701
  MEMBERSHIPS_URL,
702
+ NOT_A_MEMBER_RECHECK_GAP_MS,
464
703
  NoActiveOrganizationError,
465
704
  NotAMemberError,
466
705
  ORGANIZATION_CONTEXT_REQUIRED_CODE,
467
706
  ORGANIZATION_ENTITY_TYPE,
468
707
  ORGANIZATION_REQUIRED_CODE,
469
708
  ORGANIZATION_REQUIRED_WIRE_CODE,
709
+ ORGANIZATION_RESOLUTION_TIMEOUT_MS,
470
710
  OrganizationRequiredServerError,
711
+ adminSeatReplacesUserContext,
712
+ classifyLinkOrganizationValue,
471
713
  classifyOrganizationRefusal,
472
714
  createActiveOrganization,
715
+ createNotAMemberRefusalNotice,
716
+ createOrganizationBootstrapGate,
717
+ decideLinkOrganization,
473
718
  extractOrganizationHoldMemberships,
719
+ isNotAMemberRefusal,
474
720
  isOrganizationRequiredEnvelope,
475
721
  isOrganizationRequiredError,
476
722
  isOrganizationRequiredServerError,
723
+ linkOrganizationMalformedMessage,
724
+ linkOrganizationNotAMemberMessage,
725
+ linkOrganizationOfferMessage,
726
+ linkOrganizationSwitchAnnouncement,
477
727
  memoryHeldOrganization,
478
728
  oldestMembership,
479
729
  orderOrganizations,
@@ -483,10 +733,14 @@ export {
483
733
  organizationRequiredResponse,
484
734
  readAccountOrganizationChoices,
485
735
  readCallerMemberships,
736
+ readLinkOrganizationParam,
486
737
  readMemberships,
487
738
  readOrganizationFavourites,
488
739
  resolveActiveOrganization,
489
740
  resolveActiveOrganizationLazily,
741
+ resolveAdminSeat,
742
+ resolveChildOrganizationId,
743
+ resolveOrganizationWithLink,
490
744
  setOrganizationFavourite,
491
745
  storageHeldOrganization,
492
746
  toAccountOrganizationChoices,
package/dist/react.d.cts CHANGED
@@ -96,7 +96,7 @@ interface ActiveOrganizationSnapshot {
96
96
  readonly organization: OrganizationMembership | null;
97
97
  readonly memberships: readonly OrganizationMembership[];
98
98
  /** Which ladder rung answered (or "switched" after a person's click). */
99
- readonly rung: OrganizationRung | "switched" | null;
99
+ readonly rung: OrganizationRung | "switched" | "link" | null;
100
100
  readonly error: string | null;
101
101
  }
102
102
  interface ActiveOrganization {
package/dist/react.d.ts CHANGED
@@ -96,7 +96,7 @@ interface ActiveOrganizationSnapshot {
96
96
  readonly organization: OrganizationMembership | null;
97
97
  readonly memberships: readonly OrganizationMembership[];
98
98
  /** Which ladder rung answered (or "switched" after a person's click). */
99
- readonly rung: OrganizationRung | "switched" | null;
99
+ readonly rung: OrganizationRung | "switched" | "link" | null;
100
100
  readonly error: string | null;
101
101
  }
102
102
  interface ActiveOrganization {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-matrx/auth",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "AI Matrx sign-in, session and organizations for every app: sign in/out, session storage and refresh per platform (browser, Next.js, extension, desktop, Node), the current person, their organizations and favourites, the one active organization (held requests, never a list filter), and the credentials @ai-matrx/data and @ai-matrx/api read.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -201,5 +201,5 @@
201
201
  "test": "vitest run",
202
202
  "verify:tarball": "node ./scripts/verify-tarball.mjs"
203
203
  },
204
- "gitHead": "eeeafb1ae105f78c584681829e13dd69b200abc6"
204
+ "gitHead": "51416dab018cb60548d2baeed471c4b27a0cb44b"
205
205
  }