# Make your user's app private so only team members can see the records, with Google sign-in

Make a DeepSpace app private to a team with Google sign-in: new sign-ins start with no access, collections give viewers and signed-out visitors nothing, an admin page gives and removes access, and app sign-in stays separate from deploy accounts.

Yes, a DeepSpace app can be made private to a team, with sign-in through Google. Records live in the app's Durable Object, and the server decides by role what each connection receives, so privacy is a matter of roles, not of hiding pages. Five changes to the scaffold make the app team-only:

- every page requires sign-in, with a Google button;
- the WebSocket refuses connections without a token;
- new sign-ins start as `viewer` with no access;
- collections give viewers and signed-out visitors nothing;
- an admin page gives and removes access.

Anyone with a Google account can sign in, so the role, not the sign-in, keeps a stranger out. Magic links, sign-in through a company identity provider, and limiting sign-in to one email domain are not DeepSpace sign-in options today.

**Version:** written for and run with `deepspace@0.43.0` ([changelog](https://deep.space/changelog)). **Docs checked:** October 29, 2026. The code on this page ran in local development with three test accounts on October 29, 2026. Google sign-in itself and a deployed URL were not tried.

## Three kinds of account, kept apart

| Account           | Who has it                               | What it opens                                               | How it's given                                                                                  |
| ----------------- | ---------------------------------------- | ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| App sign-in       | Everyone who uses the app                | The app's pages, with a role: `viewer`, `member` or `admin` | They sign in with Google on the app; an admin sets the role on `/team` (step 5)                 |
| App admin         | The people who decide who gets in        | `/team` and every record                                    | The app owner is always `admin`; an admin can make others admins                                |
| DeepSpace account | The app's owner, and developers they add | Deploys, secrets and logs                                   | `npx deepspace auth login`; other developers with `npx deepspace app collaborators add <email>` |

Team members never need a DeepSpace account or the owner's `~/.deepspace/session` file. A [collaborator](https://docs.deep.space/guides/collaborators) can deploy and can read and overwrite every secret, so confirm with your user before adding one. For why app sign-in is separate from platform accounts, see [Complete your user's request without platform signups](https://docs.deep.space/agents/complete-your-users-request-without-platform-signups).

## Questions to ask the person

These need no technical knowledge to answer, and each answer maps to one setting below.

1. **Who should be able to see the records?** Each of them gets access on `/team`.
2. **Who decides who gets in?** They become admins.
3. **Does everyone have a Google account?** This page shows only the Google button. If some people use GitHub, show both. Someone without either can [create a Google account with the email they already use](https://support.google.com/accounts/answer/27441).
4. **Should every team member see every record, or only the ones they created?** This sets `read` for members in step 4.
5. **Is anything meant for the public, such as a landing page?** Pages at the top level of `src/pages/` stay public; everything under `src/pages/(app)/` becomes private.
6. **Which Google or GitHub account owns the app?** The owner is always an admin. Confirm with your user before signing in or using an existing session for them.

## Step 1: Require sign-in, with only the Google button

In `src/pages/(app)/_layout.tsx`, add `AuthGate` and `AuthOverlay` to the `deepspace` import and wrap the scaffold's `<AuthBoot>` element, leaving everything inside it unchanged:

```tsx
// src/pages/(app)/_layout.tsx
import {
  AuthGate,
  AuthOverlay,
  DeepSpaceAuthProvider,
  useAuthStatus,
} from "deepspace";

<AuthGate fallback={<AuthOverlay providers={["google"]} />}>
  <AuthBoot>{/* the scaffold's existing layout */}</AuthBoot>
</AuthGate>;
```

In the same file, delete the `allowAnonymous` line from the `<RecordProvider>` inside the `AuthBoot` function. Use `providers={['google', 'github']}` to show both buttons. The overlay always shows an email and password field too; it signs in existing accounts only, because public email signup is closed, so in practice it is used by test accounts.

## Step 2: Refuse WebSocket connections without a token

`<AuthGate>` stops the UI from rendering, not a WebSocket from connecting. In `src/server/realtime-routes.ts`, inside `wsRoute()`, replace the optional-token block:

```ts
let auth: VerifyResult | null = null;
if (token) {
  auth = (await verifyJwt(jwtConfig(c.env), token)).result;
  if (!auth) return new Response("Unauthorized", { status: 401 });
}
```

with a required token:

```ts
if (!token) return new Response("Unauthorized", { status: 401 });
const auth = (await verifyJwt(jwtConfig(c.env), token)).result;
if (!auth) return new Response("Unauthorized", { status: 401 });
```

A request to `/ws/<room>` without a token now gets `401`.

## Step 3: Start new sign-ins with no access

New signed-in users get the `member` role by default. In `src/schemas/users-schema.ts`, make them `viewer`, and give viewers no read access to the user directory:

```ts
// src/schemas/users-schema.ts
export const usersSchema: CollectionSchema = {
  name: "users",
  defaultRole: "viewer",
  columns: [...USERS_COLUMNS],
  permissions: {
    viewer: { read: false, create: false, update: "own", delete: false },
    member: { read: "own", create: false, update: "own", delete: false },
    admin: { read: true, create: false, update: true, delete: true },
  },
};
```

The directory change matters. With the scaffold's `viewer: { read: 'own' }`, every signed-in user who isn't an admin gets the name of every registered user, and in the local run a stranger who had just signed in was sent the owner's name. A role whose `read` is `false` receives an empty directory; see [the users directory](https://docs.deep.space/concepts/permissions#the-users-directory). Members still see teammates' names, which shared apps usually need.

## Step 4: Close every collection to viewers and signed-out visitors

Give `'*'` (signed out) and `viewer` nothing in every collection in `src/schemas.ts`. For a collection of records:

```ts
permissions: {
  '*':    { read: false, create: false, update: false, delete: false },
  viewer: { read: false, create: false, update: false, delete: false },
  member: { read: true,  create: true,  update: 'own', delete: 'own' },
  admin:  { read: true,  create: true,  update: true,  delete: true },
}
```

If members should see only their own records (question 4), use `read: 'own'`. The Durable Object drops records a caller can't read before they reach the browser, so this is the rule that protects the data. The scaffold's `settings` collection is already admin-only.

Files follow the same idea. `useR2Files()` uploads to the `'self'` scope by default, which only the uploader can open. `'app'` scope files are public to anyone with the URL, so keep private files out of it; see [file uploads](https://docs.deep.space/guides/file-uploads).

## Step 5: Add the access page and a waiting screen

A person who signs in before they have access should see why the app is empty. This component shows a message to viewers and the page to everyone else:

```tsx
// src/components/MembersOnly.tsx
import type { ReactNode } from "react";
import { useUser } from "deepspace";

export default function MembersOnly({ children }: { children: ReactNode }) {
  const { user, isLoading } = useUser();
  if (isLoading) return null;
  if (!user || user.role === "viewer") {
    return (
      <p>
        You're signed in, but you don't have access yet. Ask an admin to add
        you.
      </p>
    );
  }
  return <>{children}</>;
}
```

In `src/pages/(app)/_layout.tsx`, import it with `import MembersOnly from '../../components/MembersOnly'` and wrap the scaffold's `<Outlet />` in `<MembersOnly>`. The message is for the person; the server rules from steps 2 to 4 are what keep the data out.

Admins give and remove access at `/team`:

```tsx
// src/pages/(app)/team.tsx
import { useAuth, useUser, useUsers } from "deepspace";

export default function TeamPage() {
  const { userId } = useAuth();
  const { user } = useUser();
  const { users, setRole } = useUsers();

  if (user?.role !== "admin") return <p>Only admins can manage access.</p>;

  const waiting = users.filter((u) => u.role === "viewer");
  const team = users.filter((u) => u.role !== "viewer");

  return (
    <>
      <h2>Waiting for access</h2>
      {waiting.length === 0 && <p>Nobody is waiting.</p>}
      {waiting.map((u) => (
        <p key={u.id}>
          {u.name} ({u.email}){" "}
          <button onClick={() => setRole(u.id, "member")}>Give access</button>
        </p>
      ))}
      <h2>Team</h2>
      {team.map((u) => (
        <p key={u.id}>
          {u.name} ({u.email}), {u.role}
          {u.id !== userId && u.role === "member" && (
            <button onClick={() => setRole(u.id, "admin")}>Make admin</button>
          )}
          {u.id !== userId && (
            <button onClick={() => setRole(u.id, "viewer")}>
              Remove access
            </button>
          )}
        </p>
      ))}
    </>
  );
}
```

Add it to `src/nav.ts`:

```ts
{ path: '/team', label: 'Team', roles: ['admin'] },
```

Admins see each person's email because admins receive full user rows. The server refuses `setRole` from anyone who isn't an admin. In the local run, a role change reached the person's open page without a reload, both when access was given and when it was removed.

## Step 6: Check it with three accounts before deploying

This Playwright test signs in an admin and two people without access, records every WebSocket frame the two receive, and checks:

- the WebSocket refuses a connection without a token;
- the two people get the waiting message, and the server sends them no record and no teammate names;
- after the admin gives access, the record appears;
- after the admin removes access, the record disappears.

It uses the SDK's `users` fixture, which signs in `@deepspace.test` accounts; `npx deepspace test accounts list --usable` shows the ones saved on this machine. Creating new test accounts uses the developer's session, so confirm with your user first. The test assumes a page at `/records` with a "Title" input and an "Add" button that creates a record; use one of the app's own pages instead.

```ts
// tests/private.spec.ts
import { test, expect } from "deepspace/testing";
import type { Page } from "@playwright/test";

// Names of three usable test accounts. OWNER must be the app owner for the run (see below).
const OWNER = "Owner Tester";
const A = "Tester A";
const B = "Tester B";
const SECRET = "Payroll 2026";

// Everything the server sends this page over WebSockets, as text.
function recordFrames(page: Page) {
  const frames: string[] = [];
  page.on("websocket", (ws) =>
    ws.on("framereceived", (f) => frames.push(String(f.payload))),
  );
  return frames;
}

test("private app: people without access receive nothing until an admin gives it", async ({
  users,
  request,
}) => {
  test.setTimeout(120_000);

  // 0. The records WebSocket refuses a connection without a token.
  expect((await request.get("/ws/any-room")).status()).toBe(401);

  const [owner, a, b] = await users([OWNER, A, B]);
  const framesA = recordFrames(a.page);
  const framesB = recordFrames(b.page);

  // 1. The owner adds a record.
  await owner.page.goto("/records");
  await owner.page.getByPlaceholder("Title").fill(SECRET);
  await owner.page.getByRole("button", { name: "Add" }).click();
  await expect(owner.page.getByText(SECRET)).toBeVisible();

  // 2. A and B sign in as viewers: a waiting message, and the server sends no record and no teammate names.
  for (const u of [a, b]) {
    await u.page.goto("/records");
    await expect(u.page.getByText("you don't have access yet")).toBeVisible();
  }
  await a.page.waitForTimeout(2_000);
  for (const frames of [framesA, framesB]) {
    expect(frames.length).toBeGreaterThan(0);
    expect(frames.join("\n")).not.toContain(SECRET);
    expect(frames.join("\n")).not.toContain(OWNER);
  }
  expect(framesA.join("\n")).not.toContain(B);
  expect(framesB.join("\n")).not.toContain(A);

  // 3. The owner gives A access on /team; A's open page shows the record without a reload.
  await owner.page.goto("/team");
  await owner.page
    .locator("p", { hasText: a.email })
    .getByRole("button", { name: "Give access" })
    .click();
  await expect(a.page.getByText(SECRET)).toBeVisible();

  // 4. B is still waiting, and still receives nothing.
  await b.page.reload();
  await expect(b.page.getByText("you don't have access yet")).toBeVisible();
  await b.page.waitForTimeout(1_000);
  expect(framesB.join("\n")).not.toContain(SECRET);

  // 5. The owner removes A's access; A's open page loses the record without a reload.
  await owner.page
    .locator("p", { hasText: a.email })
    .getByRole("button", { name: "Remove access" })
    .click();
  await expect(a.page.getByText("you don't have access yet")).toBeVisible();
  await expect(a.page.getByText(SECRET)).toHaveCount(0);
});
```

The owner is always `admin`, and the owner is the developer's account, which the fixture can't sign in. For the test run, make a test account the owner: run `npx deepspace dev start` once so it writes `.dev.vars`, stop it, set `OWNER_USER_ID` in `.dev.vars` to the `userId` of the `OWNER` account in `~/.deepspace/test-accounts.json`, and run Playwright directly. The CLI rewrites `.dev.vars` on the next `dev start`, which undoes the change:

```bash
npx playwright test -c tests/playwright.config.ts tests/private.spec.ts
```

Delete `.wrangler/state`, the local development data, to run it again from empty. Test accounts sign in with email and password, so the Google button itself is untested by this; ask the person to sign in once with Google on the live URL and confirm they land on the waiting message.

## Step 7: Deploy

A deploy records the commit it ships, so commit first. `.dev.vars` is git-ignored and deploy never reads it, so the test owner change doesn't ship:

```bash
git add -A && git commit -m "Make the app private to the team"
npx deepspace deploy --json
```

`serving: "confirmed"` in the result means fresh connections are answered by the new release; see [deployment](https://docs.deep.space/concepts/deployment).

## Common failures and how to fix them

| What you see                                        | Cause                                                                                                                                        | Fix                                                                                               |
| --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
| A stranger who signs in can see teammates' names    | The users schema still has the scaffold's `viewer: { read: 'own' }`                                                                          | Set `viewer: { read: false, … }` (step 3)                                                         |
| Someone who was never given access sees records     | `defaultRole: 'viewer'` is missing, or a collection gives `viewer` or `'*'` read access                                                      | Add `defaultRole` and close the collection (steps 3 and 4)                                        |
| A signed-out visitor gets a blank page              | `allowAnonymous` was removed but `<AuthGate>` wasn't added                                                                                   | Wrap `<AuthBoot>` in `<AuthGate>` (step 1)                                                        |
| A new person isn't under "Waiting for access"       | They haven't signed in yet; people appear after their first sign-in                                                                          | Ask them to open the link and sign in with Google                                                 |
| `/team` says "Only admins can manage access"        | The signed-in account isn't an admin                                                                                                         | Sign in as the owner, or have an admin press **Make admin**                                       |
| The GitHub button is missing                        | `providers={['google']}` shows only Google                                                                                                   | Use `providers={['google', 'github']}`                                                            |
| `npx deepspace test run` fails three scaffold tests | The scaffold's smoke and API tests load `/home` signed out and expect the app's navigation; now a signed-out visitor gets the sign-in screen | Update those tests to sign in through the `users` fixture, or remove them                         |
| The test's admin steps fail                         | The `OWNER` test account isn't the app owner for the run                                                                                     | Set `OWNER_USER_ID` in `.dev.vars` as in step 6                                                   |
| The landing page at `/` is still public             | Pages at the top level of `src/pages/` are static and outside the gate                                                                       | Expected; they have no access to records. Move a page under `src/pages/(app)/` to make it private |

## What to tell the person when the app is private

- **The link:** `https://<app-name>.app.space`.
- **How someone gets in:** they open the link and sign in with Google. They see "you don't have access yet" until an admin gives access on the Team page.
- **Who decides:** the admins, named by account. The owner is always one.
- **Removing someone:** an admin presses **Remove access** on the Team page; it takes effect on their open page right away.
- **What stays public:** the landing page, if there is one, and nothing else.
- **What isn't included:** limiting sign-in to one email domain, magic links and company single sign-on. Anyone can sign in, but only people an admin approves see anything.

## What is available today, and what is planned

Available today, in published `deepspace@0.43.0`:

- Sign-in for app users with Google or GitHub, with `<AuthGate>` and `<AuthOverlay providers>`
- Roles (`viewer`, `member`, `admin`), `defaultRole`, and `setRole` for admins
- Collection permissions enforced in the app's Durable Object, and a user directory limited by the users schema's read rule
- Private (`'self'`) and public (`'app'`) file scopes
- A Playwright fixture that signs in test accounts for multi-user tests
- Deploys to `<app-name>.app.space` from the CLI with a DeepSpace account, which a person creates by signing in with GitHub or Google

In testing on staging, not production: agent accounts that register themselves by solving a math challenge. Production signup for agents is not enabled.

Planned: autonomous agent accounts in production, so the app can be created and kept without a person's DeepSpace sign-in. Under that plan, payments and legal actions will still require a human. See [DeepSpace for agents](https://docs.deep.space/agents).

Building private apps for a business? See [deep.space/enterprise](https://deep.space/enterprise).
