# Sign-in, users and organizations in your app

With the `AUTH` capability, each deployed environment runs the starter's
own sign-in service and keeps its users in the environment's own database.
These are your app's users, separate from Spaceboy accounts.

## Sign-in methods

Declared in `repobot.deploy.json` (`"authMethods": ["email-code"]`); the
list's order is the order on the sign-in screen:

| Method | Needs |
| --- | --- |
| `email-code` (default) | The `EMAIL` capability; codes are emailed from Spaceboy's mail domain, no DNS setup |
| `password` | The `EMAIL` capability (sign-up sends a verification link) |
| `anonymous` | Nothing ("Continue as guest") |
| `google`, `apple` | The provider's credentials, connected on the dashboard (no CLI command) |

The web app has `/login`, `/signup`, `/forgot-password`, `/reset-password`
and `/magic-link` routes out of the box.

## Sign-in email

Sign-in codes and sign-up confirmations go through the platform mail
gateway. Your project's kernel must support it: its `kernel-contract.json`
lists the capability `mail-gateway-transport` (kernel contract v9 or later
with the mail gateway transport; every project created from the current
starter has it). The platform reads that file from the code each deploy
builds, for development and production alike.

An environment whose kernel lacks it, created after the platform stopped
handing apps its shared mail password, cannot send sign-in mail. A
production deploy of an app that signs users in by email code is refused (`sign_in_mail_kernel_too_old`, nothing is deployed). A
development deploy still goes ahead, but prints:

```
WARNING SIGN_IN_MAIL_KERNEL_TOO_OLD: This project's kernel cannot send sign-in mail on this platform version: ...
  Fix:  spaceboy kernel upgrade --project <projectId>
```

(also in `--json` output as `notices`). The app answers sign-in requests
with "Sign-in email is not set up for this app yet." on a current kernel,
or "We couldn't send the email just now" on an older one; retrying does not
help. Run the fix in the project's git checkout, merge the branch it
creates, push, and deploy again.

Limits on sign-in mail, per environment:

| Project | Limits |
| --- | --- |
| Not published (free) | Test addresses and your organisation's members only (see below); 5 an hour; 25 a day (UTC) |
| Published | Anyone; 10 an hour to one address; 400 a day |

A person who hits a limit, or whose address cannot be mailed (bounced,
suppressed), sees one answer: "We couldn't send a sign-in email to that
address. Check it, or try again later." Your app's `spaceboy mail log` and
`spaceboy logs` show the real reason; `spaceboy app signin --send-code` adds
it to its own error (`details.mail` in `--json`).

### Who an unpublished project can sign in

An unpublished project (development, or anything not yet published) sends
sign-in mail to exactly two kinds of address:

- reserved test addresses (below): the code goes to the test inbox;
- the addresses of its organisation's members, owner included: each member's
  account address and, if they sign in to Spaceboy with a different verified
  address, that one too. A pending invitation does not count until it is
  accepted.

Nobody else. To sign in with another real address (a second address of your
own on a separate Spaceboy account, a colleague, a tester), invite it to the
organisation: `spaceboy orgs members invite <email>` or the console's Team
page. Or publish the project to let anyone sign in.

Every other address is refused (`auth_recipient_not_member`). On an
unpublished project, every refused sign-in send, whatever the reason (not a
member, a member whose address bounced or was suppressed, a limit reached),
carries the same `notice` in the gateway's answer, which the app may show
the person as written:

```json
{ "state": "refused", "reason": "auth_recipient_not_member",
  "notice": { "code": "signin_testing_only",
              "message": "This app is still being tested, so it sends sign-in emails only to the people building it and to test addresses." } }
```

The notice describes the project, not the address, and appears on every
refusal alike, so showing it reveals nothing about the address: not
whether it belongs to a member, has an account in the app, bounced or was
suppressed. Show `notice.message` and nothing else; `reason` and `message`
are the true reason for you, and `spaceboy mail log` records it too. A
sent message has `"notice": null`, and so does every answer of a published
project (the app keeps its one generic sentence there).

