diff --git a/API/prisma/migrations/20261120130000_team_entry_interface/migration.sql b/API/prisma/migrations/20261120130000_team_entry_interface/migration.sql new file mode 100644 index 00000000..0a604aaf --- /dev/null +++ b/API/prisma/migrations/20261120130000_team_entry_interface/migration.sql @@ -0,0 +1,4 @@ +ALTER TABLE "teams" ADD COLUMN "entry_interface" VARCHAR(6); + +ALTER TABLE "teams" ADD CONSTRAINT "teams_entry_interface_check" + CHECK ("entry_interface" IN ('family', 'work')); diff --git a/API/prisma/schema.prisma b/API/prisma/schema.prisma index 30b2ff6a..aad846bc 100644 --- a/API/prisma/schema.prisma +++ b/API/prisma/schema.prisma @@ -1625,6 +1625,7 @@ model Team { slug String @db.VarChar(63) description String? @db.VarChar(500) isDefault Boolean @default(false) @map("is_default") + entryInterface String? @map("entry_interface") @db.VarChar(6) allowedEmailDomains String[] @default([]) @map("allowed_email_domains") allowedEmails String[] @default([]) @map("allowed_emails") createdAt DateTime @default(now()) @map("created_at") diff --git a/API/src/routes/auth/auth-create-organisation.ts b/API/src/routes/auth/auth-create-organisation.ts index 9b1442ca..23f1ccad 100644 --- a/API/src/routes/auth/auth-create-organisation.ts +++ b/API/src/routes/auth/auth-create-organisation.ts @@ -1,3 +1,5 @@ +import { randomBytes } from 'node:crypto'; +import { buildSessionChoices } from '../../services/session-choices.service.js'; import { rememberCompletedSocialProvider } from '../../services/social/social-browser-preference.service.js'; import { assertLoginOrganization } from '../../services/login-organization.service.js'; import type { FastifyInstance } from 'fastify'; @@ -141,6 +143,14 @@ export function registerAuthCreateOrganisationRoute(app: FastifyInstance): void // Serialize before the active-membership read in createOrganisation so // those bridges cannot create two first teams concurrently. await lockRequiredTeamPlacementUser(lockedSession.userId, { prisma: tx }); + const entryInterface = config.login_flow?.team_interface; + if (entryInterface) { + const choices = await buildSessionChoices( + { userId: lockedSession.userId, config, authenticationEvidenceId: lockedSession.authenticationEvidenceId }, + { prisma: tx, policyPrisma: tx, crossProductPrisma: tx }, + ); + if (!choices.can_create_org) rejectOrganisationCreation(); + } // Claim before writing the new tenant. A later failure rolls the claim // and all team effects back, leaving a legitimate retry possible. @@ -156,8 +166,9 @@ export function registerAuthCreateOrganisationRoute(app: FastifyInstance): void { domain: config.domain, name, - slug, - defaultTeamJoinPolicy: join_policy, + slug: entryInterface === 'family' ? `family-${randomBytes(13).toString('hex')}` : slug, + defaultTeamJoinPolicy: entryInterface === 'family' ? 'INVITE_ONLY' : join_policy, + entryInterface, ownerId: lockedSession.userId, actorUserId: lockedSession.userId, config, diff --git a/API/src/routes/auth/auth-create-team.ts b/API/src/routes/auth/auth-create-team.ts index 752bd4c0..9a85a894 100644 --- a/API/src/routes/auth/auth-create-team.ts +++ b/API/src/routes/auth/auth-create-team.ts @@ -89,6 +89,7 @@ export function registerAuthCreateTeamRoute(app: FastifyInstance): void { QuerySchema.parse(request.query); const config = request.config; const configUrl = request.configUrl; + if (config?.login_flow?.team_interface) throw new AppError('UNAUTHORIZED', 401, 'AUTHENTICATION_FAILED'); if (!config || !configUrl) throw new AppError('BAD_REQUEST', 400, 'MISSING_CONFIG'); assertLoginOrganization(config, org_id); diff --git a/API/src/routes/auth/auth-select-team.ts b/API/src/routes/auth/auth-select-team.ts index 46359f26..7a439429 100644 --- a/API/src/routes/auth/auth-select-team.ts +++ b/API/src/routes/auth/auth-select-team.ts @@ -1,3 +1,4 @@ +import { assertEntryTeam } from '../../services/entry-team-interface.service.js'; import { rememberCompletedSocialProvider } from '../../services/social/social-browser-preference.service.js'; import { assertLoginOrganization } from '../../services/login-organization.service.js'; import { assertIndependentChooserMutation } from '../../services/authentication-evidence.service.js'; @@ -150,9 +151,10 @@ export function registerAuthSelectTeamRoute(app: FastifyInstance): void { now: new Date(), }); await assertIndependentChooserMutation(lockedSession, tx); - if (config.login_flow?.organization_id) { - const invite = await tx.teamInvite.findUnique({ where: { id: inviteId }, select: { orgId: true } }); + if (config.login_flow?.organization_id || config.login_flow?.team_interface) { + const invite = await tx.teamInvite.findUnique({ where: { id: inviteId }, select: { orgId: true, teamId: true } }); assertLoginOrganization(config, invite?.orgId); + await assertEntryTeam(config, invite, tx); } await declineTeamInviteForUser({ prisma: tx, diff --git a/API/src/routes/auth/team-invite-link.ts b/API/src/routes/auth/team-invite-link.ts index 6892074b..b34fe122 100644 --- a/API/src/routes/auth/team-invite-link.ts +++ b/API/src/routes/auth/team-invite-link.ts @@ -88,7 +88,7 @@ export function registerAuthTeamInviteLinkRoute(app: FastifyInstance): void { try { await assertTeamInviteLinkValidForLanding( - { token, domain: request.config.domain }, + { token, domain: request.config.domain, config: request.config }, { prisma: request.adminDb }, ); } catch { diff --git a/API/src/routes/auth/token-response.ts b/API/src/routes/auth/token-response.ts index 67ea9a62..2d07f6a2 100644 --- a/API/src/routes/auth/token-response.ts +++ b/API/src/routes/auth/token-response.ts @@ -8,6 +8,7 @@ export function tokenPairResponse(pair: IssuedTokenPair): Record { reply.header('Cache-Control', 'no-store'); reply.type('text/markdown; charset=utf-8').send(`${renderLlmMarkdown()}\n${machineEnrollmentMarkdown}\n${llmOrganisationBillingMarkdown}\n${llmSmsOperatorsMarkdown}\n${llmRegistrationMarkdown}\n${jobComputeContinuationMarkdown}\n${publicTeamLookupMarkdown}\n` + + 'A registered product may set signed login_flow.team_interface to family or work with auto selection and one callback. The Authenticator lists only matching teams and invites, and can create a matching first team when organisation creation is enabled. Token responses confirm the applied team_interface.\n' + 'Hosted sign-in may narrow its chooser with signed config login_flow.organization_id. Carry the same config URL through code exchange. Teams, invites and creation choices stay within that organization; no eligible team leaves a recoverable empty chooser. Omit the field for all organizations. This grants no membership and does not constrain later workspace-switch grants.\n' + 'Nessie Ledger dispatch and replay refuse uncollected PAYG or a nonregular default with 402 NESSIE_PREPAID_SETUP_REQUIRED. Free usage requires an explicit organisation/team assignment. Paid admission still requires the separate funded atomic reservation. Settlement/reconciliation of existing work remains available.\n' + 'Temporary source-JWKS DNS EAI_AGAIN returns 503 INTEGRATION_JWKS_UNAVAILABLE before identity admission. ' + diff --git a/API/src/routes/root/schema.auth-token.ts b/API/src/routes/root/schema.auth-token.ts index b490adae..75908dd2 100644 --- a/API/src/routes/root/schema.auth-token.ts +++ b/API/src/routes/root/schema.auth-token.ts @@ -46,6 +46,7 @@ export const authTokenEndpoint: EndpointSchema = { '"urn:ietf:params:oauth:token-type:access_token"; confidential token-exchange grant only', 'scope?': 'exact granted request subset of "ai.invoke", "billing.read", "token.provision", "memory.read", and/or "memory.write"; token.provision is never implied by ai.invoke; confidential token-exchange grant only', + 'team_interface?': 'family or work, returned only when the exact active team was verified against the signed hosted application scope.', token_type: '"Bearer"', 'firstLogin?': 'object { memberships: { orgs, teams }, pending_invites, capabilities { can_create_org, can_accept_invite } } — included only on authorization_code exchange when org_features.enabled is true. Never included on refresh_token or team-switch grants.', diff --git a/API/src/services/config.service.ts b/API/src/services/config.service.ts index 39c88e0d..b20e74ff 100644 --- a/API/src/services/config.service.ts +++ b/API/src/services/config.service.ts @@ -219,6 +219,7 @@ const ClientConfigSchema = RequiredConfigSchema.extend({ .object({ email_code_enabled: z.boolean().default(false), team_selection: z.enum(['off', 'auto']).default('off'), + team_interface: z.enum(['family', 'work']).optional(), // Opt in to public team navigation hints after mail-bound acceptance. invitation_return_target: z.boolean().optional(), // Optional exact organisation for this interactive sign-in, carried in the signed config. @@ -294,6 +295,11 @@ const ClientConfigSchema = RequiredConfigSchema.extend({ } } + if (config.login_flow.team_interface && (config.login_flow.team_selection !== 'auto' || config.redirect_urls.length !== 1)) { + ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['login_flow', 'team_interface'], + message: 'team_interface requires auto selection and one registered redirect' }); + } + const teamRedirect = config.login_flow.team_redirect; if (teamRedirect) { const problem = config.redirect_urls.includes(teamRedirect.redirect_url) diff --git a/API/src/services/domain-redirect-allowlist.service.ts b/API/src/services/domain-redirect-allowlist.service.ts index af7b231e..ae98b386 100644 --- a/API/src/services/domain-redirect-allowlist.service.ts +++ b/API/src/services/domain-redirect-allowlist.service.ts @@ -19,7 +19,7 @@ import type { ClientConfig } from './config.service.js'; * never wider, so swallowing the error here cannot weaken redirect security. */ export async function applyDomainRedirectAllowlist(config: ClientConfig): Promise { - if (!getEnv().DATABASE_URL) return config; + if (config.login_flow?.team_interface || !getEnv().DATABASE_URL) return config; let extra: string[]; try { diff --git a/API/src/services/entry-team-interface.service.ts b/API/src/services/entry-team-interface.service.ts new file mode 100644 index 00000000..bbca25e1 --- /dev/null +++ b/API/src/services/entry-team-interface.service.ts @@ -0,0 +1,99 @@ +import { z } from 'zod'; +import type { PrismaClient } from '@prisma/client'; +import { getEnv } from '../config/env.js'; +import { AppError } from '../utils/errors.js'; +import type { ClientConfig } from './config.service.js'; +import { parseDirectoryWebhookTargets, signDirectoryWebhook } from './directory-webhook.service.js'; + +const EntryTeamInterfaceSchema = z.enum(['family', 'work']); +export type EntryTeamInterface = z.infer; + +const ReferenceSchema = z.object({ + orgId: z.string().min(1).max(256), + teamId: z.string().min(1).max(256), +}).strict(); +type Reference = z.infer; +const BATCH_SIZE = 40; +const ResponseSchema = z.object({ + teams: z.array(ReferenceSchema.extend({ interface: EntryTeamInterfaceSchema })).max(BATCH_SIZE), +}).strict(); + +const key = (reference: Reference): string => JSON.stringify([reference.orgId, reference.teamId]); + +/** Query the registered product about its own display classification using references alone. */ +export async function matchingEntryTeams( + config: ClientConfig, + references: readonly Reference[], + prisma: Pick, + deps?: { fetch?: typeof fetch; targetsJson?: string }, +): Promise<(reference: Reference) => boolean> { + const entryInterface = config.login_flow?.team_interface; + if (!entryInterface) return () => true; + const target = parseDirectoryWebhookTargets(deps?.targetsJson ?? getEnv().DIRECTORY_WEBHOOK_TARGETS_JSON) + .find((candidate) => candidate.domain === config.domain); + if (!target) throw new AppError('SERVICE_UNAVAILABLE', 503, 'TEAM_CHOICES_UNAVAILABLE'); + const endpoint = new URL(target.url); + if (!endpoint.pathname.endsWith('/directory-webhook')) { + throw new AppError('SERVICE_UNAVAILABLE', 503, 'TEAM_CHOICES_UNAVAILABLE'); + } + endpoint.pathname = endpoint.pathname.replace(/\/directory-webhook$/, '/team-interfaces'); + endpoint.search = ''; + + const pairs = references.map(({ orgId, teamId }) => ({ orgId, teamId })); + const unique = [...new Map(pairs.map((pair) => [key(pair), pair])).values()]; + const ids = unique.map((reference) => reference.teamId); + const created = ids.length ? await prisma.team.findMany({ + where: { id: { in: ids }, entryInterface: { not: null }, org: { domain: config.domain } }, + select: { id: true, orgId: true, entryInterface: true }, + }) : []; + const createdByKey = new Map(created.map((team) => [key({ orgId: team.orgId, teamId: team.id }), team.entryInterface])); + const matches = new Set(unique.filter((reference) => createdByKey.get(key(reference)) === entryInterface).map(key)); + const unclassified = unique.filter((reference) => !createdByKey.has(key(reference))); + + try { + const signal = AbortSignal.timeout(2_000); + for (let offset = 0; offset < unclassified.length; offset += BATCH_SIZE) { + const batch = unclassified.slice(offset, offset + BATCH_SIZE); + const body = JSON.stringify({ type: 'team.interfaces', version: 1, domain: config.domain, teams: batch }); + const timestamp = String(Math.floor(Date.now() / 1000)); + const response = await (deps?.fetch ?? fetch)(endpoint, { + method: 'POST', body, redirect: 'error', signal, + headers: { + 'content-type': 'application/json', + 'x-uoa-timestamp': timestamp, + 'x-uoa-signature': signDirectoryWebhook(body, timestamp, target.secret), + }, + }); + if (!response.ok) { + await response.body?.cancel(); + throw new Error('product classification unavailable'); + } + const { teams } = ResponseSchema.parse(await response.json()); + const byKey = new Map(teams.map((team) => [key(team), team.interface])); + if (teams.length !== batch.length || byKey.size !== batch.length || batch.some((team) => !byKey.has(key(team)))) { + throw new Error('incomplete product classification'); + } + for (const team of batch) { + if (byKey.get(key(team)) === entryInterface) matches.add(key(team)); + } + } + } catch { + throw new AppError('SERVICE_UNAVAILABLE', 503, 'TEAM_CHOICES_UNAVAILABLE'); + } + return (reference) => matches.has(key(reference)); +} + +export async function assertEntryTeam( + config: ClientConfig, + team: { orgId?: string | null; teamId?: string | null } | null, + prisma: Pick, + errorCode = 'AUTHENTICATION_FAILED', + status = 401, +): Promise { + if (!config.login_flow?.team_interface) return; + if (team?.orgId && team.teamId) { + const reference = { orgId: team.orgId, teamId: team.teamId }; + if ((await matchingEntryTeams(config, [reference], prisma))(reference)) return; + } + throw new AppError(status === 403 ? 'FORBIDDEN' : 'UNAUTHORIZED', status, errorCode); +} diff --git a/API/src/services/organisation.service.organisation.ts b/API/src/services/organisation.service.organisation.ts index 02e29714..4f1ea059 100644 --- a/API/src/services/organisation.service.organisation.ts +++ b/API/src/services/organisation.service.organisation.ts @@ -130,6 +130,7 @@ export async function createOrganisation( name: string; /** Optional default-team visibility for the hosted first-team continuation. */ defaultTeamJoinPolicy?: string; + entryInterface?: 'work' | 'family'; /** Chosen tenant address. Omitted derives one from the name. */ slug?: string; ownerId: string; @@ -223,6 +224,7 @@ export async function createOrganisation( name, }), isDefault: true, + ...(params.entryInterface ? { entryInterface: params.entryInterface } : {}), ...(defaultTeamJoinPolicy === undefined ? {} : { joinPolicy: defaultTeamJoinPolicy }), }, // Widened from `{ id }` so the create response can carry the whole team diff --git a/API/src/services/required-team-placement.service.ts b/API/src/services/required-team-placement.service.ts index b9b6f987..4c510c65 100644 --- a/API/src/services/required-team-placement.service.ts +++ b/API/src/services/required-team-placement.service.ts @@ -86,7 +86,7 @@ export async function resolveRequiredAuthorizationTeam( } } - if (!placementAllowed || params.config.login_flow?.organization_id) { + if (!placementAllowed || params.config.login_flow?.organization_id || params.config.login_flow?.team_interface) { throw new AppError('UNAUTHORIZED', 401, 'INVALID_AUTH_CODE'); } diff --git a/API/src/services/session-choices.service.ts b/API/src/services/session-choices.service.ts index 90584725..319c03eb 100644 --- a/API/src/services/session-choices.service.ts +++ b/API/src/services/session-choices.service.ts @@ -3,6 +3,7 @@ import type { PrismaClient } from '@prisma/client'; import { requireAuthenticationEvidence } from './authentication-evidence.service.js'; import { activeAuthorityUserWhere,organisationManagedTeams } from './organisation-team-authority.service.js'; +import { matchingEntryTeams, type EntryTeamInterface } from './entry-team-interface.service.js'; import type { ClientConfig } from './config.service.js'; import { getAdminPrisma, getPrisma } from '../db/prisma.js'; import { avatarImageBaseUrl, publicTeamAvatarImageUrl } from '../utils/avatar-url.js'; @@ -71,6 +72,7 @@ export type TeamChoiceCreatableOrg = { export type SessionChoices = { organization_id?: string; + team_interface?: EntryTeamInterface; manageable_orgs?: TeamChoiceCreatableOrg[]; teams: TeamChoiceTeam[]; pending_invites: TeamChoicePendingInvite[]; @@ -151,8 +153,10 @@ export async function buildSessionChoices( const prisma = deps?.prisma ?? (getPrisma() as unknown as TeamChooserPrisma); const now = deps?.now ? deps.now() : new Date(); const requestedOrgId = params.config.login_flow?.organization_id; + const entryInterface = params.config.login_flow?.team_interface; const emptyChoices: SessionChoices = { teams: [], pending_invites: [], can_create_org: false, creatable_orgs: [], - ...(requestedOrgId ? { organization_id: requestedOrgId } : {}) }; + ...(requestedOrgId ? { organization_id: requestedOrgId } : {}), + ...(entryInterface ? { team_interface: entryInterface } : {}) }; let allowedOrgId: string | undefined; if (params.authenticationEvidenceId) { const authority = (deps?.crossProductPrisma ?? prisma) as PrismaClient; @@ -189,7 +193,7 @@ export async function buildSessionChoices( // team TO. Only queried when the domain has opted in — otherwise the chooser offers no // creation and the read would be dead weight on every login. const canCreateTeams = Boolean( - !allowedOrgId && params.config.org_features?.enabled && params.config.org_features.allow_user_create_team, + !entryInterface && !allowedOrgId && params.config.org_features?.enabled && params.config.org_features.allow_user_create_team, ); const [sameDomainTeamRows, inviteRows, orgRows] = await Promise.all([ @@ -223,6 +227,8 @@ export async function buildSessionChoices( }) }, select: { id: true, + teamId: true, + orgId: true, team: { select: { name: true } }, org: { select: { name: true } }, invitedByName: true, @@ -274,8 +280,11 @@ export async function buildSessionChoices( ).values(), ]; + const referenceOf = (row: (typeof teamRows)[number]) => ({ teamId: row.teamId, orgId: row.team.orgId }); + const matches = await matchingEntryTeams(params.config, [...teamRows.map(referenceOf), ...inviteRows], prisma); + const eligibleInvites = inviteRows.filter(matches); const avatarBaseUrl = avatarImageBaseUrl(); - const teams: TeamChoiceTeam[] = teamRows.map((row) => ({ + const teams: TeamChoiceTeam[] = teamRows.filter((row) => matches(referenceOf(row))).map((row) => ({ teamId: row.teamId, orgId: row.team.orgId, name: row.team.name, @@ -288,8 +297,8 @@ export async function buildSessionChoices( })); // Member-initiated invitations record only `invitedByUserId` — resolve those inviters. - const invitedBy = await resolveInviterLabel(inviteRows, { prisma }); - const pendingInvites: TeamChoicePendingInvite[] = inviteRows.map((row) => ({ + const invitedBy = await resolveInviterLabel(eligibleInvites, { prisma }); + const pendingInvites: TeamChoicePendingInvite[] = eligibleInvites.map((row) => ({ inviteId: row.id, teamName: row.team.name, orgName: row.org?.name ?? null, @@ -306,7 +315,7 @@ export async function buildSessionChoices( row.org.ownerId===params.userId?'owner':row.role, 'teams.manage')) .map((row) => ({ orgId: row.orgId, orgName: row.org.name })); - const manageableOrgs = allowedOrgId ? [] : await (deps?.crossProductPrisma ?? prisma).orgMember.findMany({ + const manageableOrgs = allowedOrgId || entryInterface ? [] : await (deps?.crossProductPrisma ?? prisma).orgMember.findMany({ where: { userId: params.userId, status: 'ACTIVE', ...(requestedOrgId ? { orgId: requestedOrgId } : {}), org: { ownerId: params.userId, lifecycleStatus: 'ACTIVE', ...(policy.scope === 'all_active_memberships' ? {} : { domain }) } }, select: { orgId: true, org: { select: { name: true } } }, @@ -314,10 +323,12 @@ export async function buildSessionChoices( return { ...(requestedOrgId ? { organization_id: requestedOrgId } : {}), + ...(entryInterface ? { team_interface: entryInterface } : {}), teams, pending_invites: pendingInvites, ...(manageableOrgs.length ? { manageable_orgs: manageableOrgs.map((m) => ({ orgId: m.orgId, orgName: m.org.name })) } : {}), - can_create_org: !allowedOrgId && !requestedOrgId && Boolean(params.config.org_features?.allow_user_create_org), + can_create_org: !allowedOrgId && !requestedOrgId && (!entryInterface || teams.length === 0) + && Boolean(params.config.org_features?.allow_user_create_org), creatable_orgs: creatableOrgs, }; } diff --git a/API/src/services/team-finalize.service.ts b/API/src/services/team-finalize.service.ts index d4b05f04..ff269ba0 100644 --- a/API/src/services/team-finalize.service.ts +++ b/API/src/services/team-finalize.service.ts @@ -1,3 +1,4 @@ +import { assertEntryTeam } from './entry-team-interface.service.js'; import { assertLoginOrganization } from './login-organization.service.js'; import { recordIndependentAuthentication, requireAuthenticationEvidence, type VerifiedAuthenticationEvent } from './authentication-evidence.service.js'; import type { PrismaClient } from '@prisma/client'; @@ -107,6 +108,8 @@ export async function finalizeWithTwoFaPolicy( const team = params.orgId === undefined ? {} : { orgId: params.orgId, teamId: params.teamId as string }; + await assertEntryTeam(params.config, params, deps?.teamPrisma ?? deps?.prisma ?? getAdminPrisma()); + // When team selection is transactional, use that transaction so a // freshly accepted invite's organisation policy is visible before commit. const twoFaPolicy = await resolveTwoFaPolicy( diff --git a/API/src/services/team-invite-link.service.ts b/API/src/services/team-invite-link.service.ts index 9949641c..4d500deb 100644 --- a/API/src/services/team-invite-link.service.ts +++ b/API/src/services/team-invite-link.service.ts @@ -1,3 +1,4 @@ +import { assertEntryTeam } from './entry-team-interface.service.js'; import type { PrismaClient } from '@prisma/client'; import type { ClientConfig } from './config.service.js'; @@ -308,7 +309,7 @@ async function findValidInviteLink( * redemption; callers render the generic invalid-link page on any thrown error. */ export async function assertTeamInviteLinkValidForLanding( - params: { token: string; domain: string }, + params: { token: string; domain: string; config?: ClientConfig }, deps?: InviteLinkDeps, ): Promise { const env = deps?.env ?? getEnv(); @@ -323,7 +324,8 @@ export async function assertTeamInviteLinkValidForLanding( void params.domain; const tokenHash = hashToken(params.token, sharedSecret); - await findValidInviteLink(prisma, { tokenHash, now }); + const { link } = await findValidInviteLink(prisma, { tokenHash, now }); + if (params.config) await assertEntryTeam(params.config, link, prisma); } export type RedeemTeamInviteLinkResult = { teamId: string; orgId: string }; @@ -345,7 +347,6 @@ export async function redeemTeamInviteLink( }, deps?: InviteLinkDeps, ): Promise { - void params.config; const env = deps?.env ?? getEnv(); assertDatabaseEnabled(env); @@ -358,6 +359,7 @@ export async function redeemTeamInviteLink( const result = await runInTransaction(prisma, async (tx) => { const { link, team } = await findValidInviteLink(tx, { tokenHash, now }); + await assertEntryTeam(params.config, link, tx); await lockTeamMembershipRows( { userId: params.userId, orgId: team.orgId, teamId: team.id }, { prisma: tx }, diff --git a/API/src/services/team-invite.service.acceptance.ts b/API/src/services/team-invite.service.acceptance.ts index 69d78d80..8af461ab 100644 --- a/API/src/services/team-invite.service.acceptance.ts +++ b/API/src/services/team-invite.service.acceptance.ts @@ -1,3 +1,4 @@ +import { assertEntryTeam } from './entry-team-interface.service.js'; import { requireIdentityEmail } from './entity-lifecycle.service.js'; import type { Prisma } from '@prisma/client'; import type { ClientConfig } from './config.service.js'; @@ -69,6 +70,7 @@ export async function acceptTeamInviteWithinTransaction(params: { if (!invite) { throw new AppError('BAD_REQUEST', 400); } + await assertEntryTeam(params.config, invite, params.prisma); if (invite.revokedAt) { throw new AppError('BAD_REQUEST', 400, 'INVITE_INVALID'); } diff --git a/API/src/services/team-switch-token.service.ts b/API/src/services/team-switch-token.service.ts index 505b3796..25d3705c 100644 --- a/API/src/services/team-switch-token.service.ts +++ b/API/src/services/team-switch-token.service.ts @@ -1,3 +1,4 @@ +import { assertEntryTeam } from './entry-team-interface.service.js'; import type { PrismaClient } from '@prisma/client'; import { getEnv, requireEnv } from '../config/env.js'; @@ -87,7 +88,10 @@ export async function exchangeTeamSwitchForTokens( const source = await tx.refreshToken.findUniqueOrThrow({ where: { tokenHash: hashRefreshToken(params.refreshToken, sharedSecret), } }); - if (!source.assuranceId) return rotationPolicy(row); + if (!source.assuranceId) { + await rotationPolicy(row); + return assertEntryTeam(params.config, targetTeam, tx, 'TEAM_NOT_AVAILABLE', 403); + } const user = await tx.user.findUnique({ where: { id: row.userId, lifecycleStatus: 'ACTIVE' }, select: { tokenVersion: true } }); if (!user) throw new AppError('UNAUTHORIZED', 401, 'INVALID_REFRESH_TOKEN'); @@ -108,6 +112,7 @@ export async function exchangeTeamSwitchForTokens( } throw error; } + await assertEntryTeam(params.config, targetTeam, tx, 'TEAM_NOT_AVAILABLE', 403); // The existing product recovery path starts normal target-bound authorization. // Refuse before any edge commits, preserving every original holder and deadline. throw new AppError('FORBIDDEN', 403, 'INTERACTION_REQUIRED'); diff --git a/API/src/services/token.service.ts b/API/src/services/token.service.ts index 37556548..6a3d6b49 100644 --- a/API/src/services/token.service.ts +++ b/API/src/services/token.service.ts @@ -1,3 +1,4 @@ +import { assertEntryTeam, type EntryTeamInterface } from './entry-team-interface.service.js'; import { resolveTokenFamilyAssurance } from './token-assurance.service.js'; import { requireIdentityEmail } from './entity-lifecycle.service.js'; import type { PrismaClient } from '@prisma/client'; @@ -102,6 +103,7 @@ export type IssuedTokenPair = { refreshToken: string; refreshTokenExpiresInSeconds: number; firstLogin?: FirstLoginBlock; + teamInterface?: EntryTeamInterface; }; export async function issueTokenPairForUser( @@ -184,6 +186,9 @@ export async function issueTokenPairForUser( throw new AppError('UNAUTHORIZED', 401, 'AUTHENTICATION_FAILED'); } + const teamInterface = params.config.login_flow?.team_interface; + await assertEntryTeam(params.config, params.active ?? null, deps?.adminPrisma ?? prisma, 'INVALID_REFRESH_TOKEN'); + const org = activeOrgContext ?? (params.config.org_features?.enabled && !assuranceId @@ -203,6 +208,10 @@ export async function issueTokenPairForUser( ? { ...params.active, tenantSlug: activeOrgContext.tenant_slug } : null; + const scopedOrg = org && active && teamInterface + ? { org_id: org.org_id, tenant_slug: org.tenant_slug, org_role: org.org_role, + teams: [active.teamId], team_roles: Object.fromEntries(Object.entries(org.team_roles).filter(([id]) => id === active.teamId)) } + : org; const accessToken = await signAccessToken({ userId: params.userId, email: requireIdentityEmail(user.email), @@ -215,12 +224,12 @@ export async function issueTokenPairForUser( tokenVersion: user.tokenVersion, assuranceId, assuranceConnectionId, - org, + org: scopedOrg, active, relyingPartyToken: accessTokenContext.relyingPartyToken, }); - const firstLogin = params.includeFirstLogin + const firstLogin = params.includeFirstLogin && !teamInterface ? ((await buildFirstLoginBlock( { userId: params.userId, config: params.config }, { @@ -237,6 +246,7 @@ export async function issueTokenPairForUser( refreshToken: params.refreshToken, refreshTokenExpiresInSeconds: params.refreshTokenExpiresInSeconds, firstLogin, + teamInterface, assuranceRef, assuranceExpiresAt, }; diff --git a/API/tests/integration/billing-first-paid-nessie-plan.test.ts b/API/tests/integration/billing-first-paid-nessie-plan.test.ts index 070acd57..7a131b75 100644 --- a/API/tests/integration/billing-first-paid-nessie-plan.test.ts +++ b/API/tests/integration/billing-first-paid-nessie-plan.test.ts @@ -59,7 +59,7 @@ describe.skipIf(!process.env.DATABASE_URL)('first paid Nessie plan', () => { async function buyer(slug: string) { const org = await db.organisation.create({ data: { slug, name: slug, ownerId: owner.id, domain: slug + '.example' } }); - const team = await db.team.create({ data: { orgId: org.id, name: 'Team', slug: 'team' } }); + const team = await db.team.create({ data: { orgId: org.id, name: 'Team', slug: 'team' }, select: { id: true } }); await db.orgMember.create({ data: { orgId: org.id, userId: owner.id, role: 'owner' } }); const key = await db.billingAppKey.create({ data: { serviceId: service.id, purpose: 'CUSTOMER_LIFECYCLE', name: slug, keyPrefix: slug, secretDigest: slug, actorIssuer: 'https://' + org.domain, actorAudience: 'https://identity.example', diff --git a/API/tests/unit/auth-create-organisation.route.test.ts b/API/tests/unit/auth-create-organisation.route.test.ts index 5bba05fd..3ae9bc82 100644 --- a/API/tests/unit/auth-create-organisation.route.test.ts +++ b/API/tests/unit/auth-create-organisation.route.test.ts @@ -23,6 +23,7 @@ const prismaMock = vi.hoisted(() => ({ team: { findFirst: vi.fn() }, user: { findUnique: vi.fn() }, })); +const buildSessionChoicesMock = vi.hoisted(() => vi.fn()); const consumeLoginSessionMock = vi.hoisted(() => vi.fn()); const createOrganisationMock = vi.hoisted(() => vi.fn()); const finalizeWithTwoFaPolicyMock = vi.hoisted(() => vi.fn()); @@ -42,6 +43,9 @@ vi.mock('../../src/middleware/config-verifier.js', () => ({ }, })); +vi.mock('../../src/services/session-choices.service.js', () => ({ + buildSessionChoices: (...args: unknown[]) => buildSessionChoicesMock(...args), +})); vi.mock('../../src/services/login-session-use.service.js', () => ({ consumeLoginSession: (...args: unknown[]) => consumeLoginSessionMock(...args), })); @@ -151,6 +155,7 @@ describe('POST /auth/create-organisation', () => { for (const mock of [ prismaMock.team.findFirst, + buildSessionChoicesMock, prismaMock.$queryRaw, prismaMock.user.findUnique, consumeLoginSessionMock, @@ -231,6 +236,21 @@ describe('POST /auth/create-organisation', () => { ); }); + it('creates an invitation-only family from a scoped chooser and rechecks eligibility before writes', async () => { + currentConfig = { ...baseConfig(), login_flow: { team_selection: 'auto', email_code_enabled: true, team_interface: 'family' } }; + buildSessionChoicesMock.mockResolvedValueOnce({ can_create_org: true }).mockResolvedValueOnce({ can_create_org: false }); + const create = async () => postCreateTeam({ login_token: await mintLoginToken(), + name: 'The Oaks', slug: 'supplied-address', join_policy: 'OPEN_TO_ORG' }); + expect((await create()).statusCode).toBe(200); + expect(createOrganisationMock).toHaveBeenCalledWith(expect.objectContaining({ + name: 'The Oaks', slug: expect.stringMatching(/^family-[a-f0-9]{26}$/), + entryInterface: 'family', defaultTeamJoinPolicy: 'INVITE_ONLY', + }), expect.anything()); + expect((await create()).statusCode).toBe(401); + expect(createOrganisationMock).toHaveBeenCalledTimes(1); + expect(consumeLoginSessionMock).toHaveBeenCalledTimes(1); + }); + it('rejects creation when the domain has not enabled self-service teams', async () => { currentConfig = baseConfig(false); const loginToken = await mintLoginToken(); diff --git a/API/tests/unit/session-choices.service.test.ts b/API/tests/unit/session-choices.service.test.ts index 80ebef21..a9929686 100644 --- a/API/tests/unit/session-choices.service.test.ts +++ b/API/tests/unit/session-choices.service.test.ts @@ -42,6 +42,50 @@ function makeConfig(overrides?: Partial): ClientConfig { } describe('buildSessionChoices', () => { + it.each(['family', 'work'] as const)('filters %s choices and enables creation only without a matching team', async (scope) => { + const other = scope === 'family' ? 'work' : 'family'; + const secret = 'dedicated-test-directory-secret-long-enough'; + vi.stubEnv('DIRECTORY_WEBHOOK_TARGETS_JSON', JSON.stringify([{ domain: 'client.example.com', + url: 'https://client.example.com/api/auth/uoa/directory-webhook', secret }])); + const fetch = vi.fn(async (_url: unknown, request: RequestInit) => { + const body = JSON.parse(String(request.body)) as { teams: Array<{ orgId: string; teamId: string }> }; + for (const team of body.teams) expect(Object.keys(team).sort()).toEqual(['orgId', 'teamId']); + return Response.json({ teams: body.teams.map((team) => ({ ...team, + interface: team.teamId.startsWith('family') ? 'family' : 'work' })) }); + }); + vi.stubGlobal('fetch', fetch); + try { + const teamRow = (name: string) => ({ teamId: name, teamRole: 'member', + team: { name, slug: name, orgId: name, iconUrl: null, updatedAt: TEAM_UPDATED_AT, org: { name } } }); + const inviteRow = (name: string) => ({ id: name, teamId: name, orgId: name, + team: { name }, org: { name }, invitedByUserId: null, invitedByName: null }); + const prisma = { + orgMember: { findMany: vi.fn(async () => []) }, + user: { findUnique: vi.fn(async () => ({ email: 'jane@acme.com' })) }, + team: { findMany: vi.fn(async () => []) }, + teamMember: { findMany: vi.fn(async () => [teamRow(scope), teamRow(other)]) }, + teamInvite: { findMany: vi.fn(async () => [inviteRow(scope + '-invite'), inviteRow(other + '-invite')]) }, + }; + const config = makeConfig({ login_flow: { team_interface: scope, email_code_enabled: true, team_selection: 'auto' }, + org_features: { allow_user_create_org: true } }); + const read = () => buildSessionChoices({ userId: 'user-1', config }, { policy: CLIENT_DOMAIN_TEAM_POLICY, prisma }); + const mixed = await read(); + expect(mixed.teams.map(({ name }) => name)).toEqual([scope]); + expect(mixed.pending_invites.map(({ inviteId }) => inviteId)).toEqual([scope + '-invite']); + expect(mixed.can_create_org).toBe(false); + prisma.teamMember.findMany.mockResolvedValueOnce([teamRow(other)]); + const empty = await read(); + expect(empty.teams).toEqual([]); + expect(empty.can_create_org).toBe(true); + expect(shouldPresentTeamChooser(empty)).toBe(true); + fetch.mockResolvedValueOnce(Response.json({ teams: [] })); + await expect(read()).rejects.toMatchObject({ statusCode: 503, message: 'TEAM_CHOICES_UNAVAILABLE' }); + } finally { + vi.unstubAllGlobals(); + vi.unstubAllEnvs(); + } + }); + it('returns empty choices when the user cannot be found', async () => { const prisma = { orgMember: { findMany: vi.fn(async () => []) }, @@ -212,6 +256,8 @@ describe('buildSessionChoices', () => { }, select: { id: true, + orgId: true, + teamId: true, team: { select: { name: true } }, org: { select: { name: true } }, invitedByName: true, diff --git a/Auth/src/components/team/CreateFirstTeamForm.tsx b/Auth/src/components/team/CreateFirstTeamForm.tsx index 92b1a79c..35e22950 100644 --- a/Auth/src/components/team/CreateFirstTeamForm.tsx +++ b/Auth/src/components/team/CreateFirstTeamForm.tsx @@ -19,6 +19,7 @@ const visibilityDescriptionKeys = { */ export function CreateFirstTeamForm(props: { loginToken: string; + family?: boolean; query: AuthFlowQuery; onOutcome: (outcome: TeamResponseOutcome) => void; }): React.JSX.Element { @@ -58,18 +59,12 @@ export function CreateFirstTeamForm(props: { return (
void handleSubmit(event)} className="flex flex-col gap-4">

