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
8 changes: 8 additions & 0 deletions hub/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -62,5 +62,13 @@ TEST_DATABASE_URL=postgresql://replica:replica@127.0.0.1:5432/postgres
# ENTRA_OIDC_CLIENT_AUTHENTICATION=managed-identity
# ENTRA_OIDC_MANAGED_IDENTITY_CLIENT_ID=<managed-identity-client-id>

# Development-only sign-in as one local administrator, without GitHub or Entra.
# `npm run dev:api` defaults NODE_ENV to development and enables local sign-in.
# `npm run dev:api:live` disables local sign-in. These values are for running
# server/index.ts directly. Requires the local DATABASE_URL above.
# See docs/development.md.
# NODE_ENV=development
# HUB_LOCAL_SIGN_IN=true

# Trust forwarded client addresses only behind this exact protected proxy-chain length.
# HUB_TRUSTED_PROXY_HOPS=0
2 changes: 2 additions & 0 deletions hub/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ Hub is being rebuilt in TypeScript. Read the [root instructions](../AGENTS.md),

Run Node commands from `hub/`, locally or inside the devcontainer. PostgreSQL and Prisma support configured GitHub authentication, administrator enrollment, Hub sessions, and a seeded read-only prototype index; see [authentication](docs/authentication.md). Other prototype APIs and repository-specific permissions are not built. Agree on the design before adding more product models, permissions, deployment choices, or product API routes.

