phibac developer docs

Sign users in

What you will do

You will add a Sign in button that signs the user in with connect(), handle the ways sign-in can fail, register the web addresses your app runs from, and add a Sign out button.

A few words used on this page:

  • An app is the web app you build. A user is the person who uses it and whose data it saves.
  • The SDK (@phibac/sdk) is the JavaScript library your page uses to talk to the phibac server.
  • Users sign in to phibac with a passkey (a key kept on their device and unlocked with the device's screen lock, fingerprint or face) or with their email address and a password. Your app never sees either: both are used only on the server's own page. A password sign-in in a browser the user has not used before also asks for a short code sent to their email address, unless they ticked "Remember this browser" there earlier.
  • Consent is the user's approval for your app to store data for them. They give it once, the first time they sign in to your app.
  • An origin is the start of a web address: http or https, the host name and the port, such as https://notes.example.com or http://localhost:5173. Paths are not part of it.

Before you start

You need an app created with npx phibac init, the local server running (npx phibac dev) and a page served by Vite on the origin you registered, as in steps 1 to 4 and 9 of Build your first app. This guide uses the quickstart's address, http://localhost:5173, and the local server, http://localhost:8787.

Steps

1. Register every origin your app runs from

The server lets an app sign users in only from origins registered for it. npx phibac init --origin registers the first one. The rules:

  • Use https. Plain http is accepted only on localhost, 127.0.0.1 and [::1], for development.
  • Give the origin only: no path, query or trailing parts.
  • An app can have at most 20 origins.

To change the list later, send the whole new list to the developer API with your developer token (the pbd_ key in PB_TOKEN). It replaces the old list, so include every origin you still use:

curl -X PATCH http://localhost:8787/v1/apps/app_... \
  -H "Authorization: Bearer $PB_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"origins": ["http://localhost:5173", "https://notes.example.com"]}'

The answer is the app with its new list of origins. An AI coding tool connected to the server can do the same with its update_app_origins tool.

On the local server, the apps that npx phibac init made belong to the server's built-in account, not to yours, so a token from your own account gets forbidden for them. Use the local server's own key instead: run the same command with $(cat ./.pb/developer-token) in place of $PB_TOKEN, in the folder you start npx phibac dev from. The shell sends the key without printing it. Or start again with a fresh ./.pb (Develop on your own machine). An unregistered http://localhost origin also works while you develop, but asks for approval at every sign-in, as the next paragraph explains.

While you develop, a page on http://localhost with any port can sign in even if that origin is not registered. In that case the server asks the user to approve your app at every sign-in, naming the origin, because any program on the user's computer can serve a page from localhost. Register the exact http://localhost:<port> you use and this extra question goes away. 127.0.0.1 is a different origin from localhost and gets no such exception: register it if you use it.

2. Add the buttons

Create index.html:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Notes</title>
  </head>
  <body>
    <button type="button" id="sign-in">Sign in</button>
    <button type="button" id="sign-out" hidden>Sign out</button>
    <p id="message" role="alert"></p>
    <script type="module" src="/src/main.ts"></script>
  </body>
</html>

3. Call connect() from the click

Create src/main.ts, with your app ID in place of app_...:

import { connect, PbError, type Backend } from "@phibac/sdk";

const APP = "app_...";
const BASE_URL = "http://localhost:8787";

const signIn = document.querySelector<HTMLButtonElement>("#sign-in")!;
const signOut = document.querySelector<HTMLButtonElement>("#sign-out")!;
const message = document.querySelector<HTMLParagraphElement>("#message")!;

let backend: Backend | null = null;

function signedIn(b: Backend): void {
  backend = b;
  signIn.hidden = true;
  signOut.hidden = false;
  message.textContent = "Signed in.";
}

// Explains why sign-in failed. textContent shows text as typed: it never runs it as HTML.
function showError(e: unknown): void {
  if (!(e instanceof PbError)) {
    message.textContent = String(e);
  } else if (e.code === "popup_blocked") {
    message.textContent = "Your browser blocked the sign-in window. Allow pop-ups for this site and press Sign in again.";
  } else if (e.code === "sign_in_cancelled") {
    message.textContent = "Sign-in was not finished. Press Sign in to try again.";
  } else if (e.code === "access_denied") {
    message.textContent = "You did not allow this app. Press Sign in if you change your mind.";
  } else {
    message.textContent = `${e.code}: ${e.message}`;
  }
}

// Call connect() straight from the click, before any await: browsers allow a pop-up only then.
signIn.addEventListener("click", async () => {
  try {
    signedIn(await connect({ app: APP, baseUrl: BASE_URL }));
  } catch (e) {
    showError(e);
  }
});

signOut.addEventListener("click", async () => {
  if (backend === null) return;
  const waiting = backend.status().pending;
  if (waiting > 0 && !confirm(`${waiting} change(s) have not reached the server yet and will be lost. Sign out anyway?`)) return;
  await backend.signOut();
  backend = null;
  signIn.hidden = false;
  signOut.hidden = true;
  message.textContent = "Signed out.";
});

// On page load, pick up a sign-in stored in this browser. Without one this fails
// with popup_blocked, because no click opened the page: then the user presses Sign in.
connect({ app: APP, baseUrl: BASE_URL }).then(signedIn, (e: unknown) => {
  if (!(e instanceof PbError && e.code === "popup_blocked")) showError(e);
});

What connect() does:

  • When the user has not signed in to your app in this browser, it opens a popup on the server (here the local server, http://localhost:8787). There the user signs in, with their passkey or their password, if they are not signed in to the server yet, and approves your app the first time. The popup then closes and connect() returns the user's backend, the object your app reads and writes their data through.
  • Browsers allow a popup only as a direct result of a click or key press. connect() opens its popup at once for that reason, so call it first in the click handler, not after an await and not from a timer. Called anywhere else, it cannot open the popup and fails with popup_blocked.
  • When a sign-in is already stored in this browser, connect() shows no sign-in page and needs no network: it returns at once, even offline. Inside a click, a blank window may flash open and close at once, because connect() opens it before it has checked for a stored sign-in. Outside a click, as in the page-load call in the last lines of the file, connect() does not try to open a window in browsers that report whether a click is in progress, and other browsers usually block the window it tries to open. A stored sign-in still works; without one, when no window opened, connect() fails with popup_blocked. In a browser of the second kind where the user has allowed popups for your site, the window opens and sign-in goes ahead as from a click.

SDK reference lists every option of connect() and every way it can fail.

4. Sign out

backend.signOut() signs the user out of your app in this browser: it deletes the stored sign-in, the user's copy of your app's data in this browser and any changes still waiting to be sent. Those waiting changes are lost, which is why the file above checks backend.status().pending first and asks. After signOut() the backend cannot be used; calls on it fail with unauthorized. Call connect() again from a click to sign in.

Signing out of your app does not sign the user out of the phibac server in this browser. The next time they press Sign in, the popup may close by itself without asking anything. To end their session on the server, the user signs out in their account area on the server (http://localhost:8787/account for the local server).

5. Know what is kept in the browser

The SDK keeps everything in the browser's IndexedDB storage, and nothing in localStorage, sessionStorage or cookies on your origin:

  • The sign-in, one per server and app: a token that lets the SDK get new short-lived access (the refresh token), and the user's ID. The access itself (the access token) is held only in memory and lasts 15 minutes; the SDK renews it by itself.
  • A private key for each server, made by the browser. Every request is signed with it, so a stolen token is useless on another device. The browser can sign with the key but never reveal it, not even to your page's code.
  • A copy of the user's data for your app, and the changes still waiting to be sent, so your app works offline (see Offline writes and sync).

The stored sign-in is renewed as your app uses the server. One left unused for 30 days expires: requests then fail with unauthorized, and the user signs in again from a click. Your app is never given the user's email address, passkey or password. How sign-in works explains each of these in detail.

What you should see

  1. Open http://localhost:5173. The page shows Sign in. The first time, the message stays empty: no sign-in is stored yet.
  2. Press Sign in. A popup from the server opens, asks you to sign in if you are not signed in to the server, then shows "Notes (http://localhost:5173) will store data in your backend." with Allow and Cancel. Press Allow. The popup closes and the page says "Signed in.".
  3. Reload the page. It says "Signed in." without any popup: the stored sign-in was found.
  4. Press Sign out, then Sign in again. The popup opens and closes by itself, because you are still signed in to the server and have already approved the app.

Common problems

  • popup_blocked. The browser did not open the sign-in popup. Call connect() directly in a click or key handler, before any await. If it still happens, the browser blocks popups for your site: allow them in the browser's settings.
  • sign_in_cancelled. The popup was closed before sign-in finished. Let the user press Sign in again.
  • access_denied. The user pressed Cancel on the consent page. Show your app without their data and let them try again.
  • The popup says "The app asked to sign in from an address it has not registered." The page's origin is not registered for the app and is not http://localhost. Register it as in step 1. When the user closes the popup, connect() fails with sign_in_cancelled.
  • The popup says "This app is not registered." The app ID passed to connect() is wrong, or the app was created on another server. Check app and baseUrl.
  • The user is asked to approve the app at every sign-in. The page runs on an http://localhost origin that is not registered. Register that exact origin, port included.
  • Requests fail with forbidden saying the app "may not be used from origin". The page's origin is not registered for the app. Register it, or use http://localhost while you develop.
  • Requests fail with unauthorized. The user signed out, or the stored sign-in expired or was ended (for example, the user disconnected your app in their account area). Show Sign in and call connect() again from a click.
  • app_suspended. The server's operator suspended your app. Nothing in your page can fix it; contact the operator.

Next step

Read and write records uses the signed-in backend to create, read, change and delete the user's notes.