- {t('team.createDialog.newOrganisationDescription')} + {t(props.family ? 'team.createFamily.hint' : 'team.createDialog.newOrganisationDescription')}

- {/* - F3: this form creates an ORGANISATION (the route hard-codes its first team to - "General"), so the field is labelled for what it actually names, and the hint says - what the submit produces. `team.createOrg.nameLabel` stays as-is — the create dialog - still uses it for a genuine team name. - */}
setName(event.target.value)} disabled={submitting} @@ -77,10 +72,10 @@ export function CreateFirstTeamForm(props: { autoFocus required /> -

{t('team.createOrg.firstTeamHint')}

+ {props.family ? null :

{t('team.createOrg.firstTeamHint')}

}
-
+ {props.family ? null :
+
} {error ?

{error}

: null}
); diff --git a/Auth/src/hooks/use-popup.tsx b/Auth/src/hooks/use-popup.tsx index a0116c23..69444783 100644 --- a/Auth/src/hooks/use-popup.tsx +++ b/Auth/src/hooks/use-popup.tsx @@ -76,6 +76,7 @@ export type InviteChoice = { /** Mirrors `buildSessionChoices` (API `first-login.service.ts`) field-for-field. */ export type SessionChoices = { organization_id?: string; + team_interface?: 'family' | 'work'; teams: TeamChoice[]; pending_invites: InviteChoice[]; can_create_org: boolean; diff --git a/Auth/src/i18n/translations/cs.ts b/Auth/src/i18n/translations/cs.ts index 17ee8352..89c8c0d2 100644 --- a/Auth/src/i18n/translations/cs.ts +++ b/Auth/src/i18n/translations/cs.ts @@ -114,6 +114,9 @@ export const cs = { 'team.createOrg.submit': 'Vytvořit tým', 'team.createOrg.cancel': 'Zrušit', 'team.createOrg.organisationNameLabel': 'Název organizace', + 'team.createFamily.title': 'Vytvořit rodinu', + 'team.createFamily.name': 'Název rodiny', + 'team.createFamily.hint': 'Zvolte název rodiny. Další členy můžete pozvat v aplikaci Nessie Family.', 'team.createOrg.firstTeamHint': 'Váš první tým se bude jmenovat stejně jako organizace — později jej můžete přejmenovat.', 'team.createOrg.error.nameTaken': diff --git a/Auth/src/i18n/translations/en.ts b/Auth/src/i18n/translations/en.ts index 0627de30..7caa5b5d 100644 --- a/Auth/src/i18n/translations/en.ts +++ b/Auth/src/i18n/translations/en.ts @@ -116,6 +116,9 @@ export const en = { 'team.createOrg.submit': 'Create team', 'team.createOrg.cancel': 'Cancel', 'team.createOrg.organisationNameLabel': 'Organisation name', + 'team.createFamily.title': 'Create a family', + 'team.createFamily.name': 'Family name', + 'team.createFamily.hint': 'Choose a name for your family. You can invite people in Nessie Family.', 'team.createOrg.firstTeamHint': 'Your first team will have the same name as the organisation — you can rename it later.', 'team.createOrg.error.nameTaken': diff --git a/Auth/src/i18n/translations/es.ts b/Auth/src/i18n/translations/es.ts index 8c8bfa39..2a76ebdc 100644 --- a/Auth/src/i18n/translations/es.ts +++ b/Auth/src/i18n/translations/es.ts @@ -114,6 +114,9 @@ export const es = { 'team.createOrg.submit': 'Crear equipo', 'team.createOrg.cancel': 'Cancelar', 'team.createOrg.organisationNameLabel': 'Nombre de la organización', + 'team.createFamily.title': 'Crear una familia', + 'team.createFamily.name': 'Nombre de la familia', + 'team.createFamily.hint': 'Elige un nombre para tu familia. Puedes invitar a otras personas en Nessie Family.', 'team.createOrg.firstTeamHint': 'Tu primer equipo tendrá el mismo nombre que la organización; puedes cambiarle el nombre más adelante.', 'team.createOrg.error.nameTaken': diff --git a/Auth/src/pages/TeamChooserPage.test.tsx b/Auth/src/pages/TeamChooserPage.test.tsx index b2dfab4a..56c90c4d 100644 --- a/Auth/src/pages/TeamChooserPage.test.tsx +++ b/Auth/src/pages/TeamChooserPage.test.tsx @@ -222,6 +222,16 @@ describe('TeamChooserPage SSR rendering', () => { expect(withExistingTeams).toContain('aria-label="Create team"'); }); + it('offers family creation beside a matching invitation without work setup fields', () => { + const html = renderChooser({ team_interface: 'family', teams: [], can_create_org: true, + pending_invites: [{ inviteId: 'invite-1', teamName: 'The Oaks', invitedBy: null }] }); + expect(html).toContain('Create a family'); + expect(html).toContain('Family name'); + expect(html).toContain('The Oaks'); + expect(html).not.toContain('Organisation name'); + expect(html).not.toContain('Visibility'); + }); + it('auto-skips a single team with no pending invites (never shows a one-item chooser)', () => { const html = renderChooser({ teams: [{ teamId: 't1', orgId: 'o1', name: 'Solo Team', role: 'owner' }], diff --git a/Auth/src/pages/TeamChooserPage.tsx b/Auth/src/pages/TeamChooserPage.tsx index 2f1668bb..079747df 100644 --- a/Auth/src/pages/TeamChooserPage.tsx +++ b/Auth/src/pages/TeamChooserPage.tsx @@ -192,7 +192,7 @@ export function TeamChooserPage(): React.JSX.Element { // With no usable team or invitation there is no organisation destination to pick. Put the // first-team form directly in the chooser rather than stranding it behind a floating modal. const showInlineFirstTeamForm = - canCreateNewOrganisation && !hasTeams && !hasInvites && creatableOrgs.length === 0; + canCreateNewOrganisation && !hasTeams && (!hasInvites || Boolean(teamChoices.team_interface)) && creatableOrgs.length === 0; // The inline first-team form already exposes the only available creation destination, so // do not duplicate it with the floating trigger. Every other permitted destination opens the // custom picker. @@ -225,7 +225,7 @@ export function TeamChooserPage(): React.JSX.Element { ) : null}
-

{t('auth.teamChooser.title')}

+

{t(showInlineFirstTeamForm && teamChoices.team_interface === 'family' ? 'team.createFamily.title' : 'auth.teamChooser.title')}

{pendingEmail ? (

{t('teamChooser.subtitle', { email: pendingEmail })} @@ -245,7 +245,8 @@ export function TeamChooserPage(): React.JSX.Element { ) : null} {showInlineFirstTeamForm ? ( - + ) : null} {hasInvites ? ( diff --git a/Auth/src/utils/team-response.ts b/Auth/src/utils/team-response.ts index 4ea0e867..511d096d 100644 --- a/Auth/src/utils/team-response.ts +++ b/Auth/src/utils/team-response.ts @@ -75,18 +75,12 @@ export function interpretTeamResponse(data: unknown): TeamResponseOutcome { if (!isRecord(data)) return { kind: 'error' }; // Chooser payload (design §4.3): no `ok` field, but a bridge `login_token` plus the choices. - if (typeof data.login_token === 'string' && Array.isArray(data.teams)) { + const choices = toSessionChoices(data); + if (typeof data.login_token === 'string' && choices) { return { kind: 'chooser', loginToken: data.login_token, - choices: { - ...(typeof data.organization_id === 'string' ? { organization_id: data.organization_id } : {}), - teams: toTeamChoices(data.teams), - pending_invites: toInviteChoices(data.pending_invites), - can_create_org: Boolean(data.can_create_org), - creatable_orgs: toCreatableOrgs(data.creatable_orgs), - manageable_orgs: toCreatableOrgs(data.manageable_orgs), - }, + choices, }; } @@ -123,6 +117,7 @@ export function toSessionChoices(data: unknown): SessionChoices | null { if (!isRecord(data) || !Array.isArray(data.teams)) return null; return { ...(typeof data.organization_id === 'string' ? { organization_id: data.organization_id } : {}), + ...(data.team_interface === 'family' || data.team_interface === 'work' ? { team_interface: data.team_interface } : {}), teams: toTeamChoices(data.teams), pending_invites: toInviteChoices(data.pending_invites), can_create_org: Boolean(data.can_create_org), diff --git a/Docs/brief.md b/Docs/brief.md index 466d6f33..d1c17604 100644 --- a/Docs/brief.md +++ b/Docs/brief.md @@ -2246,7 +2246,7 @@ direct membership additions use that exact-organisation uniqueness, so joining o does not prevent joining another. A single-team chooser auto-skips only when there is neither a new-organisation option nor an authorised existing-organisation destination to create in. -##### Emailed invitation validity and failure copy (2026-09 clarification) +##### App-specific team choice\n\nA registered product can set the signed login flow team interface to family or work.\nThe verified chooser uses the product’s classification of the eligible UOA organisation and\nteam references. The app’s chooser shows only matching teams and pending invitations.\nIf the person has no matching team and creation is enabled, they can create an organisation\nand its first team here. A family uses an internal address and invitation-only membership.\nThe token response confirms the app interface for the exact selected team.\n\n##### Emailed invitation validity and failure copy (2026-09 clarification) An emailed team invitation is valid for exactly 24 hours from its send or resend. The durable `TeamInvite.expiresAt` and the linked `VerificationToken.expiresAt` use that same deadline class;