Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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'));
1 change: 1 addition & 0 deletions API/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
15 changes: 13 additions & 2 deletions API/src/routes/auth/auth-create-organisation.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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.
Expand All @@ -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,
Expand Down
1 change: 1 addition & 0 deletions API/src/routes/auth/auth-create-team.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
6 changes: 4 additions & 2 deletions API/src/routes/auth/auth-select-team.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion API/src/routes/auth/team-invite-link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
1 change: 1 addition & 0 deletions API/src/routes/auth/token-response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export function tokenPairResponse(pair: IssuedTokenPair): Record<string, unknown
refresh_token: pair.refreshToken,
refresh_token_expires_in: pair.refreshTokenExpiresInSeconds,
token_type: 'Bearer',
...(pair.teamInterface ? { team_interface: pair.teamInterface } : {}),
...(pair.assuranceRef ? { assurance_ref: pair.assuranceRef,
assurance_expires_at: pair.assuranceExpiresAt } : {}),
...(pair.firstLogin ? { firstLogin: pair.firstLogin } : {}),
Expand Down
1 change: 1 addition & 0 deletions API/src/routes/root/config-docs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ export const configJwtDocumentation = {
'array of { email_domain, org_id, team_id? } — email-domain-based org/team placement',
language: 'string — currently selected language override',
login_flow: {
team_interface: 'Optional family or work for registered products with a directory team-classification endpoint. Requires auto team selection and one signed callback. Filters memberships and invitations before display, and allows creation in the Authenticator when no eligible team exists and organisation creation is enabled.',
organization_id: 'Optional exact UOA organisation ID for this hosted sign-in; narrows choices before auto-selection and forbids completing in a different organisation.',
email_code_enabled: 'boolean (default false)',
invitation_return_target:
Expand Down
1 change: 1 addition & 0 deletions API/src/routes/root/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ export function registerRootRoute(app: FastifyInstance): void {
docs: '/llm',
api: '/api',
team_redirect: { config: 'login_flow.team_redirect', description: 'Optional { redirect_url, template }: a sign-in that asks for that registered redirect URL and finishes inside a team receives its code at the team address the template names, a direct organisation subdomain of the registered host. The token exchange presents the address the code arrived at. No membership or access is granted.' },
app_team_sign_in: { config: 'login_flow.team_interface', description: 'Optional family or work. Requires auto team selection and a single signed callback. The Authenticator filters teams and invitations and offers matching first-team creation when enabled.' },
organization_sign_in: { config: 'login_flow.organization_id', description: 'Optional exact UOA organization for hosted sign-in choices and completion; no membership grant. Omit for all eligible organizations.' },
browser_team_reauthorization: { entry: '/auth', hint: 'team_hint', preference_cookie: 'uoa_social_preference',
description: 'A signed host-only non-authentication provider preference may skip choices for a new S256 browser team entry. It is consumed before the existing real provider flow and renewed only after completed social authorization. No prompt, native, enterprise, invitation, management or continuation request auto-launches. Original proof and refresh admission are unchanged.' },
Expand Down
1 change: 1 addition & 0 deletions API/src/routes/root/llm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ export function registerLlmRoute(app: FastifyInstance): void {
app.get('/llm', async (_request, reply) => {
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. ' +
Expand Down
1 change: 1 addition & 0 deletions API/src/routes/root/schema.auth-token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.',
Expand Down
6 changes: 6 additions & 0 deletions API/src/services/config.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion API/src/services/domain-redirect-allowlist.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<ClientConfig> {
if (!getEnv().DATABASE_URL) return config;
if (config.login_flow?.team_interface || !getEnv().DATABASE_URL) return config;

let extra: string[];
try {
Expand Down
99 changes: 99 additions & 0 deletions API/src/services/entry-team-interface.service.ts
Original file line number Diff line number Diff line change
@@ -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<typeof EntryTeamInterfaceSchema>;

const ReferenceSchema = z.object({
orgId: z.string().min(1).max(256),
teamId: z.string().min(1).max(256),
}).strict();
type Reference = z.infer<typeof ReferenceSchema>;
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<PrismaClient, 'team'>,
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<PrismaClient, 'team'>,
errorCode = 'AUTHENTICATION_FAILED',
status = 401,
): Promise<void> {
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);
}
2 changes: 2 additions & 0 deletions API/src/services/organisation.service.organisation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion API/src/services/required-team-placement.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
}

Expand Down
Loading
Loading