@sssb/kit 0.6.0 → 0.6.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/dist/release.json CHANGED
@@ -1 +1 @@
1
- {"commit":"d70d56db1537eee2bcfe9c8c72bb4c784b131117"}
1
+ {"commit":"993193893bda13fc98aaaeba0ad004092482c039"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sssb/kit",
3
- "version": "0.6.0",
3
+ "version": "0.6.1",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -37,6 +37,7 @@
37
37
  "./adapters/index": "./src/adapters/index.ts",
38
38
  "./adapters/proxy": "./src/adapters/proxy.ts",
39
39
  "./adapters/real/accept-invite-form": "./src/adapters/real/accept-invite-form.tsx",
40
+ "./adapters/real/account-refused-form": "./src/adapters/real/account-refused-form.tsx",
40
41
  "./adapters/real/index": "./src/adapters/real/index.ts",
41
42
  "./adapters/real/llm": "./src/adapters/real/llm.ts",
42
43
  "./adapters/real/migrate-handler": "./src/adapters/real/migrate-handler.ts",
@@ -51,6 +52,7 @@
51
52
  "./components/agreements/agreement-gate": "./src/components/agreements/agreement-gate.tsx",
52
53
  "./components/app-header": "./src/components/app-header.tsx",
53
54
  "./components/auth/accept-invite-screen": "./src/components/auth/accept-invite-screen.tsx",
55
+ "./components/auth/account-refused": "./src/components/auth/account-refused.tsx",
54
56
  "./components/auth/org-switcher": "./src/components/auth/org-switcher.tsx",
55
57
  "./components/auth/people-picker": "./src/components/auth/people-picker.tsx",
56
58
  "./components/auth/sign-in-screen": "./src/components/auth/sign-in-screen.tsx",
@@ -1,6 +1,6 @@
1
1
  import { isRestricted } from '../core/roles'
2
2
  import type { Locale } from '../core/locale'
3
- import type { AuthPort, AuthUser, CreatedInvite, MemberStanding, Membership, OrgRef } from '../ports/auth'
3
+ import type { AuthPort, AuthRefusal, AuthUser, CreatedInvite, MemberStanding, Membership, OrgRef } from '../ports/auth'
4
4
  import { AuthRequiredError, ForbiddenError } from '../ports/errors'
5
5
  import { type AuthSettings, fixedOrgProblem } from './auth-tenancy'
6
6
 
@@ -42,7 +42,8 @@ export interface ProviderIdentitySource {
42
42
  * slug, is no user at all, and has no standing anywhere as a credential (`getMember`): that is a multi-tenant instance
43
43
  * switched to this mode by mistake, and admitting them would put another tenant's people in this one. Refused without
44
44
  * signing out: this runs while server components render, where a session cookie cannot be changed, and on a shared
45
- * instance it would end their session in the other product. Over the provider's organizations, every method is
45
+ * instance it would end their session in the other product. `refusal` says why to the sign-in page, which offers the
46
+ * person an explicit sign-out (`@sssb/kit/components/auth/account-refused`). Over the provider's organizations, every method is
46
47
  * otherwise the adapter's, with its organizations, roles, members and invitations; the ones that act for the signed-in
47
48
  * person (`updateProfile`, `createInvite`, `listMyOrgs`, `setActiveOrg`) run the tenant guard first, and `getMember`
48
49
  * runs it after the provider's membership.
@@ -60,7 +61,8 @@ export interface ProviderIdentitySource {
60
61
  * needs a non-restricted member), so such a job is one the app's own rules let the person start.
61
62
  * - `createInvite`: refused. Anyone the provider signs in is already placed in the home org; an app adds people through
62
63
  * its provider's own sign-up.
63
- * - `listMyOrgs`: the home org alone, named by its slug (this module reads no database). `setActiveOrg`: the home org
64
+ * - `listMyOrgs`: the home org alone, named by its org row's name, which the caller supplies a lookup for (`orgName`;
65
+ * the slug when the row is missing). `setActiveOrg`: the home org
64
66
  * is accepted and changes nothing; any other is refused.
65
67
  *
66
68
  * `signInPath` and `signOut` are always the adapter's, and `updateProfile` writes through it after the guard.
@@ -70,6 +72,11 @@ export function configuredAuth(
70
72
  settings: AuthSettings,
71
73
  source: ProviderIdentitySource,
72
74
  staffOrgSlug: string,
75
+ /**
76
+ * The display name of an org, by its tenant's slug and its own, or null when there is no such row: how a fixed org
77
+ * source names its home org, since this module knows it only by slug. Left out (a test), the slug is the name.
78
+ */
79
+ orgName?: (tenantSlug: string, orgSlug: string) => Promise<string | null>,
73
80
  ): AuthPort {
74
81
  const { tenancy, orgSource } = settings
75
82
  if (tenancy.kind === 'multi' && orgSource.kind === 'provider') return base
@@ -169,10 +176,23 @@ export function configuredAuth(
169
176
  async listMyOrgs(): Promise<OrgRef[]> {
170
177
  const user = await port.getCurrentUser()
171
178
  if (!user) return []
172
- if (fixed) return [{ slug: fixed.homeOrgSlug, name: fixed.homeOrgSlug, role: fixed.role }]
179
+ if (fixed) {
180
+ // The org row's name, read per call (a rename shows at once); the slug when the row is missing,
181
+ // which the cutover row `auth-tenancy` says to create.
182
+ // A failed read falls back too: a display name never takes the page down.
183
+ const name =
184
+ (await orgName?.(user.tenantSlug, fixed.homeOrgSlug).catch(() => null)) ?? fixed.homeOrgSlug
185
+ return [{ slug: fixed.homeOrgSlug, name, role: fixed.role }]
186
+ }
173
187
  return base.listMyOrgs()
174
188
  },
175
189
 
190
+ async refusal(): Promise<AuthRefusal | null> {
191
+ // The guard's own reason, from the same identity read. Its callers are the sign-in pages, not every request.
192
+ const identity = await source.current()
193
+ return identity && !admitted(identity.tenantClaim) ? { reason: 'other-tenant' } : null
194
+ },
195
+
176
196
  async setActiveOrg(orgSlug: string): Promise<void> {
177
197
  await port.requireUser()
178
198
  if (!fixed) return base.setActiveOrg(orgSlug)
@@ -8,7 +8,7 @@ import { copyFile, rename, unlink, writeFile } from 'node:fs/promises'
8
8
  *
9
9
  * WHY this exists: every fake adapter persists its state as a flat file, and under concurrent
10
10
  * requests two writers can land on the SAME file at once (see
11
- * .claude/future-tasks/e2e-shared-world-blocks-parallelism.md). Plain `writeFileSync`/`writeFile`
11
+ * safeinsights/sssb#99). Plain `writeFileSync`/`writeFile`
12
12
  * TRUNCATE the file and then stream the new bytes in — so if writer A (shorter payload) and writer
13
13
  * B (longer payload) interleave, a reader can observe B's truncate landing after A has already
14
14
  * written, leaving A's shorter content followed by the tail of B's longer content: neither writer's
@@ -1,8 +1,10 @@
1
1
  import { staffOrgSlug } from '@sssb/app-config/abilities'
2
2
  import type { AuthPort } from '../../ports/auth'
3
3
  import { authSettings } from '../auth-tenancy'
4
+ import { orgNameForSlugs } from '../../db/org-lookup'
4
5
  import { configuredAuth } from '../configured-auth'
5
6
  import { fakeAuth, fakeIdentitySource } from './auth'
7
+ import { fakeDb } from './db'
6
8
 
7
9
  let cached: AuthPort | undefined
8
10
 
@@ -19,6 +21,10 @@ let cached: AuthPort | undefined
19
21
  * reach, and the replay says so.
20
22
  */
21
23
  export function simulatedAuth(): AuthPort {
22
- if (cached === undefined) cached = configuredAuth(fakeAuth, authSettings(), fakeIdentitySource, staffOrgSlug)
24
+ if (cached === undefined) {
25
+ cached = configuredAuth(fakeAuth, authSettings(), fakeIdentitySource, staffOrgSlug, (tenant, org) =>
26
+ orgNameForSlugs(fakeDb, tenant, org),
27
+ )
28
+ }
23
29
  return cached
24
30
  }
@@ -0,0 +1,32 @@
1
+ 'use client'
2
+
3
+ import { useAuth, useClerk } from '@clerk/nextjs'
4
+ import { AccountRefused } from '../../components/auth/account-refused'
5
+
6
+ /**
7
+ * The refused-account screen in real mode (`@sssb/kit/components/auth/account-refused`), signing out through Clerk's
8
+ * client. Revoking the session on the server alone leaves the browser's short-lived session token in place, which the
9
+ * middleware still verifies until it lapses, so the page would come back refused. Clerk's client sign-out ends this one
10
+ * session (`sessionId`), clears its cookies, and then sends the browser back to this page (`redirectUrl`), which now
11
+ * shows the sign-in form.
12
+ *
13
+ * Only on the person's click, as the screen says: on an identity-provider instance shared with another product, this
14
+ * session may be that product's too. Until Clerk has loaded and knows the session, a click signs nobody out and says
15
+ * so: before then Clerk only queues the call, and with no session id it would end every session on the device.
16
+ *
17
+ * AUTHORED — CUTOVER (`auth-tenancy`): never run against a real Clerk instance. Lives in packages/kit/src/adapters
18
+ * because it imports the vendor SDK; mount it under `RealAuthProviders`.
19
+ */
20
+ export function RealAccountRefused() {
21
+ const { signOut } = useClerk()
22
+ const { isLoaded, sessionId } = useAuth()
23
+ return (
24
+ <AccountRefused
25
+ onSignOut={async () => {
26
+ if (!isLoaded || !sessionId) return false
27
+ await signOut({ sessionId, redirectUrl: window.location.href })
28
+ return true
29
+ }}
30
+ />
31
+ )
32
+ }
@@ -159,7 +159,8 @@ export const realAuth: AuthPort = {
159
159
  },
160
160
 
161
161
  async signOut(): Promise<void> {
162
- // Server-side revocation; the client additionally calls Clerk's signOut for local state.
162
+ // Server-side revocation only: the browser keeps its short-lived session token until it lapses, so a page that must
163
+ // show the person signed out at once also signs out through Clerk's client (./account-refused-form.tsx does).
163
164
  const { sessionId } = await auth()
164
165
  if (!sessionId) return
165
166
  const client = await clerkClient()
@@ -261,7 +262,7 @@ export const realAuth: AuthPort = {
261
262
  *
262
263
  * The page goes to Clerk as a PATH, which Clerk's `redirectUrl` accepts ("The full URL or path"), never as the
263
264
  * absolute URL it arrives as: that is built from the request's URL, whose host behind `SssbApp` is the server's own
264
- * (`localhost`), not the app's (.claude/future-tasks/request-url-is-not-the-public-url.md in SSSB's repository).
265
+ * (`localhost`), not the app's (safeinsights/sssb#131).
265
266
  */
266
267
  async createInvite(invite: InviteInput): Promise<CreatedInvite> {
267
268
  const { userId } = await auth()
@@ -10,6 +10,7 @@ import type { StoragePort } from '../../ports/storage'
10
10
  import { absentEmail, absentJobs, absentLlm, absentStorage } from './absent'
11
11
  import { authRequiredEnv, authSettings, fixedOrgProblem } from '../auth-tenancy'
12
12
  import { configuredAuth } from '../configured-auth'
13
+ import { orgNameForSlugs } from '../../db/org-lookup'
13
14
  import { clerkIdentitySource, realAuth } from './auth'
14
15
  import { DATABASE_ENV, databaseTransport } from './database-transport'
15
16
  import { noAnalytics } from './no-analytics'
@@ -108,9 +109,6 @@ interface RealPortsHooks {
108
109
  export async function createRealPorts(hooks: RealPortsHooks = {}): Promise<RealPorts> {
109
110
  assertRealEnv()
110
111
  const env = process.env
111
- // Clerk, placed as the auth settings say (../auth-tenancy.ts), and Clerk itself on the defaults. Every port that
112
- // reaches the people (the in-process runner's job context included) is handed this one.
113
- const auth: AuthPort = configuredAuth(realAuth, authSettings(), clerkIdentitySource, staffOrgSlug)
114
112
  // assertRealEnv above already proved every required variable is set; this narrows the type.
115
113
  const need = (name: string): string => {
116
114
  const value = env[name]
@@ -130,6 +128,12 @@ export async function createRealPorts(hooks: RealPortsHooks = {}): Promise<RealP
130
128
  region: need('AWS_REGION'),
131
129
  })
132
130
  : (await import('./db')).createRealDb(need('DATABASE_URL'))
131
+ // Clerk, placed as the auth settings say (../auth-tenancy.ts), and Clerk itself on the defaults. Every port that
132
+ // reaches the people (the in-process runner's job context included) is handed this one. A fixed org source names
133
+ // its home org from the database's org row.
134
+ const auth: AuthPort = configuredAuth(realAuth, authSettings(), clerkIdentitySource, staffOrgSlug, (tenant, org) =>
135
+ orgNameForSlugs(db, tenant, org),
136
+ )
133
137
  const storageChoice = portChoice('storage')
134
138
  const storage =
135
139
  storageChoice === 's3'
@@ -16,12 +16,18 @@ import {
16
16
  PostgresIntrospector,
17
17
  PostgresQueryCompiler,
18
18
  type DatabaseConnection,
19
+ type ColumnMetadata,
20
+ type DatabaseIntrospector,
21
+ type DatabaseMetadataOptions,
19
22
  type Dialect,
20
23
  type Driver,
21
24
  type Kysely,
22
25
  type QueryResult,
26
+ type SchemaMetadata,
27
+ type TableMetadata,
23
28
  type TransactionSettings,
24
29
  } from 'kysely'
30
+ import { DEFAULT_MIGRATION_LOCK_TABLE, DEFAULT_MIGRATION_TABLE } from 'kysely/migration'
25
31
  import {
26
32
  castPlaceholder,
27
33
  commitOutcome,
@@ -91,10 +97,121 @@ export class RdsDataDialect implements Dialect {
91
97
  }
92
98
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- kysely's Dialect interface signature
93
99
  createIntrospector(db: Kysely<any>) {
94
- return new PostgresIntrospector(db)
100
+ return new RdsDataIntrospector(db)
95
101
  }
96
102
  }
97
103
 
104
+ /**
105
+ * Kysely's Postgres introspector, with the one column the Data API cannot return cast to text. Kysely's `getTables`
106
+ * selects `pg_class.relkind`, a one-byte `"char"`, which the Data API refuses whole ("The result contains the
107
+ * unsupported data type "CHAR"", ./rds-data-emulator.ts's `REFUSED_RESULT_TYPES`), and its Migrator calls it before
108
+ * anything else, to see whether its own tables exist. So this is Kysely 0.29's query and its reading of the rows, with
109
+ * `relkind::text` for `relkind`; `getSchemas` reads only `nspname`, a `name`, and is Kysely's own. The contract suite
110
+ * (./rds-data.contract.test.ts) holds it to Kysely's introspector on the same database, so an upgrade of Kysely that
111
+ * changes what `getTables` returns fails there.
112
+ */
113
+ export class RdsDataIntrospector implements DatabaseIntrospector {
114
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- kysely's Dialect interface signature
115
+ readonly #db: Kysely<any>
116
+ readonly #postgres: PostgresIntrospector
117
+
118
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- kysely's Dialect interface signature
119
+ constructor(db: Kysely<any>) {
120
+ this.#db = db
121
+ this.#postgres = new PostgresIntrospector(db)
122
+ }
123
+
124
+ getSchemas(): Promise<SchemaMetadata[]> {
125
+ return this.#postgres.getSchemas()
126
+ }
127
+
128
+ async getTables(options: DatabaseMetadataOptions = { withInternalKyselyTables: false }): Promise<TableMetadata[]> {
129
+ let query = this.#db
130
+ .selectFrom('pg_catalog.pg_attribute as a')
131
+ .innerJoin('pg_catalog.pg_class as c', 'a.attrelid', 'c.oid')
132
+ .innerJoin('pg_catalog.pg_namespace as ns', 'c.relnamespace', 'ns.oid')
133
+ .innerJoin('pg_catalog.pg_type as typ', 'a.atttypid', 'typ.oid')
134
+ .innerJoin('pg_catalog.pg_namespace as dtns', 'typ.typnamespace', 'dtns.oid')
135
+ .select([
136
+ 'a.attname as column',
137
+ 'a.attnotnull as not_null',
138
+ 'a.atthasdef as has_default',
139
+ 'c.relname as table',
140
+ sql<string>`c.relkind::text`.as('table_type'),
141
+ 'ns.nspname as schema',
142
+ 'typ.typname as type',
143
+ 'dtns.nspname as type_schema',
144
+ sql<string | null>`col_description(a.attrelid, a.attnum)`.as('column_description'),
145
+ sql<
146
+ string | null
147
+ >`pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as(
148
+ 'auto_incrementing',
149
+ ),
150
+ ])
151
+ .where('c.relkind', 'in', ['r', 'v', 'p', 'f'])
152
+ .where('ns.nspname', '!~', '^pg_')
153
+ .where('ns.nspname', '!=', 'information_schema')
154
+ .where('ns.nspname', '!=', 'crdb_internal')
155
+ .where(sql<boolean>`has_schema_privilege(ns.nspname, 'USAGE')`)
156
+ .where('a.attnum', '>=', 0)
157
+ .where('a.attisdropped', '!=', true)
158
+ .orderBy('ns.nspname')
159
+ .orderBy('c.relname')
160
+ .orderBy('a.attnum')
161
+ .$castTo<IntrospectedColumn>()
162
+ if (!options.withInternalKyselyTables) {
163
+ query = query
164
+ .where('c.relname', '!=', DEFAULT_MIGRATION_TABLE)
165
+ .where('c.relname', '!=', DEFAULT_MIGRATION_LOCK_TABLE)
166
+ }
167
+ const tables: TableMetadata[] = []
168
+ const bySchema = new Map<string, Map<string, TableMetadata>>()
169
+ for (const column of await query.execute()) {
170
+ let schema = bySchema.get(column.schema)
171
+ if (!schema) bySchema.set(column.schema, (schema = new Map()))
172
+ let table = schema.get(column.table)
173
+ if (!table) {
174
+ table = Object.freeze({
175
+ columns: [],
176
+ isForeign: column.table_type === 'f',
177
+ isView: column.table_type === 'v',
178
+ name: column.table,
179
+ schema: column.schema,
180
+ })
181
+ schema.set(column.table, table)
182
+ tables.push(table)
183
+ }
184
+ table.columns.push(
185
+ // `comment` present and undefined on an uncommented column, as Kysely's is: the cast is
186
+ // exactOptionalPropertyTypes', which Kysely's own type does not satisfy either.
187
+ Object.freeze({
188
+ comment: column.column_description ?? undefined,
189
+ dataType: column.type,
190
+ dataTypeSchema: column.type_schema,
191
+ hasDefaultValue: column.has_default,
192
+ isAutoIncrementing: column.auto_incrementing !== null,
193
+ isNullable: !column.not_null,
194
+ name: column.column,
195
+ } as ColumnMetadata),
196
+ )
197
+ }
198
+ return tables
199
+ }
200
+ }
201
+
202
+ interface IntrospectedColumn {
203
+ column: string
204
+ not_null: boolean
205
+ has_default: boolean
206
+ table: string
207
+ table_type: string
208
+ schema: string
209
+ type: string
210
+ type_schema: string
211
+ column_description: string | null
212
+ auto_incrementing: string | null
213
+ }
214
+
98
215
  /** Kysely's own Postgres migration-lock id, so a `pg` migrator and a Data API one exclude each other. */
99
216
  const MIGRATION_LOCK_ID = '3853314791062309107'
100
217
 
@@ -30,7 +30,10 @@ import type { RdsDataClientLike, RdsDataCommand } from './rds-data-dialect'
30
30
  * - a statement inside a transaction runs on that transaction's one connection, until Commit/Rollback;
31
31
  * - a response over 1 MiB is refused, and an unknown transaction id is TransactionNotFoundException;
32
32
  * - database errors come back as a message only, WITHOUT a SQLSTATE — the least the Data API is
33
- * reported to give, so what is proven is that SSSB's error handling survives the worst case.
33
+ * reported to give, so what is proven is that SSSB's error handling survives the worst case;
34
+ * - a result with a column of a type the Data API refuses is refused whole, rows or none, with its
35
+ * `UnsupportedResultException`, after the statement has run (REFUSED_RESULT_TYPES says which types, and on what
36
+ * evidence, some of it inferred).
34
37
  *
35
38
  * What it cannot know is AWS's exact wire format (column `typeName`s, timestamp strings, error wording).
36
39
  * It follows PgJDBC's conventions, which the Data API is built on; the `data-api` cutover row is the live
@@ -44,6 +47,30 @@ export interface EmulatedCall {
44
47
 
45
48
  const RESPONSE_LIMIT_BYTES = 1024 * 1024
46
49
 
50
+ /**
51
+ * Result column types the Data API refuses, seen or inferred, by `pg_type.typname`, with the name its error gives them. AWS lists none:
52
+ * "The Data API doesn't support all data types", and the fix it gives is a cast to TEXT (the Aurora User Guide's
53
+ * "Troubleshooting Amazon RDS Data API", "Unsupported result exception"). What is here is evidence:
54
+ *
55
+ * - `char`, Postgres's one-byte "char" (`pg_class.relkind`): refused live on Aurora PostgreSQL with
56
+ * `UnsupportedResultException: The result contains the unsupported data type "CHAR"`, for a result of no rows (Kysely's
57
+ * introspector, on a database with no tables yet), so the refusal reads the columns, not the values;
58
+ * - `bpchar`, `char(n)`: the same JDBC type, `CHAR`, in PgJDBC's type map, on which the Data API is built, so the same
59
+ * error, if the error's "CHAR" is that JDBC type and not the type's own name upper-cased; inferred, not observed;
60
+ * - `_char` and `_bpchar`, arrays of the two, whose elements the Data API would have to return as the same type;
61
+ * inferred, not observed.
62
+ *
63
+ * Strict where unobserved, so a query passes here only if it passes on the evidence's worst reading; a cast to text
64
+ * costs nothing. The `data-api` cutover row's smoke run (`docs/runbooks/data-api.md`, step 3) records what AWS does
65
+ * with each, and a type it answers leaves this map, as one it refuses joins it.
66
+ */
67
+ const REFUSED_RESULT_TYPES: ReadonlyMap<string, string> = new Map([
68
+ ['char', 'CHAR'],
69
+ ['bpchar', 'CHAR'],
70
+ ['_char', 'CHAR'],
71
+ ['_bpchar', 'CHAR'],
72
+ ])
73
+
47
74
  export class RdsDataEmulator implements RdsDataClientLike {
48
75
  /** Every call, in order — the contract suite asserts on the transaction sequence. */
49
76
  readonly calls: EmulatedCall[] = []
@@ -161,6 +188,13 @@ export class RdsDataEmulator implements RdsDataClientLike {
161
188
  client,
162
189
  result.fields.map((field) => field.dataTypeID),
163
190
  )
191
+ const refused = result.fields.find((field) =>
192
+ REFUSED_RESULT_TYPES.has(typeNames.get(field.dataTypeID) ?? ''),
193
+ )
194
+ if (refused) {
195
+ const name = REFUSED_RESULT_TYPES.get(typeNames.get(refused.dataTypeID)!)
196
+ throw awsError('UnsupportedResultException', `The result contains the unsupported data type "${name}"`)
197
+ }
164
198
  const longAsString = input.resultSetOptions?.longReturnType === 'STRING'
165
199
  const columns: ColumnMetadata[] = result.fields.map((field) => ({
166
200
  name: field.name,
@@ -0,0 +1,53 @@
1
+ 'use client'
2
+
3
+ import { Alert, Button, Stack, Text } from '@mantine/core'
4
+ import { useTranslations } from 'next-intl'
5
+ import { useState } from 'react'
6
+
7
+ /**
8
+ * The sign-in card's body for a person the identity provider has signed in but this app refuses
9
+ * (`AuthPort.refusal`): their account names another tenant, or holds something that is not a tenant at all, so it is
10
+ * taken to belong to another site. It says so, and offers one
11
+ * explicit sign-out. Never automatic: on a provider instance shared with another product, signing out ends the
12
+ * person's session there too, which the copy says before they choose.
13
+ *
14
+ * `onSignOut` answers whether the sign-out went through: `false` (or a rejection) shows the error and lets them try
15
+ * again; anything else keeps the spinner while the page navigates (a reload, or the provider's own redirect).
16
+ */
17
+ export function AccountRefused({ onSignOut }: { onSignOut: () => void | Promise<boolean | void> }) {
18
+ const t = useTranslations('auth')
19
+ const [busy, setBusy] = useState(false)
20
+ const [failed, setFailed] = useState(false)
21
+
22
+ async function signOut() {
23
+ setBusy(true)
24
+ setFailed(false)
25
+ try {
26
+ if ((await onSignOut()) === false) {
27
+ setBusy(false)
28
+ setFailed(true)
29
+ }
30
+ } catch {
31
+ setBusy(false)
32
+ setFailed(true)
33
+ }
34
+ }
35
+
36
+ return (
37
+ <Stack gap="sm" data-testid="account-refused">
38
+ <Text fw={600}>{t('refusedTitle')}</Text>
39
+ <Text size="sm">{t('refusedBody')}</Text>
40
+ <Text size="sm" c="gray.7">
41
+ {t('refusedSignOutNote')}
42
+ </Text>
43
+ {failed ? (
44
+ <Alert color="red" role="alert">
45
+ {t('refusedSignOutError')}
46
+ </Alert>
47
+ ) : null}
48
+ <Button onClick={() => void signOut()} loading={busy} data-testid="account-refused-signout">
49
+ {t('signOut')}
50
+ </Button>
51
+ </Stack>
52
+ )
53
+ }
package/src/db/family.ts CHANGED
@@ -8,7 +8,7 @@ import { runWithTenant } from './with-tenant'
8
8
  /**
9
9
  * The database family (ADR-0015, second addendum, point 3): what is specific to one database engine, gathered behind
10
10
  * one object so the framework's logic stays generic over the engine. SSSB has one family today, Postgres, with three
11
- * transports (pglite, node-postgres, the RDS Data API); a second family (libsql, `.claude/future-tasks/db-libsql-family.md`)
11
+ * transports (pglite, node-postgres, the RDS Data API); a second family (libsql, safeinsights/sssb#174)
12
12
  * is a second object of this shape, not a fork of the data layer.
13
13
  *
14
14
  * A family owns:
@@ -102,3 +102,21 @@ export async function listOrgsInTenant(
102
102
  .orderBy('name', 'asc')
103
103
  .execute()
104
104
  }
105
+
106
+ /**
107
+ * An org's display name, by its tenant's slug and its own: the same RLS-free raw read of the `organizations` infra
108
+ * table as the lookups above. The auth port's fixed org source names its home org with it (`listMyOrgs`), since the
109
+ * port knows the org only by slug. Null when the tenant has no such org.
110
+ */
111
+ export async function orgNameForSlugs(db: DbPort, tenantSlug: string, orgSlug: string): Promise<string | null> {
112
+ await db.ready()
113
+ const row = await db
114
+ .getDb()
115
+ .selectFrom('organizations')
116
+ .innerJoin('tenants', 'tenants.id', 'organizations.tenant_id')
117
+ .select('organizations.name as name')
118
+ .where('tenants.slug', '=', tenantSlug)
119
+ .where('organizations.slug', '=', orgSlug)
120
+ .executeTakeFirst()
121
+ return row?.name ?? null
122
+ }
package/src/guide.md CHANGED
@@ -123,6 +123,15 @@ preset, SSSB's conformance suite or `sssb doctor`; keep the rest by hand.
123
123
  - In `appAbilityRules`, grant org-scoped access through the `sameOrg` you are handed, never by a role alone: `sameOrg` is
124
124
  false for a person without standing, and a rule that grants because a role is not some other role would grant
125
125
  `none` too.
126
+ - Under a fixed org source (`params.auth.orgSource` `'fixed'`) everyone has the role `none` or `restricted`, and both
127
+ are restricted (`AuthUser.restricted` and the actor's `restricted`), so `restricted` cannot tell your own admins from
128
+ anyone else. Grant your own people from your own data (a field on the subject, such as its publishers; your own table
129
+ in a route or screen) BEFORE any denial on `restricted`, in `appAbilityRules` and wherever a route or screen reads
130
+ `user.restricted`: a check that denies on `restricted` first locks out everyone, your own admins included. Key that
131
+ grant on `actor.userId`, never an email, which another product on a shared instance may let anyone claim. Every
132
+ person credential reaches your rules (a token, an inbound email: the same `userId`), so a grant meant for the person
133
+ at the keyboard also checks `actor.credential?.kind === 'session'`. Your rules see `none` in no org (`sameOrg` is
134
+ false), so a grant that must be scoped to the home org needs `defaultRole: 'restricted'`.
126
135
 
127
136
  ## UI
128
137
 
@@ -15,7 +15,11 @@
15
15
  "mfaNotImplemented": "This account requires MFA, which arrives with a later slice.",
16
16
  "userMenuLabel": "{name}, account menu",
17
17
  "profileLink": "Profile",
18
- "signOut": "Sign out"
18
+ "signOut": "Sign out",
19
+ "refusedTitle": "This account belongs to another site",
20
+ "refusedBody": "You are signed in, but your account is registered with another site that uses the same sign-in, so it cannot be used here.",
21
+ "refusedSignOutNote": "Signing out here also signs you out of any other site that shares this sign-in.",
22
+ "refusedSignOutError": "You could not be signed out. Try again."
19
23
  },
20
24
  "profile": {
21
25
  "title": "Your profile",
@@ -15,7 +15,11 @@
15
15
  "mfaNotImplemented": "Esta cuenta requiere MFA, que llegará en una fase posterior.",
16
16
  "userMenuLabel": "{name}, menú de la cuenta",
17
17
  "profileLink": "Perfil",
18
- "signOut": "Cerrar sesión"
18
+ "signOut": "Cerrar sesión",
19
+ "refusedTitle": "Esta cuenta pertenece a otro sitio",
20
+ "refusedBody": "Has iniciado sesión, pero tu cuenta está registrada en otro sitio que usa el mismo inicio de sesión, así que no se puede usar aquí.",
21
+ "refusedSignOutNote": "Al cerrar sesión aquí también la cierras en cualquier otro sitio que comparta este inicio de sesión.",
22
+ "refusedSignOutError": "No se pudo cerrar la sesión. Inténtalo de nuevo."
19
23
  },
20
24
  "profile": {
21
25
  "title": "Tu perfil",
package/src/ports/auth.ts CHANGED
@@ -79,6 +79,15 @@ export interface CreatedInvite extends Membership {
79
79
  acceptUrl: string | null
80
80
  }
81
81
 
82
+ /**
83
+ * Why a person the identity provider has signed in is not a user here. `other-tenant`: their account names another
84
+ * tenant under the deployment's metadata key, or holds there something that is not a slug (a single tenancy's guard),
85
+ * so it is taken to belong to another site.
86
+ */
87
+ export interface AuthRefusal {
88
+ reason: 'other-tenant'
89
+ }
90
+
82
91
  /**
83
92
  * Server-side auth port (ADR-0003). Sized to what the app needs — never to Clerk's API.
84
93
  * The custom Mantine auth UI is the ONLY auth UI; both adapters sit behind it.
@@ -112,4 +121,11 @@ export interface AuthPort {
112
121
  listMyOrgs(): Promise<OrgRef[]>
113
122
  /** @throws ForbiddenError when the user has no membership in that org */
114
123
  setActiveOrg(orgSlug: string): Promise<void>
124
+ /**
125
+ * Why the person signed in to the identity provider on this request is refused here, or null when nobody is
126
+ * signed in or nobody is refused: what tells a refused person apart from a signed-out one, which `getCurrentUser`
127
+ * answers alike (null). Optional: only a port that refuses people has it (a single tenancy's guard). The sign-in
128
+ * page reads it to say why, and to offer an explicit sign-out (`@sssb/kit/components/auth/account-refused`).
129
+ */
130
+ refusal?(): Promise<AuthRefusal | null>
115
131
  }
@@ -31,6 +31,7 @@ import type { CheckImpl } from './types'
31
31
  const FORMS: ReadonlySet<string> = new Set([
32
32
  '@sssb/kit/adapters/real/sign-in-form',
33
33
  '@sssb/kit/adapters/real/accept-invite-form',
34
+ '@sssb/kit/adapters/real/account-refused-form',
34
35
  ])
35
36
  const PROVIDER = '@sssb/kit/adapters/real/providers'
36
37
  /**