SkybuDocs

Ferdigheter · Oppskrifter

Add sign-in to an app

Give an app sign-up and sign-in with Better Auth, with users and sessions in the project's own Postgres, or put members-only sign-in in front of it with no code.

skill://playbooks/add-loginAgenter leser den med resources/read eller skills_read. Den er skrevet på engelsk, for agentene.

There are two ways to make people sign in to an app on Skybu. When only the organisation's own staff use it, Skybu's gateway can sign them in with their organisation accounts, and the app needs no login code. When anyone else signs in (customers, citizens, partners), the app runs Better Auth itself and keeps users and sessions in the project's own Postgres database, in Norway, next to the rest of its data.

In short

  1. Ask the user who signs in, and pick members-only or Better Auth (table below).
  2. For Better Auth: install it, write src/auth.ts, generate its tables into the Drizzle schema and migrate them as app_owner after a restore point. This needs the database setup from skill://playbooks/app-with-a-database.
  3. Set BETTER_AUTH_SECRET with set_env_vars, write-only.
  4. Mount /api/auth/*, check the session on every protected route, and add sign-up and sign-in forms.
  5. Raise the data class to at least personal, deploy, and sign up once to test.

Step 1: which kind of sign-in

Who signs inUseCode in the app
Only members of the organisation (staff), every pageMembers-only, skill://access/members-only-appsNone. An owner turns it on.
Only members (and invited guests), with public pages or webhooks tooSign in with your organisation, skill://access/sign-in-with-your-organisationAn OpenID Connect client.
Anyone with an email addressBetter Auth, belowYes
Staff and outsidersBetter AuthYes

Members-only stops everyone who is not a member, webhooks included, and gives the app the person's email and name in headers. You can check it with get_app_access, but only an owner can change it (set_app_access). A few people from outside can be let in as guests (skill://access/guests-and-groups), but that is for partners and consultants, not for customers. If the user is unsure, ask whether anyone outside the organisation will ever need to sign in.

Do not use Clerk, Auth0, Supabase Auth, Firebase Authentication or another hosted login service unless the user asks for it after hearing why not. They store every user's email, password hash and sign-in history with a US vendor, which defeats hosting the app and its data in Norway. Skybu's own sign-in is for the organisation's members and invited guests only; for everyone else, Better Auth runs inside the app instead.

Step 2: Better Auth and its tables

This builds on the app from skill://playbooks/app-with-a-database: src/db.ts exports a Drizzle db created with the schema, and src/migrate.ts migrates where DATABASE_URL_DIRECT is set.

npm install better-auth@1.7.14

src/auth.ts, with email and password on:

import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { db } from "./db.ts";

const onSkybu = Boolean(process.env.SKYBU_DEPLOYMENT);

export const auth = betterAuth({
  secret: process.env.BETTER_AUTH_SECRET,
  baseURL: {
    allowedHosts: ["notater.acme.skybu.app", "notater-pr-*.acme.skybu.app", "localhost:8080"],
    protocol: onSkybu ? "https" : "http",
  },
  database: drizzleAdapter(db, { provider: "pg" }),
  emailAndPassword: {
    enabled: true,
    sendResetPassword: async ({ user, url }) => {
      if (onSkybu) throw new Error("No email sender is set up for password reset");
      console.log(`Password reset for ${user.email}: ${url}`);
    },
  },
});
  • allowedHosts lists the app's address, https://<app>.<org>.skybu.app, and its previews, <app>-pr-<n>.<org>.skybu.app. Add custom domains here too (skill://domains/custom-domain). Better Auth builds its links and trusts origins from this list.
  • Skybu sets SKYBU_DEPLOYMENT on every app, so its absence means the app runs on a developer's machine. Skybu ends TLS before the app, so the protocol must be set to https there, not read from the request.
  • The adapter finds its tables in the schema db was created with, once they are generated:
npx auth@1.7.14 generate --config src/auth.ts --output src/db/auth-schema.ts --yes

Add export * from "./auth-schema.ts"; to src/db/schema.ts, then generate the migration with npm run generate. It creates user, session, account and verification. Mark a restore point and run the migration through the tunnel as app_owner, exactly as in skill://playbooks/app-with-a-database Step 8. Previews create the tables themselves at start.

Step 3: the secret

The app must exist before it can have variables. If it does not yet, deploy it once without sign-in first. Then generate a secret (openssl rand -base64 32) and set it for production and previews separately:

{
  "name": "set_env_vars",
  "arguments": { "appId": "<app id>", "variables": { "BETTER_AUTH_SECRET": "<32 random bytes, base64>" }, "environment": "production", "sensitive": true }
}

Call it again with "environment": "preview" and a different value. sensitive makes it write-only: nobody can read it back. Never run the app without it. Changing it later signs everyone out. See skill://apps/environment-variables.

Step 4: routes and forms

With node:http, hand /api/auth/* to Better Auth and check the session everywhere else:

import { createServer } from "node:http";
import { fromNodeHeaders, toNodeHandler } from "better-auth/node";
import { auth } from "./auth.ts";

const authHandler = toNodeHandler(auth);

createServer(async (req, res) => {
  if (req.url?.startsWith("/api/auth/")) return authHandler(req, res);
  const session = await auth.api.getSession({ headers: fromNodeHeaders(req.headers) });
  if (!session) return res.writeHead(401).end("Sign in first");
  res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ id: session.user.id, email: session.user.email }));
}).listen(Number(process.env.PORT ?? 8080));

In Next.js (App Router), app/api/auth/[...all]/route.ts is export const { GET, POST } = toNextJsHandler(auth); with toNextJsHandler from better-auth/next-js. In Express, mount toNodeHandler(auth) before express.json(), which would otherwise consume the body.

In the browser:

import { createAuthClient } from "better-auth/client";

const authClient = createAuthClient();

await authClient.signUp.email({ email, password, name });
await authClient.signIn.email({ email, password });
await authClient.signOut();

React apps import createAuthClient from better-auth/react and get authClient.useSession().

Use session.user.id as the owner of the user's rows, and filter every query by it on the server. The browser never decides whose data it gets.

Step 5: data class and test

An app with accounts stores names and email addresses, so its data class is at least personal. Ask the user, and change it if needed:

{ "name": "update_app_details", "arguments": { "appId": "<app id>", "dataClass": "personal" } }

Deploy (skill://apps/deploy-an-app), sign up once on the address, and check that the account exists without reading it:

{ "name": "query_database", "arguments": { "databaseId": "<database id>", "sql": "select count(*) from \"user\"" } }

Errors show in get_app_logs. relation "user" does not exist means the migration has not run in that database.

Password reset and email

Reset links, email verification and magic links need a transactional email sender. Skybu has not chosen one to recommend yet, so ask the user which sender they use, and prefer one that keeps data in Europe. Until there is one, the code above logs reset links on a developer's machine and refuses on Skybu. Never log reset links in production: anyone who can read the app's log could take over the account. If the organisation limits outbound traffic, the sender's host must be on the list (skill://access/outbound-traffic).

Vipps and BankID (add-ons, untested)

Better Auth has no built-in Vipps provider. Vipps Login is an OpenID Connect provider, so it can be added with Better Auth's generic OAuth plugin. This has not been tested end to end on Skybu; tell the user so, and test it against Vipps' test environment first. The customer needs their own Vipps agreement and keys.

import { genericOAuth } from "better-auth/plugins/generic-oauth";

plugins: [
  genericOAuth({
    config: [{
      providerId: "vipps",
      discoveryUrl: process.env.VIPPS_DISCOVERY_URL!,
      clientId: process.env.VIPPS_CLIENT_ID!,
      clientSecret: process.env.VIPPS_CLIENT_SECRET!,
      scopes: ["openid", "name", "email"],
    }],
  }),
],

Take the discovery URL and scopes from Vipps' Login API documentation; test and production differ. Register https://<app address>/api/auth/callback/vipps as the redirect URI at Vipps, and sign in with authClient.signIn.social({ provider: "vipps" }). Store the client secret with sensitive: true.

BankID goes the same way through an identity broker that speaks OpenID Connect; it is documented, not pre-wired. Both need outbound access to the provider's hosts when the organisation limits outbound traffic.

Things to know

  • Users, sessions and password hashes (scrypt) live in the project's database, so the database's backups and restore points cover them, and query_database hides them unless someone tags the columns.
  • Members-only and Better Auth do not combine well: members-only keeps out everyone who is not a member before Better Auth sees them.
  • Do not trust x-skybu-user-email in an app that uses Better Auth on a public address; anyone can send that header.
  • Moving users from Supabase Auth keeps their passwords: see skill://playbooks/leave-supabase.