Use `npm run dev:api` to run Hub with local developer sign-in; this is the default choice for trying or testing Hub. Use `npm run dev:api:live` only when the task needs real GitHub or Entra sign-in configured in `.env`. [Development](docs/development.md#start-with-the-real-api) explains both modes.

`npm test` does not require PostgreSQL. Use `npm run test:database` for `.db.test.ts` and `.db.test.tsx` cases in Node.js or jsdom. Follow the database isolation and reset rules in [testing](docs/testing-and-operations.md).

Keep the top-level `HubThemeProvider` around Hub and Storybook content. It synchronizes the resolved light/dark mode to `<html data-color-mode>` so portals inherit Brand and `--hub-*` tokens. Do not add a fixed light theme to an overlay.
Expand Down
38 changes: 38 additions & 0 deletions hub/client/application/hub-application/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,44 @@ describe("HubApplication()", () => {
expect(screen.queryByRole("button", { name: "Sign in with GitHub" })).toBeNull()
})

it("offers local developer sign-in when the API enables it", async () => {
vi.stubGlobal(
"fetch",
vi.fn((input: RequestInfo | URL) =>
Promise.resolve(
requestUrl(input).endsWith("/api/auth/providers")
? Response.json({ providers: ["local"] })
: new Response(null, { status: 401 }),
),
),
)

renderApplication()

expect(
await screen.findByRole("button", { name: "Sign in as local developer" }),
).toBeInTheDocument()
})

it("leaves local developer sign-in out of administrator enrollment", async () => {
window.history.replaceState({}, "", "/admin-enrollment")
vi.stubGlobal(
"fetch",
vi.fn((input: RequestInfo | URL) =>
Promise.resolve(
requestUrl(input).endsWith("/api/auth/providers")
? Response.json({ providers: ["github", "local"] })
: new Response(null, { status: 401 }),
),
),
)

renderApplication()

expect(await screen.findByRole("button", { name: "Verify with GitHub" })).toBeInTheDocument()
expect(screen.queryByRole("button", { name: /local/i })).toBeNull()
})

it("shows an explicit discovery failure with no fallback actions", async () => {
vi.stubGlobal(
"fetch",
Expand Down
39 changes: 28 additions & 11 deletions hub/client/application/hub-application/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,21 @@ import { useHubTheme } from "@hooks/use-hub-theme"
import { CurrentSessionPage } from "@pages/current-session-page"
import { HomeIndexPage } from "@pages/home-index-page"
import { HubAdminEnrollmentPage } from "@pages/hub-admin-enrollment-page"
import type { HomeSignInAction } from "@pages/home-index-page/types"
import { SessionLoadingPage } from "@pages/session-loading-page"

type SessionState =
| { status: "loading" }
| {
status: "signed-out"
providerDiscoveryFailed: boolean
providers: Array<"github" | "entra">
providers: HomeSignInAction["provider"][]
restoreFailed: boolean
}
| {
status: "signed-in"
providerDiscoveryFailed: boolean
providers: Array<"github" | "entra">
providers: HomeSignInAction["provider"][]
membershipId: string
userId: string
provider: string
Expand All @@ -30,10 +31,16 @@ type SessionState =

const providersSchema = z
.object({
providers: z.array(z.enum(["github", "entra"])),
providers: z.array(z.enum(["github", "entra", "local"])),
})
.strict()

const signInLabels: Record<HomeSignInAction["provider"], string> = {
entra: "Sign in with Microsoft Entra",
github: "Sign in with GitHub",
local: "Sign in as local developer",
}

export function HubApplication() {
const { resolvedColorMode } = useHubTheme()
const [session, setSession] = useState<SessionState>({ status: "loading" })
Expand All @@ -48,7 +55,7 @@ export function HubApplication() {
})
.catch(() => ({
failed: true,
providers: [] as Array<"github" | "entra">,
providers: [] as HomeSignInAction["provider"][],
}))
.then(async (providerResult) => {
try {
Expand Down Expand Up @@ -87,7 +94,7 @@ export function HubApplication() {

if (session.status === "loading") return <SessionLoadingPage />
const providerActions = session.providers.map((provider) => ({
label: provider === "github" ? "Sign in with GitHub" : "Sign in with Microsoft Entra",
label: signInLabels[provider],
path: `/api/auth/${provider}/start`,
provider,
}))
Expand All @@ -106,12 +113,22 @@ export function HubApplication() {
heading: "Enroll a Hub administrator",
description: "Enter the deployment bootstrap secret, then verify your identity.",
secretLabel: "Bootstrap secret",
providerActions: providerActions.map((action) => ({
...action,
label:
action.provider === "github" ? "Verify with GitHub" : "Verify with Microsoft Entra",
path: `/api/auth/${action.provider}/admin-enrollment/start`,
})),
// The local developer is already an administrator, so it has no enrollment step.
providerActions: providerActions.flatMap((action) =>
action.provider === "local"
? []
: [
{
...action,
provider: action.provider,
label:
action.provider === "github"
? "Verify with GitHub"
: "Verify with Microsoft Entra",
path: `/api/auth/${action.provider}/admin-enrollment/start`,
},
],
),
}}
/>
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@ export function administratorProviderLabel(provider: string | null) {
if (!provider) return "Provider profile unavailable"
if (provider === "github") return "GitHub account"
if (provider === "entra") return "Microsoft Entra account"
if (provider === "local") return "Local developer account"
return `${provider} account`
}
8 changes: 6 additions & 2 deletions hub/client/pages/home-index-page/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { MarkGithubIcon, OrganizationIcon } from "@primer/octicons-react"
import { MarkGithubIcon, OrganizationIcon, PersonIcon } from "@primer/octicons-react"
import { Button, Hero, Text } from "@primer/react-brand"
import { useEffect, useId, useState } from "react"

Expand Down Expand Up @@ -135,7 +135,11 @@ export function HomeIndexPage({
<Hero.ButtonGroup className="home__actions">
{data.signInActions.map((action) => {
const SignInIcon =
action.provider === "github" ? MarkGithubIcon : OrganizationIcon
action.provider === "github"
? MarkGithubIcon
: action.provider === "local"
? PersonIcon
: OrganizationIcon
return (
<Button
type="submit"
Expand Down
15 changes: 15 additions & 0 deletions hub/client/pages/home-index-page/stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,21 @@ export const GitHubAndMicrosoftEntra: Story = {
},
}

export const LocalDeveloper: Story = {
args: {
data: {
...data,
signInActions: [
{
label: "Sign in as local developer",
path: "/api/auth/local/start",
provider: "local",
},
],
},
},
}

export const AuthorizationFailed: Story = {
args: {
data: {
Expand Down
2 changes: 1 addition & 1 deletion hub/client/pages/home-index-page/types.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export interface HomeSignInAction {
label: string
path: string
provider: "github" | "entra"
provider: "github" | "entra" | "local"
}

export interface HomeIndexPageData {
Expand Down
2 changes: 1 addition & 1 deletion hub/docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ Domain operations receive only the transaction-scoped repositories they need. A

The [authentication and session flow](authentication.md) uses this foundation to validate explicit GitHub and [Microsoft Entra OIDC](entra-oidc.md) configuration, complete provider user authentication, resolve the immutable external identity, apply current provider-owned assignment evidence, decide current Hub admission, and issue an opaque browser session. An installation may configure either or both providers, and provider network work remains outside identity transactions.

The administrator-management API and retained frontend list and search existing Hub users, designate one to 50 administrators, and revoke one administrator-managed assignment. Sensitive role changes reuse the current session's GitHub or Entra authorization flow and bind one short-lived, one-use continuation to the live session, external identity, operation, and target memberships. The callback and mutation reread current authority before changing roles. This surface does not invite users or manage general membership lifecycle.
The administrator-management API and retained frontend list and search existing Hub users, designate one to 50 administrators, and revoke one administrator-managed assignment. Sensitive role changes reuse the current session's GitHub, Entra, or local authorization flow and bind one short-lived, one-use continuation to the live session, external identity, operation, and target memberships. The callback and mutation reread current authority before changing roles. This surface does not invite users or manage general membership lifecycle.

The administrator security-audit API and retained frontend list Hub-wide identity and administrator records newest first through bounded opaque-cursor pagination. The API rereads the live administrator session and projects stored records through action-specific presentation allowlists. The frontend keeps the cursor opaque, shows stable membership UUIDs when available, and does not load provisional product workspace contracts. Repository audit, export, retention changes, and deletion remain separate work.

Expand Down
6 changes: 6 additions & 0 deletions hub/docs/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,12 @@ Administrator-enrollment rate limits write at most one durable denial audit for

Database guards cover invariants that application validation alone cannot protect across concurrent writers or future code paths. They keep membership ownership and history immutable, keep assignment ownership, provenance, and role immutable, allow only one active administrator-managed assignment per membership, prevent reactivation of revoked administrator-managed assignments, require an assignment identity to belong to the membership user, keep external evidence ordering state immutable and monotonic, permit only first session termination, protect the global revocation identity and exact revision increment, and keep an authorization attempt's server-selected purpose, bootstrap-secret generation, nonce, and revocation generation immutable. Ordinary value-shape and time-order checks remain in the application contracts.

## Local developer sign-in

Run `npm run dev:api` to test Hub on your own machine without registering a GitHub or Entra application. This command enables `HUB_LOCAL_SIGN_IN` and adds a `local` provider with the same start, callback, admission, session, sign-out, rate-limit, and audit behavior as the hosted providers. Its start redirects straight back to `/api/auth/local/callback` instead of an outside sign-in page. The callback always proves one fixed `local-developer` identity with provider-assigned administrator access, so the first sign-in creates an active administrator membership without bootstrap enrollment. Administrator management re-authorizes through the same local flow. Use `npm run dev:api:live` to disable local sign-in and test configured GitHub or Entra providers.

Because anyone who can reach the API could sign in this way, startup requires `NODE_ENV=development` and a local development `DATABASE_URL`. It also requires `HOST` to be `127.0.0.1`, `::1`, or `localhost` and `HUB_APPLICATION_ORIGIN` to be a loopback origin. It cannot be combined with GitHub or Entra. Startup chooses the local provider revision itself: it keeps the current revision for an unchanged restart and moves to the next revision after the mode was turned off or the origin changed. When the origin, encryption key, or bootstrap secret is unset, startup uses `http://127.0.0.1:5173` and throwaway secrets. Restarting with a throwaway key only invalidates sign-ins that were in progress.

## Safety boundaries

GitHub and Entra configuration are explicit and independently revisioned. Only the public github.com endpoints and the exact configured single-tenant Entra issuer are accepted. Provider requests have fixed deadlines, reject redirects, and discard provider tokens and client assertions after validation.
Expand Down
25 changes: 21 additions & 4 deletions hub/docs/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,18 @@ npm run setup

The example URL connects to PostgreSQL on `127.0.0.1:5432`. To use another development database, set `DATABASE_URL` in `.env` instead. Do not commit credentials. With `DATABASE_URL` set, API startup requires a reachable, migrated database so it can reconcile configured providers and durably disable removed providers before serving requests. Run `npm run setup` after creating or updating the database and before `npm run dev:api`.

For a true process-only health check without database or authentication composition, leave `DATABASE_URL` and all authentication settings unset. The health route itself does not query the database, but a database-backed API still fails closed at startup when the database is unreachable or its schema has not been set up.
For a true process-only health check without database or authentication composition, leave `DATABASE_URL` and all authentication settings unset and run `node server/index.ts` directly. The health route itself does not query the database, but a database-backed API still fails closed at startup when the database is unreachable or its schema has not been set up.

## Start with the real API

Run these commands from `hub/`, inside the devcontainer or with local Node.js:
Run these commands from `hub/`, inside the devcontainer or with local Node.js. First choose how you will sign in:

| Command | Sign-in | Use it when |
| --- | --- | --- |
| `npm run dev:api` | One fixed local developer who is a Hub administrator | You want to try or test Hub without setting up a sign-in provider. This is the default. |
| `npm run dev:api:live` | GitHub or Entra, as configured in `.env` | You are testing provider sign-in, administrator enrollment through a provider, or real user identities. |

For example, to start with local sign-in:

```sh
npm run dev:api
Expand All @@ -47,11 +54,21 @@ npm run dev

Open <http://127.0.0.1:5173>. React Router's Vite development server forwards `/api` requests to Express at <http://127.0.0.1:3001>. `GET /api/health` and `GET /api/ready` return JSON. The [authentication and Hub session guide](authentication.md) describes configured sign-in and enrollment. A signed-in member opens the first available repository, or an empty workspace when none exist. The real index supports search, user filtering, pagination, and latest Build status; prototype details are not connected yet.

The API registers authentication routes when `HUB_APPLICATION_ORIGIN` and at least one complete GitHub or Entra profile are configured. Set the shared encryption key and bootstrap secret at the same time. See `.env.example` and [Microsoft Entra OIDC](entra-oidc.md). Both development servers accept connections only from this machine. Stop each with Ctrl+C.
With `npm run dev:api`, the home page shows **Sign in as local developer**. Selecting it signs you in as one fixed local developer who is a Hub administrator. No password or outside account is involved. The API refuses to start in this mode unless `NODE_ENV` is `development` and `DATABASE_URL` points at a local development database. It also requires `HOST` to be `127.0.0.1`, `::1`, or `localhost` and `HUB_APPLICATION_ORIGIN` to be a loopback origin. It refuses GitHub or Entra settings at the same time. Unset origin, encryption key, and bootstrap secret values get local defaults. See [Local developer sign-in](authentication.md#local-developer-sign-in) for how this mode reuses the normal sign-in checks. The command defaults `NODE_ENV` to `development` and enables local sign-in for you.

Remove GitHub or Entra settings from `.env` before switching to local mode; otherwise, use `npm run dev:api:live`. Starting local mode on a database with enabled providers disables those providers. To switch back to live mode on that database, increase the revision of each provider you re-enable by exactly one above its last stored revision. For example, if the last GitHub revision was `1`, set `GITHUB_PROVIDER_REVISION=2`.

With `npm run dev:api:live`, configure `HUB_APPLICATION_ORIGIN` and at least one complete GitHub or Entra profile. Set the shared encryption key and bootstrap secret at the same time. This command refuses to start without provider settings and disables local sign-in even if it is enabled in `.env`. See `.env.example` and [Microsoft Entra OIDC](entra-oidc.md). With the default `HOST`, both development servers accept connections only from this machine. Stop each with Ctrl+C.
Comment thread
nshki marked this conversation as resolved.
Resolved

No authentication-provider database seed is required. API startup validates each configured provider adapter and persists only its provider key, revision number, and public-configuration digest.

To populate a local index, sign in and find your `userId` in the browser's `/api/auth/session` response. Replace `USER_UUID` with that ID:
To populate a local index, sign in as the local developer once, then run:

```sh
NODE_ENV=development npm run db:seed:index
```

When you sign in through GitHub or Entra instead, find your `userId` in the browser's `/api/auth/session` response and pass it to the seed:

```sh
NODE_ENV=development npm run db:seed:index -- USER_UUID
Expand Down
Loading
Loading