Refused attempts are logged one by one up to 20 an hour per environment (40
across the project's environments). Past that, the person still gets
exactly the same answer, but `spaceboy mail log` shows one summary line per
environment per hour (`auth_refusals_not_logged`, with the count) instead of
a line per attempt. Members and test addresses are never affected.

### Telling development from production in the web app

Every deploy builds the web app with `VITE_DEPLOY_TARGET` set to
`development` or `production` (from the environment, never from a project
variable). Use it to word development-only messages instead of guessing from
the host name:

```ts
const isDevelopment = import.meta.env.VITE_DEPLOY_TARGET === "development"
```

It is unset in a local run, and in a client-only site whose bundle comes
from the pre-built template cache (such a site has no sign-in); treat unset
as "not known".

### Mail modes

Each environment has a mail mode (`spaceboy mail mode` shows the one in
force, `spaceboy mail mode held|redirect|live` sets it):

| Mode | App mail (welcome, receipts …) | Sign-in codes |
| --- | --- | --- |
| `held` | Kept in the log; nothing leaves | Development: held too (nothing leaves). Production: still sent, so people can sign in |
| `redirect` (development default) | Sent to one organisation member (default: the environment's owner) | Sent to the address asked for (members only while unpublished) |
| `live` (needs a verified mail domain) | Sent to its recipients | Sent to the address asked for |

Production defaults to `held`. Whatever the mode, a held or refused message
is in `spaceboy mail log` with a machine-readable `reason`.

### Test users on development

Sign-in mail to a reserved test address (`example.com`, `example.net`,
`example.org` and their subdomains, or a `.test`, `.invalid` or
`.localhost` domain) is never mailed. On a development environment the
platform keeps its code in the environment's test inbox for 15 minutes,
shown once (reading it deletes it), so an agent can sign in as any number
of users through the app's real sign-in:

```bash
spaceboy app signin --email rider@example.com --send-code    # reads the code and signs in
spaceboy app request --email rider@example.com --query '{ currentUser { id } }'
spaceboy mail test-inbox --email driver@example.com --json   # the code, for a browser sign-in
```

Only members of the project's organisation can read the test inbox, through
the authenticated CLI, under the same rules as test sessions: an owner or
admin can turn both off (`spaceboy app test-sessions disable`); a code for a
staff address (a persona with the `operator` role, or an address in the
app's `OPERATOR_EMAILS`) needs an organisation owner or admin; and every
code kept and every read is in the audit log. Production refuses test addresses (reason
`test_address_on_production`) and keeps no codes. Real people signing in to
an unpublished project's development app must be members of your
organisation; publish the project to let anyone sign in.

## How server code knows who is calling

Every GraphQL request carries the user's token; the server verifies it and
attaches a **principal** to the request context before any resolver runs.
Anonymous requests are rejected, except fields on an explicit public
allowlist.

```ts
// firebase/functions/src/Utils/Principal.ts
interface Principal {
    authSubject: string // the sign-in identity
    email: string
    userId?: string     // the app user (usr_...)
    accountId?: string  // that user's organization in your app
}
```

A resolver reads `context.principal` and passes `userId` to a service,
which checks access to the row:

```ts
static async notes(_parent: unknown, _args: unknown, context: GraphqlRequestContext) {
    const userId = context.principal?.userId
    if (userId === undefined) throw new RpcError("UNAUTHENTICATED", "Sign in first.")
    return noteService.listNotesForUser({ actingUserId: userId })
}
```

The sign-in service creates (or links) the app user, with an organization
(an `Account`), before it issues the first token, so `userId` and
`accountId` are set for every signed-in user. Per-row checks belong in services, not resolvers (starter
doc `docs/authorization.md`).

## How the web app knows who is signed in

```graphql
query CurrentUser { currentUser { id email displayName account { id name } } }
```

The starter generates a hook for it (`useCurrentUserQuery` from
`web/app/src/generated/graphql/types`); `runtime.authClient` signs in and
out.

## Verifying the deployed app behind sign-in

After every `spaceboy push`, run:

```bash
spaceboy app verify
```

It runs the smoke steps in the project's `spaceboy.verify.json` against the
deployed development app, signing in as the **test personas** declared
there (no email, no inbox), prints PASS/FAIL per step (`--json` for the
report) and exits `0` when every step passed, `1` when one failed, `2` when
the file is invalid. Add a step for each feature you build:

```json
{
    "personas": {
        "manager": { "displayName": "Test Manager", "roles": ["manager"] }
    },
    "steps": [
        { "name": "home page", "http": { "base": "site", "path": "/" }, "expect": { "status": 200 } },
        {
            "name": "anonymous callers are refused",
            "graphql": { "query": "{ currentUser { id } }" },
            "expect": { "errorCode": "UNAUTHENTICATED" }
        },
        {
            "name": "a manager lists the team",
            "as": "manager",
            "graphql": { "query": "{ team { members { id } } }" },
            "expect": { "json": { "data.team.members": { "minLength": 1 } } }
        }
    ]
}
```

- A step is `http` (`base` `site` for the web app or `functions` for the
  API functions, a `path`, `GET` or `HEAD`) or `graphql` (`query`,
  `variables`). `as` signs in as a declared persona first.
- `expect`: `status`, `errorCode` (the GraphQL error code), `noErrors`
  (default true unless `errorCode`), `bodyIncludes`, and `json`: dot paths
  (`data.items.0.id`) mapped to a value or one matcher (`exists`, `equals`,
  `contains`, `endsWith`, `type`, `minLength`).
- `--step <text>` runs only matching steps; `--env prod` runs against
  production (below).

### Test personas

A persona signs in as `<persona>@<deploy-slug>.dev.spaceboy.test`: a
reserved address that never receives mail and that the app's real sign-in
refuses. Personas are what the **committed** `spaceboy.verify.json` declares:
the platform records them at each `spaceboy push`, and mints a 15-minute
**test session** only for a recorded persona, with exactly its declared
roles (development only; audited). Change a persona or its roles by
committing the file and pushing. Any member of the project can sign in as an
ordinary persona; a persona with the role `operator` (an app operator) needs
an organisation owner or admin.

The starter gives each persona its own app user, marked as a test persona
and left out of user lists and counts. The app decides what the roles mean
in `firebase/functions/src/Services/Identity/TestPersonaSeed.ts`, for
example by making the persona a member of a demo team. A test session cannot
set a password or a second factor, the app never emails a persona, and every
request it makes is logged as `auth.test_session`.

```bash
spaceboy app personas reset                     # delete persona users (and their data, per the seed)
spaceboy app test-sessions disable              # owners and admins: stop minting for development
spaceboy app test-sessions enable
```

For one-off calls:

```bash
spaceboy app signin --persona manager            # prints a 15-minute token
spaceboy app request --persona manager --query '{ currentUser { id email } }'
spaceboy app request --query @query.graphql --variables '{"first":10}'
```

Without `--persona`, `app request` uses the persona `test-user` (no roles).
Apps on a starter older than test personas accept the session but give it
no app user; `spaceboy kernel upgrade` fixes that.

### Production

There are no test sessions on production: the platform refuses to mint
one and the starter refuses one on a production deploy. `spaceboy app
verify` decides production from the environment's real mode, whatever
`--env` says. On production it runs only the steps without `as` that are a
single GraphQL query or an HTTP GET/HEAD, and reports the rest as skipped.
To check production behind sign-in, the app's owner signs in.

`app verify` never follows redirects or talks to other hosts, and a failing
step names the status and the expectation, never the value the app
returned.

### Never

- Read sign-in codes, tokens or password hashes from the app's database to
  get in.
- Set `AUTH_DEV_CODE` or change sign-in to get in.
- Sign in as a real person's address. The platform refuses to mint a test
  session for any address outside the reserved test domain.

Sign in through the app's own emailed code from the terminal: on
development, `spaceboy app signin --email rider@example.com --send-code`
signs in as a test user in one step (see "Test users on development"); with
a real mailbox you read, `--send-code` emails the code and you finish with
`--code <code>`. `app request` then runs as that user until `spaceboy app
signout`.

## Not available from the CLI

- Listing, inviting, disabling or deleting app users (use `spaceboy db query`
  against the environment's database to inspect them).
- Switching sign-in methods live, editing sign-in emails, and connecting
  Google or Apple sign-in: these are dashboard settings.
