toiljs 0.0.132 → 0.0.134
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/build/backend/security.js +4 -2
- package/build/cli/index.js +9 -9
- package/build/client/auth.d.ts +14 -0
- package/build/client/auth.js +31 -4
- package/build/client/components/GoogleSignIn.d.ts +8 -0
- package/build/client/components/GoogleSignIn.js +57 -0
- package/build/client/index.d.ts +3 -1
- package/build/client/index.js +2 -1
- package/build/compiler/config.d.ts +3 -1
- package/build/compiler/config.js +3 -0
- package/build/compiler/security.d.ts +4 -3
- package/build/compiler/security.js +8 -7
- package/build/compiler/sri.js +2 -2
- package/build/compiler/toil-docs.generated.js +3 -1
- package/build/compiler/vite.js +1 -1
- package/build/devserver/http/runtime.d.ts +1 -1
- package/build/devserver/http/runtime.js +5 -5
- package/build/devserver/production.js +3 -3
- package/build/devserver/runtime/base64.d.ts +2 -0
- package/build/devserver/runtime/base64.js +39 -0
- package/build/devserver/runtime/crypto.d.ts +1 -1
- package/build/devserver/runtime/crypto.js +24 -0
- package/build/devserver/runtime/google.d.ts +9 -0
- package/build/devserver/runtime/google.js +157 -0
- package/build/devserver/runtime/host.js +6 -0
- package/build/devserver/runtime/module.d.ts +2 -0
- package/build/devserver/runtime/module.js +19 -0
- package/build/shared/index.d.ts +2 -1
- package/build/shared/index.js +1 -1
- package/build/shared/security.d.ts +4 -2
- package/build/shared/security.js +6 -2
- package/examples/basic/client/routes/google-login.tsx +132 -0
- package/package.json +19 -19
- package/server/auth/AuthController.ts +201 -61
- package/server/auth/AuthMaintenance.ts +1 -1
- package/server/auth/AuthRealm.ts +22 -0
- package/server/auth/AuthStateDb.ts +14 -0
- package/server/auth/AuthStore.ts +4 -0
- package/server/auth/Authenticator.ts +93 -0
- package/server/auth/FactorSettings.ts +9 -8
- package/server/auth/GoogleIdentity.ts +63 -0
- package/server/auth/SessionEpochs.ts +54 -12
- package/server/globals/auth.ts +51 -20
- package/server/runtime/envelope.ts +9 -7
- package/server/runtime/http/base64.ts +18 -98
- package/server/runtime/http/percent.ts +4 -0
- package/server/runtime/http/securecookies.ts +1 -1
- package/server/runtime/request.ts +3 -0
- package/std/server/http/base64.d.ts +2 -18
- package/std/server/http/securecookies.d.ts +1 -1
- package/std/server/request.d.ts +3 -0
|
@@ -3,9 +3,11 @@ export const TOIL_DOCS = {
|
|
|
3
3
|
"auth/configuration.md": "# Configuring auth for production\n\nBuilt-in auth runs locally with **zero configuration**, it falls back to published, insecure DEV secrets\nso `toiljs dev` Just Works. **A deployment MUST replace all three secrets and pin its KEM key.** This page\nis the checklist.\n\n## The secrets\n\nAuth reads these from the tenant environment store (locally, `.env.secrets`; on the edge, the per-host\nsecure env). They resolve **lazily** the first time auth runs, so no startup wiring is needed.\n\n| Key | What it is | Dev fallback |\n| --- | --- | --- |\n| `AUTH_SESSION_SECRET` | HMAC-SHA256 key that signs the session cookie. Must be identical on every edge instance (a cookie minted anywhere must verify everywhere). | a public constant, **anyone can forge a session** |\n| `AUTH_OPRF_SEED` | Master seed for the per-user OPRF salt key. Rotating it invalidates every password (users must re-register). | a hashed public constant |\n| `AUTH_KEM_SK` | The server's ML-KEM-768 **secret** key (hex). Its public half is what the client encapsulates to. | a pinned dev key pair |\n\n```bash\n# .env.secrets (gitignored; mode 0600 on the edge, NEVER under hosts/, NEVER in the .wasm)\nAUTH_SESSION_SECRET=…64 hex chars (32 bytes)…\nAUTH_OPRF_SEED=…64 hex chars (32 bytes)…\nAUTH_KEM_SK=…hex of an ML-KEM-768 secret key…\n```\n\n### Generating them\n\nRun this from your project root (or pass `--root <dir>`):\n\n```bash\ntoiljs generate auth\n```\n\nThe command saves `AUTH_SESSION_SECRET`, `AUTH_OPRF_SEED`, and `AUTH_KEM_SK` in\n`.env.secrets` with mode `0600`, and the matching `VITE_AUTH_KEM_PUBLIC_KEY` in `.env`.\nIt adds both files to `.gitignore`, preserves unrelated settings, and does not print credentials.\nRerunning preserves existing keys and restores a missing public key from `AUTH_KEM_SK`.\nInvalid, empty, or mismatched existing credentials cause an error without changing the env files.\nThere is no automatic rotation: changing the OPRF seed invalidates passwords, and changing the\nsession secret invalidates sessions. Back up the private file securely.\n\nFor toil-backend, merge the private settings into `/run/toil/env/<host>.env.secrets`\n(or the directory selected by `TOIL_ENV_DIR`). If using database-backed env settings, run\n`toil env sync <host>` with the production configuration after editing the files.\nThe **public** key must also be present in the project `.env` on the machine running the frontend\nbuild. Backend runtime env files do not supply Vite's build-time variables. Rebuild and deploy\nthe client with its matching key; the command does not edit your client code or deploy anything.\n\nTo generate keys manually instead:\n\n`AUTH_SESSION_SECRET` and `AUTH_OPRF_SEED` are just 32 random bytes each:\n\n```bash\nnode -e \"console.log(require('crypto').randomBytes(32).toString('hex'))\"\n```\n\n`AUTH_KEM_SK` is an ML-KEM-768 key pair. Generate it and keep BOTH halves, the secret goes in the env, the\npublic half is pinned in the client (next section):\n\n```ts\nimport { ml_kem768 } from '@dacely/noble-post-quantum/ml-kem';\nconst { secretKey, publicKey } = ml_kem768.keygen();\nconsole.log('AUTH_KEM_SK =', Buffer.from(secretKey).toString('hex'));\nconsole.log('client serverKemPublicKey =', Buffer.from(publicKey).toString('hex'));\n```\n\n## Pin the client's KEM public key\n\nThe browser must know the server's genuine KEM public key to run the mutual-auth handshake, this is the\nanti-phishing anchor. The `toiljs/client` `Auth` helper ships with the **dev** key pinned, so a deployment\nMUST pass its own:\n\n```ts\nimport { Auth } from 'toiljs/client';\n\n// Set by `toiljs generate auth` in the project .env, embedded during the client build.\nconst hex = import.meta.env.VITE_AUTH_KEM_PUBLIC_KEY;\nif (!hex || !/^[0-9a-f]{2368}$/.test(hex)) throw new Error('Missing auth public key');\nconst SERVER_KEM_PUBLIC_KEY = Uint8Array.from(hex.match(/../g)!, byte => parseInt(byte, 16));\n\nawait Auth.login(username, password, { serverKemPublicKey: SERVER_KEM_PUBLIC_KEY });\nawait Auth.register(username, password, { serverKemPublicKey: SERVER_KEM_PUBLIC_KEY });\n```\n\nShip the public key with your client bundle (it's public, safe to embed). If it doesn't match the server's\n`AUTH_KEM_SK`, login's `serverConfirm` check fails and the client aborts.\n\n## Optional: audience & domain\n\nBoth are optional and have sensible defaults; set them for stability across host aliases:\n\n| Key | Meaning | Default |\n| --- | --- | --- |\n| `TOIL_AUTH_AUDIENCE` | The service audience bound into the signed login message. | `\"toil\"` |\n| `TOIL_AUTH_DOMAIN` | The `domain` field in the [stable `ToilUserId` derivation](./how-it-works.md#the-stable-user-identity-toiluserid): SHA-256 over the length-prefixed `toil.userid.v1` label, ML-DSA public key, username, and domain. | the request `Host` header, else `localhost` |\n\nSet `TOIL_AUTH_DOMAIN` explicitly if your site answers on multiple hostnames, otherwise the same user could\nget different `ToilUserId`s from different aliases. Once users exist, changing it changes everyone's id, so\npick it before launch.\n\n## Email confirmation\n\nTwo plain env vars (tenant-readable, like `PUBLIC_BASE_URL`) control the built-in email-verification flow. They are separate on purpose: sending a verify email at registration is one decision, blocking login until confirmed is another.\n\n| Key | What it does |\n| --- | --- |\n| `AUTH_EMAIL_CONFIRMATION` | Registration emails a one-time confirm link (`/confirm#token=…`) and stores the account **unconfirmed**. Login is **not** blocked: the user can sign in, and you nudge them to verify. Use this for \"verify at signup, but let people in\". |\n| `AUTH_REQUIRE_EMAIL_CONFIRMATION` | The stricter form: does everything above AND **refuses login** until the email is confirmed (a distinguishable status the client surfaces as `EmailNotConfirmedError`, so the UI can prompt \"confirm your email / resend\"). Implies `AUTH_EMAIL_CONFIRMATION`. On the managed edge this is force-set from the per-domain Dacely setting. |\n\nWith neither set, accounts are auto-confirmed at registration and no confirm email is sent. The one-time link is delivered by email; in `toiljs dev` it is drawn in the console (no mailer needed). Both use the standard non-enumerating responses (a generic 200 that never reveals whether an address exists).\n\n## Argon2id strength (known limitation)\n\nThe built-in controller currently uses **demo-light** Argon2id params (32 MiB, 2 iterations, 1 lane) so it\nstays responsive in a browser tab. These are baked into the shipped controller today; **config-driven\ntuning is a planned follow-up.** For a high-value production deployment you should either wait for the\nconfig knob or hand-write your own controller with `≥ 256 MiB / ≥ 3 iterations`. The OPRF still provides the\nprimary offline-attack resistance regardless, but raise these before protecting anything sensitive.\n\nThe client always derives against whatever params the server returns in `/login/start`, so when the config\nknob lands you can raise them server-side with **no client change**.\n\n## Deploy checklist\n\n- [ ] `AUTH_SESSION_SECRET` set (32 random bytes), identical on every edge instance.\n- [ ] `AUTH_OPRF_SEED` set (32 random bytes).\n- [ ] `AUTH_KEM_SK` set (an ML-KEM-768 secret key), and its **public** half pinned in the client via\n `serverKemPublicKey`.\n- [ ] `TOIL_AUTH_DOMAIN` set if you serve multiple hostnames (stable `ToilUserId`).\n- [ ] (Recommended) Argon2id params reviewed for your threat model.\n\nThe CLI doctor warns when `server.auth` is on and the secrets are missing, run it before you ship.\n\n## Upgrading to 0.0.118\n\nLogin now requires `AuthOptions.serverKemPublicKey`, the 1184-byte public key matching\n`AUTH_KEM_SK`. There is no implicit fallback to the published development key. Keep\nexisting OPRF and KEM secrets when upgrading; replacing the OPRF seed invalidates\nexisting password credentials. Project-root `VITE_*` variables are loaded by default.\n\nSessions use a versioned signed payload with a random session identifier and a user\nrevocation generation. Pre-upgrade session cookies and pending login challenges are\nrejected, so users must sign in again. Single-session logout revokes the signed session;\n`POST /auth/logout-all`, password reset, and confirmed two-factor changes revoke all\nsessions. Two-factor changes require a fresh login after success. Existing account IDs\nremain stable after password reset. The compiler includes the new revocation and factor\nsettings database declarations automatically.\n\nAuthenticated factor operations accept `headers` and `onRequestFailed(status)` options\nfor application account guards. HTTP failures include their status in the client error.\n\n## Session lifetime\n\nSuccessful password and two-factor sign-ins issue sessions valid for seven days\n(604800 seconds). The signed expiry and both session/display cookie lifetimes\nmatch. This is a fixed lifetime from sign-in, not an idle timeout. Logout, password\nreset, and account revocation can end a session earlier. Existing cookies retain\nthe expiry they were issued with; sign in again to receive the longer lifetime.\n\n## Account deletion\n\n`await Auth.deleteAccount(options)` calls authenticated `POST /auth/delete`.\nIt releases the sign-in account's username and email, revokes all its sessions,\nand clears both browser cookies. Clean application-owned records and projections\nbefore calling it. The endpoint operates only on the authenticated user's account.\n\nDeletion marks the old account before cleanup and frees the username last.\nIf cleanup is interrupted, retry with the existing session. Registration also\nfinishes an interrupted deletion before claiming the username. Conditional\nwrites prevent an overlapping request from removing or modifying a replacement\naccount. Confirm/reset links and pending logins bind to an account incarnation;\nlinks issued before this upgrade are rejected and can be requested again.\nA re-registered account starts with fresh factor settings. Revocation epochs and opaque deletion-incarnation guards\nremain to reject copied cookies and delayed replays of old account rows; random login challenges expire and cannot\nbe redeemed against a replacement account.\n\nFor cleanup that spans background runs, finish deleting application-owned data,\nthen call `AuthService.deleteUser(id)` from a `@job`, passing a `ToilUserId`.\nIt uses the same account cleanup and session revocation as `/auth/delete`,\nwithout a signed-in request. Request Actions, Queries, and Derives are rejected.\nIt returns `true` after removing the account, or `false` if the ID is absent,\nits index is stale, or its account incarnation no longer owns that ID. Concurrent\nupdates and storage failures throw; retry them to resume deletion. A marked account\ncannot sign in while cleanup is incomplete. Permanent incarnation guards and\nsession epochs remain after deletion. The ID index removes the deleted account's\nusername/realm pointer after the account is removed, using a conditional update\nthat preserves pointers for replacement accounts.\n\nRegistration stores the ID index before activating the account; sign-in repairs\nmissing entries. Existing deployments should backfill their accounts from a Job\nbefore relying on ID deletion. `AuthService.indexUsers(limit = 8, cursor = null)`\nindexes at most eight accounts per invocation and returns the next cursor, or\n`null` at completion. Persist the cursor after a successful invocation and keep\ncalling even when a page indexes no accounts. Retry the same cursor on failure.\nThe scan requires a [complete local collection copy](../database/documents.md#background-collection-scans)\nand, for existing native data, the record-directory migration described there.\nAccounts predating stored stable IDs require the original `TOIL_AUTH_DOMAIN`\nvalue; the Job refuses to guess a historic request hostname or port. Accounts\nwith stored IDs do not require that setting.\n\nNormally an ID identifies one realm. If a deployment intentionally assigns the\nsame ID to accounts in multiple realms, pass the normalized realm as the second\nargument: `AuthService.deleteUser(id, 'example.com')`. Ambiguous lookups throw.\nThe index supports up to sixteen realms per ID. Account pointers include an\nincarnation so a delayed cleanup cannot remove a replacement with another ID.\nRe-registering with identical credentials and identity-domain inputs can reuse\nthe same stable ID; applications requiring a distinction between those lifetimes\nshould retain their own deletion generation.\n",
|
|
4
4
|
"auth/emails.md": "# Customizing the auth emails\n\nBuilt-in auth sends three transactional emails: the email-verification link, the password-reset link, and the two-factor code. Each ships with a plain, working default. You can replace any of them with your own branded template, and you never touch the auth code to do it.\n\n## The three emails\n\n| Email | When it sends | The value it gives your template |\n| --- | --- | --- |\n| Email verification | On register, when email confirmation is on | `link` (the confirm URL) |\n| Password reset | On `POST /auth/reset/request` | `link` (the reset URL) |\n| Two-factor code | On login or 2FA setup, for the email method | `code` (the numeric code) and `action` (the flow phrase) |\n\nThe defaults are intentionally minimal so a fresh project sends real, correct mail with no setup. To match your brand, override them.\n\n## How to override\n\nDrop a React template in your project's `emails/` folder with the reserved name for that email. If the file exists, the build uses it; if not, the default stands. This is the same `emails/*.tsx` system you use for your own mail (see [Email](../services/email.md)), so you get full markup and inline CSS.\n\n| Reserved file | Overrides | Prop it must read |\n| --- | --- | --- |\n| `emails/auth-confirm.tsx` | Email verification | `link` |\n| `emails/auth-reset.tsx` | Password reset | `link` |\n| `emails/auth-2fa.tsx` | Two-factor code | `code`, `action` |\n\nEach template is a default-exported React component. Read the one prop it is given, and it becomes a `{{token}}` hole the edge fills per send. Reading any other prop renders empty, so the build warns you.\n\n```tsx\n// emails/auth-confirm.tsx -> overrides the email-verification message.\nexport const subject = 'Verify your Acme account';\n\nexport default function AuthConfirm({ link }: { link: string }) {\n return (\n <div style={{ fontFamily: 'system-ui', padding: 24 }}>\n <h1 style={{ color: '#cb9820' }}>Welcome to Acme</h1>\n <p>Tap below to verify your email and finish signing up.</p>\n <p>\n <a\n href={link}\n style={{ background: '#cb9820', color: '#fff', padding: '10px 18px', borderRadius: 8, textDecoration: 'none' }}\n >\n Verify my email\n </a>\n </p>\n <p style={{ color: '#666', fontSize: 13 }}>Or paste this link: {link}</p>\n </div>\n );\n}\n```\n\nThe reset template works the same way with the `link` prop.\n\n## The subject line\n\nFor verification and reset, set the subject with `export const subject = '...'`. Leave it out and the default subject is used (`Confirm your account`, `Reset your password`).\n\nThe two-factor email is different. It serves three flows (signing in, enabling 2FA, and turning 2FA off), so besides the `code` it also gets an `action` prop: the framework fills it with the flow phrase, `sign in`, `enable two-factor authentication`, or `turn off two-factor authentication`. Write it into a sentence like \"Enter this code to {action}.\" and the one template reads correctly for every flow. The subject is likewise set by the framework and stays contextual, so a `subject` export in this file is ignored.\n\n```tsx\n// emails/auth-2fa.tsx -> overrides the 2FA code message (subject is contextual).\nexport default function Auth2fa({ code, action }: { code: string; action: string }) {\n return (\n <div style={{ fontFamily: 'system-ui', padding: 24, textAlign: 'center' }}>\n <p>Your Acme verification code:</p>\n <p style={{ fontSize: 32, fontWeight: 700, letterSpacing: 6 }}>{code}</p>\n <p>Enter it to {action}.</p>\n <p style={{ color: '#666' }}>It expires in a few minutes.</p>\n </div>\n );\n}\n```\n\n## What you can and cannot put in\n\nEach template is rendered once, at build time, into a static string of HTML with your styles inlined, and the prop becomes a fill hole. So a fixed layout and inline styles work, but per-send logic does not: a `{items.map(...)}` or a conditional runs at build, not per email. For these three messages that is all you need, one link or one code.\n\nThe only values auth hands each template are the ones in the table above (`link`, or `code` plus `action` for 2FA). There is no user name, no app name, no expiry value. Write those into the template text directly.\n\nStyling rules are the same as any toiljs email: write inline `style={{ ... }}`, or import a stylesheet and its rules are inlined for you. A bare CSS import with no inlining has no effect in an email client. See [Email](../services/email.md) for the details.\n\n## Delivery stays safe\n\nYou cannot weaken the security of these flows by overriding a template. Every auth email is sent detached (fire-and-forget), so the response time never reveals whether an address maps to an account. That holds whether the message is the default or your override. Overriding only changes what the email looks like, never how it is sent.\n\n## Where the templates go\n\nThere is nothing to import and nothing to register. The build reads `emails/auth-*.tsx`, bakes the effective templates into the compiled server, and the auth controller sends them. Changing a template and rebuilding (or saving under `toiljs dev`) is all it takes.\n\n## Related\n\n- [Email](../services/email.md): the full `emails/*.tsx` system, `EmailService`, and `EmailTemplate`.\n- [Configuration](./configuration.md): the auth secrets and the email provider a deployment must set.\n- [Usage](./usage.md): enabling auth, the client API, and guarding routes.\n",
|
|
5
5
|
"auth/extending.md": "# Extending & integrating auth\n\nBuilt-in auth is deliberately opinionated so the common case is one line. This page covers the identity\nyou build ON, `ToilUserId`, and how to go beyond the defaults: keying your own data on a user, a custom\nuser shape, and hand-writing auth from the same primitives.\n\n## `ToilUserId`\n\nThe stable, tenant-scoped user identity is a 256-bit SHA-256 hash of four\nlength-prefixed fields: the `toil.userid.v1` label, ML-DSA public key, identifier\n(the built-in account username), and tenant domain. See the\n[exact derivation](./how-it-works.md#the-stable-user-identity-toiluserid).\nIt's a **global** (no import), like `crypto`.\n\n```ts\n// Read the current user's id in any handler (gate on hasSession(), see the null note below).\nconst id: ToilUserId = AuthService.userId()!;\n\n// Or derive one yourself.\nconst id2 = ToilUserId.derive(mldsaPublicKey, 'alice@example.com', 'acme.dacely.com');\n```\n\n| Member | Description |\n| --- | --- |\n| `ToilUserId.derive(pk, identifier, domain)` | Derive from an ML-DSA public key + email/username + tenant domain. Deterministic. |\n| `ToilUserId.fromBytes(b)` | Rebuild from a 32-byte digest (from `toBytes()` or storage). |\n| `toBytes(): Uint8Array` | The 32 identity bytes. |\n| `toHex(): string` | Lowercase 64-char hex, a convenient string key. |\n| `isZero(): bool` | True for the unset / anonymous id. |\n| `equals(other): bool` | Value equality. |\n| `a == b` / `a != b` | Overloaded value comparison, **O(1)** (four `u64` word compares, no byte loop, no allocation). |\n\n```ts\nconst a = ToilUserId.derive(pk, 'alice', 'acme.com');\nconst b = ToilUserId.derive(pk, 'alice', 'acme.com');\nconst c = ToilUserId.derive(pk, 'bob', 'acme.com');\na == b; // true, same inputs, same id\na != c; // true, different user\n```\n\n> **Null-check gotcha:** because `ToilUserId` overloads `==`, `AuthService.userId() == null` does NOT\n> type-check (`==` expects a `ToilUserId`). Gate with `AuthService.hasSession()` and then `userId()!`, or\n> compare with `getUser()` (a plain nullable). `===` is reference identity in AssemblyScript and is not\n> overloadable, use `==` for value equality.\n\n## Keying your own data on the user\n\n`toilUserId` is the right key for per-user data, it's stable across sessions/devices and opaque. Use the\nhex as a string key, or the bytes in a `@data` key class:\n\n```ts\n@data\nclass UserKey {\n id: Uint8Array = new Uint8Array(0); // toilUserId bytes\n constructor(id: Uint8Array = new Uint8Array(0)) { this.id = id; }\n}\n\n@data class Profile { displayName: string = ''; bio: string = ''; }\n\n@database\nclass AppDb {\n @collection static profiles: Documents<UserKey, Profile>;\n}\n\n@rest('profile')\nclass ProfileApi {\n @auth\n @post('/')\n public save(ctx: RouteContext): Response {\n const key = new UserKey(AuthService.userId()!.toBytes());\n const p = Profile.decode(ctx.request.body);\n // Save this user's profile. create is insert-only, so the first save creates\n // the record and later saves overwrite the existing one with enqueue.\n if (!AppDb.profiles.create(key, p)) {\n AppDb.profiles.enqueue(key, p);\n }\n return Response.text('saved\\n');\n }\n}\n```\n\n## Extending the user: add your own fields\n\nBuilt-in auth reserves exactly two fields on the authenticated user: `toilUserId` and `username`. To carry\nmore (a role, a display name, a tenant), just declare your OWN `@user` in your server code while\n`server.auth` is on. The build detects it and **extends** it: it injects the reserved `toilUserId` +\n`username` as the first two fields and mints sessions for your shape automatically. You do not opt out of\nanything, and there is still exactly one `@user` per program.\n\n```ts\n@user\nclass Account {\n admin: bool = false;\n displayName: string = '';\n tenant: string = '';\n // toilUserId + username are INJECTED by the build; do not declare them here.\n}\n```\n\nRules:\n\n- Do **not** declare `toilUserId` or `username` yourself. They are reserved and injected; declaring either is\n a compile error (`'username' is reserved by built-in auth`).\n- Your `@user` must be default-constructible (give every field an initializer), like any `@data` class.\n\n`AuthService.getUser()` is now typed to YOUR shape:\n\n```ts\nconst user = AuthService.getUser(); // { toilUserId, username, admin, displayName, tenant } | null\n```\n\n**Populating your fields.** Login fills `toilUserId` + `username`; your extra fields start at their declared\ndefaults (`admin = false`, and so on). The built-in controller cannot know your business fields, so you set\nthem yourself on one of your own `@auth` routes by reading the user, updating it, and re-minting the session:\n\n```ts\n@rest('account')\nclass AccountApi {\n @auth @post('/promote')\n public promote(): Response {\n const user = AuthService.getUser()!;\n user.admin = true;\n const resp = Response.text('promoted\\n');\n resp.setCookie(AuthService.mintSession(user.encode())); // re-sign the session with the new fields\n resp.setCookie(AuthService.userCookie(user.encode())); // update the readable companion cookie\n return resp;\n }\n}\n```\n\nIf you would rather hand-write the whole controller instead, you still can: do **not** enable `server.auth`,\nand build your own `@user` + routes from the [AuthService primitives](#the-authservice-primitive-reference)\nbelow. But for most apps, extending is all you need.\n\n## Adding email verification / 2FA\n\nLayer a second factor on top of the session with `TwoFactor` (stateless email codes, no DB; see\n[email](../services/email.md)). Typical flow: after login, require a verified email before granting access to\nsensitive routes.\n\n```ts\n@rest('2fa')\nclass TwoFactorApi {\n // Step 1: email a code to the logged-in user, hand back the signed token.\n @auth @post('/send')\n public send(): Response {\n const email = /* the user's email, e.g. their username, or a stored profile field */;\n const ch = TwoFactor.send(email, 'login'); // emails the code, returns { token, status }\n return Response.bytes(new DataWriter().writeString(ch.token).toBytes());\n }\n\n // Step 2: verify the code the user typed against the token.\n @auth @post('/verify')\n public verify(ctx: RouteContext): Response {\n const r = new DataReader(ctx.request.body);\n const token = r.readString(); const email = r.readString(); const code = r.readString();\n if (!TwoFactor.verify(token, email, code)) return Response.text('bad code\\n', 401);\n // Mark this session 2FA-verified: re-mint the session with a flag in your own @user, or store a\n // per-user \"verified\" record keyed on AuthService.userId().\n return Response.text('verified\\n');\n }\n}\n```\n\n`TwoFactor` gives integrity + expiry but not single-use (a code re-verifies within its TTL); keep the TTL\nshort. For a branded email, use `TwoFactor.issue(...)` (returns the code without sending) + your own\n`Emails.*` template. Call `TwoFactor.setSecret(...)` once at startup in production.\n\n## The `AuthService` primitive reference\n\nEverything the built-in controller is built from, available for hand-written auth. All are ambient globals\n(no import).\n\n**Sessions & cookies**\n- `mintSession(userData: Uint8Array, ttlSecs?: u64): Cookie`: the signed `__Host-toil_sess` cookie.\n- `userCookie(userData, ttlSecs?): Cookie`: the readable `__Secure-toil_user` companion.\n- `clearSession(): Cookie` / `clearUserCookie(): Cookie`.\n- `hasSession(): bool`: the `@auth` predicate.\n- `getSessionBytes(): Uint8Array | null`: the verified `@user` payload bytes.\n- `getUser(): <your @user> | null`: decoded, typed to your `@user`.\n- `userId(): ToilUserId | null`: the stable id (built-in `@user` layout).\n- `setSecret(secret: Uint8Array)`: override the session HMAC key programmatically.\n\n**Post-quantum login crypto**\n- `oprfEvaluate(username, blinded): Uint8Array`: server-keyed OPRF eval.\n- `buildRegisterMessage(username, pk)` / `verifyRegister(pk, msg, sig): bool`: proof-of-possession.\n- `buildLoginMessage(sub, aud, cid, nonce, iat, exp, ct, memKiB, iterations, parallelism, serverKemKeyId)`\n / `verifyLogin(pk, msg, sig): bool`.\n- `mlkemDecapsulate(ct): Uint8Array`, `serverKemKeyId(): Uint8Array`.\n- `deriveSessionKey(sharedSecret, transcriptHash)`, `serverConfirmTag(sessionKey, transcriptHash)`: the\n mutual-auth confirmation.\n- `sha256(data): Uint8Array`.\n- `setOprfSeed(seed)`, `setServerKemSecretKey(sk)`, `setServerKemPublicKey(pk)`: override the seeds/keys.\n- Sizes: `PUBLIC_KEY_LEN`, `SIGNATURE_LEN`, `OPRF_ELEMENT_LEN`, `KEM_CIPHERTEXT_LEN`, `SHARED_SECRET_LEN`, …\n\n**Related globals**, `TwoFactor` (email codes; see [email](../services/email.md)), `RateLimitService` (used by\n`@ratelimit`), `Environment` (the secret store).\n\n## Two ways in, one behavior\n\nThe config flag and the import are identical at build time, both make the build append the shipped\n`@user` + `@rest('auth')` controller to the toilscript **entry** set, where their decorators weave and the\n`@rest` class self-mounts. (A framework decorator source only weaves as an entry; that's why a plain\n`import` of the controller isn't enough on its own, the marker import is detected by the build, which does\nthe entry injection.) This is why built-in auth needs no runtime registration call.\n\n\n## Static server typings\n\nServer editor declarations ship with the package; they do not require an app\nbuild. Importing `toiljs/server/runtime` loads them. A project with no runtime\nimport can add `/// <reference types=\"toiljs/server/globals\" />` to a declaration\nfile, or include `\"toiljs/server/globals\"` in its tsconfig `types` alongside\n`\"assembly\"`. The generated `toil-server-env.d.ts` is only a reference shim;\ncreate, build and doctor share the same declaration source.\n\nA plain ToilScript compile needs the framework globals in `--lib`. Without a\ncustom `@user` entry, `AuthService.getUser()` exposes the standard signed\nidentity prefix (`toilUserId: Uint8Array` and `username: string`) without a\ngenerated application declaration. Its decoder validates the 32-byte identity.\nAn explicit `@user` source entry preserves the application's full typed codec,\nincluding additional fields. The framework auth build still appends the built-in\nuser codec when auth is enabled and no custom user exists. That codec also\nsupplies the account controller's session encoder.\n\n## Initializing application records during registration\n\nInstall `AuthService.onRegistered((id, username, email) => { ... })` from your\nserver entry point. The callback receives the reserved stable `ToilUserId` and\nvalidated account fields. It runs before the account becomes active and uses the\nsame Action budget as registration. Use conditional create/upsert logic suitable\nfor retries: the callback may run more than once.\n\nIf it traps, registration remains pending and cannot sign in. A new registration\nattempt with the same credentials and proof resumes it and reruns the initializer.\nEarlier successful database calls remain committed, so callbacks must be\nidempotent. This is appropriate for creating an initial profile or pending\neligibility record; it does not supply extra age/profile answers absent from the\nregistration protocol.\n",
|
|
6
|
+
"auth/google-and-authenticator.md": "# Google login and Google Authenticator\n\nEnable `server: { auth: true }` in `toil.config.ts`. Both features use the existing\n`/auth/me`, `@auth`, session revocation, account deletion, and custom `@user` codec.\nGoogle login is an additional identity provider; its signature security is Google's\nRS256, rather than the post-quantum password protocol.\n\n## Google sign-in\n\nCreate a Web application client in [Google Cloud](https://developers.google.com/identity/gsi/web/guides/get-google-api-clientid).\nRegister your production HTTPS origin and your localhost development origin as\nAuthorized JavaScript origins. Configure branding/consent and publish the consent\nscreen as appropriate. This implementation uses the GIS JavaScript credential\ncallback; it does not need a client secret or redirect URI.\n\n```dotenv\n# .env (and the tenant's plain environment on toil-backend)\nAUTH_GOOGLE_CLIENT_ID=your-client-id.apps.googleusercontent.com\nPUBLIC_BASE_URL=https://your-site.example\n```\n\nRun `toiljs generate auth` to configure the auth secrets. Google login and TOTP\nrequire an explicitly configured `AUTH_SESSION_SECRET` of at least 32 characters\nin `.env.secrets` (or the tenant secure environment). Never expose it to Vite.\nKeep it stable across workers and deployments. Rotating it invalidates sessions,\npending Google nonces, and existing encrypted authenticator secrets.\n\nRender the official button:\n\n```tsx\nimport { GoogleSignIn, Auth, TwoFactorRequiredError } from 'toiljs/client';\n\n<GoogleSignIn\n onSuccess={() => { location.assign('/account'); }}\n onError={error => {\n if (error instanceof TwoFactorRequiredError) {\n // Show your code form; save error.twoFaId for Auth.verifyTwoFactor.\n } else {\n // Show a retry action. Never log the credential.\n }\n }}\n/>\n```\n\nRender one widget at a time. The button initializes a browser-bound nonce valid for\n120 seconds; remount it to retry after expiry, cancellation, or a failed attempt.\nFor your own GIS UI, use `Auth.googleLoginStart()`, initialize GIS with the returned\n`clientId` and `nonce`, then pass the callback's `credential` to\n`Auth.loginWithGoogle(credential)`. Complete a second-factor challenge using\n`Auth.verifyTwoFactor(error.twoFaId, code)`. No session is issued before that succeeds.\n\nGoogle's SDK needs explicit [CSP allowances](https://developers.google.com/identity/gsi/web/guides/get-google-api-clientid#content_security_policy).\nAdd these to `client.cspSources` (merge with existing settings):\n\n```ts\ncoop: 'same-origin-allow-popups',\ncspSources: {\n 'connect-src': ['https://accounts.google.com/gsi/'],\n 'frame-src': ['https://accounts.google.com/gsi/'],\n 'style-src': ['https://accounts.google.com/gsi/style'],\n // Google's current library uses DOM sinks that do not support Trusted Types.\n // This opt-out applies to the whole page; keep Toil's CSP script protections.\n 'require-trusted-types-for': [],\n}\n```\n\nToil's default script CSP trusts scripts intentionally loaded by `Toil.Script`,\nwhich the component uses. If you override `script-src`, also authorize\n`https://accounts.google.com/gsi/client` and your application scripts. The component\nrequests the FedCM button flow. For browsers using Google's popup fallback, serve\nthe login page with `Cross-Origin-Opener-Policy: same-origin-allow-popups`. The\n`client.coop` option above configures development, Node production, and generated\nstatic-host headers. Apply `build/client/_headers` on other hosts and remove any\nconflicting proxy COOP header.\nSee [Google's setup guidance](https://developers.google.com/identity/gsi/web/guides/get-google-api-clientid#cross_origin_opener_policy).\n\nThe server validates the RS256 signature, issuer, audience, authorized party,\nexpiration, issue time, optional not-before time, verified email, and nonce before account access. Google\n`sub` determines identity; an email match never links an existing password account.\nIf the address is already reserved by another account, sign-in fails. The internal\n`google_` username prefix is reserved. A changed Google email does not change your\nexisting Toil account's email or identity. Users can delete their account through\nthe existing account API. Account linking is not currently exposed. Email password reset does not create a\npassword credential for Google-only accounts; recover access through Google.\n\nGoogle is authoritative for Gmail addresses and verified Workspace addresses\nwith an `hd` claim. A third-party address without `hd` stays unconfirmed until\nan independent email confirmation succeeds. When the tenant requires email\nconfirmation, Google login returns `EmailNotConfirmedError`, sends the initial\nconfirmation email, and issues no session; `Auth.resendConfirmation(email)`\nresends it. A valid Google identity alone does not prove current ownership of a\nrecycled third-party mailbox. See [Google's verification guidance](https://developers.google.com/identity/gsi/web/guides/verify-google-id-token).\n\n\nNode >=24 uses asynchronous key preparation around synchronous Wasm dispatch.\nSingle and multiple production workers use the same path. toil-backend includes\n`google-auth` in default features; custom feature builds must include it. Its\nasync executor suspends while a bounded two-thread service fetches keys and\nverifies signatures; the inline executor waits for the same service. Both hosts fetch keys only from\nGoogle's fixed HTTPS JWKS endpoint, with a bounded shared cache, single-flight\nrefresh, timeout, and refresh cooldown. No per-login tokeninfo or userinfo request.\nSecurity-state unique lookups read the owning database cell. With multiple cells,\nthe async host routes these reads directly to the owner; the inline host fails\nclosed when a security key is not local.\n\nInitialization performs zero DB calls. Invalid claims perform zero account calls.\nReturning Google login performs one authoritative account read and conditional\nreplay update, plus the existing deletion, factor, and session-generation checks.\nThe account retains at most 16 nonces for its latest Google issue-time second;\nolder tokens and additional simultaneous logins beyond that limit require retry.\nThere are no Google state/token rows to expire or scan. New-account creation also\nreserves the email and maintains the existing user index and registration hook.\n\n## Google Authenticator (TOTP)\n\nCompatible with Google Authenticator and other RFC 6238 apps: SHA-1, six digits,\n30-second periods, and a one-step clock tolerance. Keep server time synchronized.\n\n```ts\n// Requires a signed-in session. Show the secret directly or encode URI in a QR\n// code locally. Never send it to a third-party QR service or analytics.\nconst { secret, uri } = await Auth.setupAuthenticator('Your Site', 'user@example.com');\n// Display secret or QR(uri), collect the code from the user's app:\nawait Auth.confirmTwoFactorSetup(code);\n// Existing sessions are revoked; sign in again with password or Google + TOTP.\n```\n\n`Auth.twoFactorStatus()` returns `Auth.TwoFactorMethod.Authenticator` (`2`) when\nenabled. Existing `None` (`0`) and `Email` (`1`) values keep their meanings.\nEnrollment is pending until a valid app code confirms it; repeating setup replaces\nthe pending enrollment. Secrets are AES-256-GCM encrypted in the database and bound\nto the tenant and account incarnation. Setup responses use `Cache-Control: no-store`.\n\nOn login, catch `TwoFactorRequiredError` and submit the app code using\n`Auth.verifyTwoFactor(error.twoFaId, code)`. Codes are rate- and attempt-limited.\nA successful code advances a linearizable counter: reusing the same or an older\n30-second code fails even across separate challenges and workers. Wait for the\nnext code after confirming enrollment or using a code on another device.\nLogin and current-factor replacement guesses share a cap of five per minute\nper account across source IPs and pending challenges. The counter uses one row per enrollment; successful verification costs one\ncounter read and one compare-and-exchange. Secret verification itself does no DB I/O.\n\nTo disable, prove the current authenticator:\n\n```ts\nawait Auth.setupTwoFactor(Auth.TwoFactorMethod.None);\nawait Auth.confirmTwoFactorSetup(codeFromCurrentAuthenticator);\n```\n\nTo replace an authenticator while it is enabled, pass a fresh current code as the\nfourth argument to `Auth.setupAuthenticator(issuer, account, options, currentCode)`;\nthen confirm with the new authenticator. To switch from email 2FA, disable it with\nits email code first, sign in again, then enroll TOTP. A session alone cannot\nreplace an enabled factor. Password reset keeps the second factor enabled.\nThere is no automatic factor recovery or recovery-code API; applications must\nprovide their own identity-verified operator recovery process for lost devices.\nBack up authenticator accounts before deploying this option.\n\n## Runtime rollout and limits\n\nDeploy the updated toil-backend before new Wasm: the runtime now imports\n`google_verify`, `crypto.totp_verify`, and bounded `codec.base64url_*` helpers.\nNode builds include the matching implementations. Existing password accounts and\nemail-factor values retain their layouts; added security fields are append-only.\nSession format 3 rejects existing session cookies and older pending challenges,\nso users must sign in again. Its generation keys include the normalized Host;\nold application code cannot overwrite the new factor state. Existing factors\nin `AuthStateDb` remain readable without resetting the database. Upgrade all\napplication instances before enabling Google login or TOTP; mixed application\nversions cannot consistently enforce a newly introduced factor policy.\n\nFactor confirmation atomically commits the policy and session-generation change\nin one immutable claim. A failure after that write may leave the client without\na success response, but earlier sessions are already invalid and the new factor\nis enforced. Sign in again to determine the resulting state.\n\nThe native integration gate exercises Google registration, authenticator setup,\nand two-factor login with the default 128M gas budget. Custom `@user` codecs,\nlonger domains, concurrent revocations, and application registration hooks can\nrequire additional headroom; configure `TOIL_LIMIT_GAS_HTTP` for the measured\nworkload. Keep database budgets enabled when testing. No database scans or\nper-login Google token/state rows are used.\n",
|
|
6
7
|
"auth/how-it-works.md": "# How Toil auth works\n\nToil auth is a **post-quantum, password-based, mutually-authenticated** login. The design goal: the user\ntypes a password, but the server never sees it, never stores it, and can't be phished into leaking a\nverifier, and every primitive is quantum-resistant.\n\nThis page explains the protocol. You do not need to understand it to use auth (see [Usage](./usage.md)),\nbut you should understand the guarantees before you ship.\n\n## The building blocks\n\n| Primitive | Role |\n| --- | --- |\n| **OPRF** (RFC 9497, ristretto255-SHA512) | A *server-keyed* salt. The client blinds its password, the server evaluates it under a per-user key, the client unblinds. The result can't be computed without the server, so a stolen database can't be brute-forced offline. |\n| **Argon2id** | Stretches the OPRF output into key material (memory-hard, GPU/ASIC-resistant). Runs in the browser. |\n| **ML-DSA-44** (FIPS 204) | The user's identity key pair is *derived* from the Argon2id output. The server stores only the **public** key. Login is proved by an ML-DSA signature. |\n| **ML-KEM-768** (FIPS 203) | Key encapsulation on login: the server proves it holds its KEM secret by returning a confirmation tag only derivable from the decapsulated shared secret → **mutual** auth (anti-phishing). |\n| **HMAC-SHA256** | Signs the session cookie (`AUTH_SESSION_SECRET`). |\n\n> The whole thing is sometimes called an *aPAKE* (asymmetric password-authenticated key exchange). Do not\n> call it OPAQUE, this is Toil's own OPRF + KEM + signature construction.\n\n## What the server stores\n\nPer account, in ToilDB (`@database AuthDb`):\n\n- `username`, a deterministic `salt`, the **ML-DSA public key**, and the Argon2id params.\n\nThat's it. **No password, no password hash, no verifier that can be brute-forced without the OPRF key.**\nLogin challenges are a second collection, consumed exactly once (atomic `getDelete`).\n\n## Registration\n\n```\n Browser (client) Toil edge (server)\n ───────────────── ──────────────────\n blind(password) OPRF key = f(seed, username)\n │ username, blinded │\n │ ───────── POST /auth/register/start ───────────► │\n │ │ evaluated = OPRF(blinded)\n │ ◄──── {mem,iters,par, salt, evaluated} ───────── │ (salt is deterministic per user)\n │ │\n unblind → oprfOut │\n seed = Argon2id(oprfOut, salt, params) │\n (pk, sk) = ML-DSA-44.keygen(seed) │\n proof = ML-DSA.sign(sk, \"register|username|pk\") │\n │ username, pk, proof │\n │ ───────── POST /auth/register/finish ──────────► │\n │ │ verifyRegister(pk, msg, proof) ✓ proof-of-possession\n │ ◄──────────── {status: 0 ok | 1 taken} ──────── │ store AuthAccount{username, salt, pk, params}\n```\n\nThe server never learns the password or the secret key `sk`, only the public key `pk` and a proof the\nclient holds the matching `sk`. A duplicate username returns a **distinguishable** `status = 1` (so the UI\ncan say \"taken, log in instead\"); everything else fails generically.\n\n## Login (with mutual auth)\n\n```\n Browser (client) Toil edge (server)\n ───────────────── ──────────────────\n blind(password) │\n │ username, blinded │\n │ ───────── POST /auth/login/start ──────────────► │ evaluated = OPRF(blinded) (ALWAYS, even unknown user)\n │ │ if known: store Challenge{cid, nonce, iat, exp}\n │ ◄─ {cid, aud, params, salt, nonce, iat, exp, ── │ (identical response whether the user exists or not)\n │ evaluated} │\n unblind → Argon2id → (pk, sk) = ML-DSA.keygen │\n (ct, ssС) = ML-KEM-768.encapsulate(serverKemPublicKey) │\n msg = \"login|username|aud|cid|nonce|iat|exp|ct|params|kid\" │\n sig = ML-DSA.sign(sk, msg) │\n │ cid, ct, sig │\n │ ───────── POST /auth/login/finish ─────────────► │ ch = challenges.getDelete(cid) (consume once; check exp)\n │ │ rebuild msg from OUR stored values + ct\n │ │ verifyLogin(acct.pk, msg, sig) ✓ it's really this user\n │ │ ssS = ML-KEM.decapsulate(ct) ✓ we hold the KEM key\n │ │ K = deriveSessionKey(ssS, H(msg))\n │ ◄──── {0, sessionToken, serverConfirm} ──────── │ serverConfirm = tag(K, H(msg))\n │ + Set-Cookie: __Host-toil_sess=… │ mint session cookie\n verify serverConfirm using ssC ✓ the server is genuine │\n```\n\nTwo verifications, both required:\n1. **The server verifies the client**: the ML-DSA signature over a message bound to the challenge, the\n Argon2id params, and the server's KEM key id. Replays fail (the challenge is consumed).\n2. **The client verifies the server**: the `serverConfirm` tag is derivable only from the ML-KEM shared\n secret, which only the holder of the KEM secret key can decapsulate. A phishing site can't forge it.\n\n## Anti-enumeration\n\n`/login/start` behaves identically for a known and an unknown user: it always runs the OPRF (a decoy key\nfor unknown users), returns a **deterministic** per-user salt and constant params, and a fresh challenge.\nThe challenge is persisted only for a real account, and `/login/finish` fails generically at consume for an\nunknown user. So an attacker can't probe which usernames exist. Every failure path returns the same\n`401 auth: request failed`.\n\n## Sessions & cookies\n\nOn successful login the server mints **two** cookies:\n\n- **`__Host-toil_sess`**: the authoritative session. HMAC-SHA256 signed with `AUTH_SESSION_SECRET`,\n `HttpOnly`, `Secure`, `SameSite=Lax`. It carries the `@user` codec payload. `@auth` and\n `AuthService.getUser()` open + verify this cookie server-side; a forged or tampered cookie fails.\n- **`__Secure-toil_user`**: a **readable** companion carrying the same payload, so the browser can show\n \"logged in as …\" via the client's `getUser()`. The server **never trusts it**, it is display-only.\n\nEach request runs in a fresh wasm instance. The signed payload is self-contained,\nbut verification also reads the revoked-session and user-generation collections. `AUTH_SESSION_SECRET` must be identical across every edge instance (it is, via the\nenv store) so a cookie minted anywhere verifies everywhere.\n\n## The stable user identity: `ToilUserId`\n\nAt account creation the server derives and stores a stable, tenant-scoped id; login puts that stored id in the session (the first field of the\nbuilt-in `@user`):\n\n```\ntoilUserId = SHA-256(bytes(\"toil.userid.v1\") ‖ bytes(mldsaPublicKey) ‖ bytes(username) ‖ bytes(domain))\n```\n\nEach `bytes(x)` writes a `u32` little-endian byte length followed by the bytes.\nText fields use UTF-8. The prefix is framed the same way as the other fields;\nthe preimage is not a raw concatenation of strings.\n\n- **Stable:** same login key + username on the same tenant `domain` → same id, forever, across sessions\n and devices. Key your own data on it.\n- **Opaque + one-way:** it's a hash: safe to store, log, or expose without leaking the key or the address.\n- Read it anywhere with `AuthService.userId()`. See [Extending](./extending.md#toiluserid) for the\n `ToilUserId` API (O(1) `==` / `!=`, `toHex()`, …).\n\n## Threat-model summary\n\n- **Server database stolen** → attacker gets public keys + salts, not passwords. Brute-forcing needs the\n OPRF key (server-side) *and* Argon2id work per guess.\n- **Server compromised / malicious** → still can't recover passwords (only public keys) and can't forge a\n past session without `AUTH_SESSION_SECRET`.\n- **Phishing site** → can't produce the `serverConfirm` tag (no KEM secret), so a correct client aborts.\n- **Quantum adversary** → ML-DSA + ML-KEM are post-quantum; the OPRF/Argon2id/HMAC pieces are classical but\n not the long-term identity or key-exchange.\n- **Replay** → challenges are single-use (`getDelete`) with a short TTL.\n\nResidual responsibilities are yours: set the [secrets](./configuration.md), pin your deployment's KEM\npublic key in the client, and raise the Argon2id params for production.\n\nFor native/mobile ports, see the [binary protocol and verified test vectors](./native-protocol.md).\n",
|
|
7
8
|
"auth/native-protocol.md": "# Native client protocol and vectors\n\nA native client can implement the same protocol as `toiljs/client` without a\nWebView. The portable known-answer fixture is [vectors-v1.json](./vectors-v1.json).\nThe package ships it as `toiljs/auth/vectors-v1.json`, and builds copy it beside\nthis guide under `.toil/docs/auth/` so the relative link works locally.\nIt contains public test seeds and keys, intermediate values, complete signed\nmessages, signatures, and confirmation tags. The fixture is tested against the\nJavaScript client, compiled ToilScript server helpers, and native Rust OPRF,\nML-DSA, ML-KEM, SHA-256, and HMAC implementations.\n\nRegenerate it after building toiljs with `node scripts/gen-auth-vectors.mjs`.\nAll binary fields in the JSON are hexadecimal; timestamps are decimal strings.\nThe fixture's fixed timestamps and keys are for offline interoperability tests.\n\n## Binary framing\n\nHTTP bodies use `application/octet-stream`. All integers are unsigned,\n**little-endian**. `bytes(x)` is `u32(byteLength) || x`; `str(s)` is\n`bytes(UTF8(s))`. Strings are length-prefixed UTF-8, without a terminator.\nThese auth bodies do not have the four-byte `@data` class tag.\n\n## Password and key derivation\n\n1. Encode `NFKC(password)` as UTF-8. Do not trim, lowercase, or otherwise change it.\n2. Use RFC 9497 **OPRF mode**, `ristretto255-SHA512`, not VOPRF or POPRF mode.\n The client generates a fresh blind and sends the 32-byte blinded element.\n The server derives its per-user OPRF key with `DeriveKeyPair(oprfSeed,\n UTF8(username))` and evaluates that element.\n3. Finalize the OPRF using the normalized password bytes, saved blind, and\n evaluated element. Its 64-byte output is the **binary password input** to\n Argon2id; it is not hexadecimal text.\n4. Run Argon2id with the server-issued salt, memory size in **KiB**, iteration\n count, parallelism, and a 32-byte output. The vector records each parameter.\n5. Use those 32 output bytes as the ML-DSA-44 key-generation seed. Public keys\n are 1,312 bytes and signatures are 2,420 bytes. Do not send the password,\n OPRF output, Argon2 output, or signing secret key to the server.\n\n## Registration\n\n`POST /auth/register/start`:\n\n```\nrequest = str(username) bytes(blinded)\nresponse = u8(status) u32(memKiB) u32(iterations) u32(parallelism)\n bytes(salt) bytes(evaluated)\n```\n\nContinue only for status 0. Build the registration proof message:\n\n```\nu8(1) str(username) bytes(mldsaPublicKey)\n```\n\nSign it with ML-DSA-44 and the separate FIPS 204 context\n`qauth:register:v1`. Pass the context through the signature API; do not prepend\nit to the message yourself.\n\n`POST /auth/register/finish` sends:\n\n```\nstr(username) str(email) bytes(mldsaPublicKey) bytes(registerSignature)\n```\n\nThe response starts with a status byte. Status 0 means registration completed;\nnonzero statuses are errors. Email confirmation may still be required by the\napplication. Initialize application records through the server-side\n`AuthService.onRegistered` hook when appropriate.\n\n## Login and server authentication\n\nPin the deployment's **ML-KEM-768 public key** in the native app's trusted\nconfiguration. It is 1,184 bytes; never replace it with a key learned from an\nuntrusted login response.\n\n`POST /auth/login/start`:\n\n```\nrequest = str(username) bytes(blinded)\nresponse = bytes(cid) str(audience)\n u32(memKiB) u32(iterations) u32(parallelism) bytes(salt)\n bytes(nonce) u64(iat) u64(exp) bytes(evaluated)\n```\n\nFinish the OPRF/KDF and regenerate the signing key. Encapsulate a fresh ML-KEM-768\nsecret to the pinned server public key. The ciphertext is 1,088 bytes; the shared\nsecret is 32 bytes. Compute `serverKemKeyId = SHA256(serverKemPublicKey)`.\nBuild the exact login message:\n\n```\nu8(1) str(username) str(audience) bytes(cid) bytes(nonce)\nu64(iat) u64(exp) bytes(ciphertext)\nu32(memKiB) u32(iterations) u32(parallelism) bytes(serverKemKeyId)\n```\n\nSign with the separate context `qauth:login:v1`. Submit\n`bytes(cid) bytes(ciphertext) bytes(signature)` to `/auth/login/finish`.\nFor status 0 or 3, its response is:\n\n```\nu8(status) bytes(first) bytes(serverConfirm)\n```\n\nStatus 0 supplies the readable user codec bytes in `first`; status 3 supplies a\nsecond-factor challenge identifier and creates no session. For **both** statuses,\nverify server authentication before accepting a login or showing the 2FA prompt:\n\n```\nH = SHA256(loginMessage)\nK = HMAC_SHA256(sharedSecret, UTF8(\"toil-session-key-v1\") || H)\nexpected = HMAC_SHA256(K, UTF8(\"toil-server-confirm-v1\") || H)\n```\n\nCompare `expected` to `serverConfirm` without an early exit on differing bytes.\nOther status values represent failed credentials, confirmation requirements, or\nother errors. Challenges are expiring and single-use; obtain a new challenge for\na retry.\n\n## Sessions on native transports\n\nThe readable `first` value is **not a bearer credential**. Preserve the signed\nHttpOnly session cookie from `Set-Cookie` in the platform's cookie jar and send\nit on later requests to the same tenant. Over HTTPS its name is\n`__Host-toil_sess`; the readable companion is `__Secure-toil_user`. Honor both\nclearing cookies on logout or 401. The companion and decoded user bytes are for\ndisplay, and the server revalidates the signed cookie and revocation state.\n\n## Initial stable identity\n\nFor a newly registered account, the user ID is SHA-256 over four `bytes(...)`\nfields: UTF-8 `toil.userid.v1`, the ML-DSA public key, UTF-8 username, and the\nconfigured identity domain. The vector includes this initial ID. The account\nstores its ID so password/key changes preserve the existing identity; clients\nshould use the returned server identity rather than derive a replacement.\n",
|
|
8
|
-
"auth/README.md": "# Authentication\n\nToil ships a complete, **post-quantum password login** you turn on with one line. No passwords on your\nserver, no third-party identity provider, no hand-written crypto: enable it and you get a `/auth/*` API,\nsigned sessions, `@auth`-guarded routes, and a stable per-user identity.\n\n```ts\n// toil.config.ts\nimport { defineConfig } from 'toiljs/compiler';\n\nexport default defineConfig({\n server: { auth: true }, // ← mounts the full /auth/* API + sessions\n});\n```\n\nThat is the whole setup. The build appends the framework's auth controller to your server, so `/auth/*`\nis live and `@auth` works everywhere.\n\n## Storage and request lifetime\n\nAuthentication uses collections in two databases: `AuthDb` for accounts and\nchallenges, and `AuthStateDb` for revoked sessions, user generations, and two-factor\nsettings. Verification is cached only on the current request object. Later requests\ncheck revocation state again; local revocation and signing-secret changes invalidate\nthe cached result. Temporary failures reading revocations, generations, or\ntwo-factor state abort the request; they never mean that a restriction is absent.\n\nSession generations use immutable revocation claims and a conditional head update.\nReads probe at most eight revisions beyond the head. Writable requests repair a\nstale head without overwriting a concurrent advance; read-only queries never\nrepair it. If a chain exceeds the probe limit, verification fails closed with\n`Session state recovering; retry`. A writable sign-in or revocation attempt still\npersists its scanned progress before failing, so repeated attempts recover even\nchains longer than 64 revisions. No sessions are minted from a partial scan.\nAuthentication calls count against the same database budget as your handler;\nsee [database limits](../database/documents.md#size-limits-and-file-uploads).\n\nWhen a generated `@auth` guard returns 401, it clears both the signed session and\nreadable user cookies, using their HTTP or HTTPS names and attributes. Storage\nfailures abort verification instead of returning that 401, preserving credentials\nfor a retry.\n\
|
|
9
|
+
"auth/README.md": "# Authentication\n\nToil ships a complete, **post-quantum password login** you turn on with one line. No passwords on your\nserver, no third-party identity provider, no hand-written crypto: enable it and you get a `/auth/*` API,\nsigned sessions, `@auth`-guarded routes, and a stable per-user identity.\n\n```ts\n// toil.config.ts\nimport { defineConfig } from 'toiljs/compiler';\n\nexport default defineConfig({\n server: { auth: true }, // ← mounts the full /auth/* API + sessions\n});\n```\n\nThat is the whole setup. The build appends the framework's auth controller to your server, so `/auth/*`\nis live and `@auth` works everywhere.\n\nFor [Google sign-in and Google Authenticator](./google-and-authenticator.md), see the setup,\nbrowser component, production configuration, and TOTP enrollment guide.\n\n## Storage and request lifetime\n\nAuthentication uses collections in two databases: `AuthDb` for accounts and\nchallenges, and `AuthStateDb` for revoked sessions, user generations, and two-factor\nsettings. Verification is cached only on the current request object. Later requests\ncheck revocation state again; local revocation and signing-secret changes invalidate\nthe cached result. Temporary failures reading revocations, generations, or\ntwo-factor state abort the request; they never mean that a restriction is absent.\n\nSession generations use immutable revocation claims and a conditional head update.\nReads probe at most eight revisions beyond the head. Revocation claims include\na random ownership nonce so separate revocations cannot coalesce as identical\nunique owners. A factor change stores the new factor policy in the same claim\nthat advances the generation: request failure cannot leave an enabled factor\nwith still-valid earlier sessions. A competing advance triggers a fresh scan;\nordinary revocations preserve the factor policy. A successful fast claim leaves\na single revision for the next writable request to repair. Writable requests repair a\nstale head without overwriting a concurrent advance; read-only queries never\nrepair it. If a chain exceeds the probe limit, verification fails closed with\n`Session state recovering; retry`. A writable sign-in or revocation attempt still\npersists its scanned progress before failing, so repeated attempts recover even\nchains longer than 64 revisions. No sessions are minted from a partial scan.\nAuthentication calls count against the same database budget as your handler;\nsee [database limits](../database/documents.md#size-limits-and-file-uploads).\n\nWhen a generated `@auth` guard returns 401, it clears both the signed session and\nreadable user cookies, using their HTTP or HTTPS names and attributes. Storage\nfailures abort verification instead of returning that 401, preserving credentials\nfor a retry.\n\nSession format 3 uses host-scoped generation keys, even when domains share a\nconfigured `TOIL_AUTH_DOMAIN`. Upgrading signs everyone out and rejects older\npending login/setup challenges. Existing `AuthStateDb` factor records remain\nreadable; new changes use atomic generation commits. All server instances must\nrun the updated application before enabling the new authentication features.\n\nFor deployments migrating from the earlier separate session and factor database\nnamespaces, the `AuthStateDb` layout replaces those namespaces. It requires a fresh store or an explicit migration of existing security\nstate; it does not read the previous namespaces. The Nerva rollout uses a database\nreset alongside the application schema change.\n\n## What you get\n\n| Endpoint | Purpose |\n| --- | --- |\n| `POST /auth/register/start`, `/register/finish` | Create an account (password never leaves the browser) |\n| `POST /auth/login/start`, `/login/finish` | Log in; sets a signed session cookie |\n| `GET /auth/me` *(`@auth`)* | The current user (`toilUserId` + `username`) |\n| `POST /auth/logout` *(`@auth`)* | Clear the session |\n\nPlus, in your own code:\n\n- **`@auth`** on any route (or a whole `@rest` class) → 401 unless there's a valid session.\n- **`AuthService.getUser()`** → the typed logged-in user.\n- **`AuthService.userId()`** → the stable [`ToilUserId`](./extending.md#toiluserid) (a 256-bit id you can\n key your data on).\n- **The client**: `import { Auth } from 'toiljs/client'`, then `Auth.register(username, password)` /\n `Auth.login(username, password)`. It does all the browser-side crypto and talks to `/auth/*` for you.\n\n## A login page in full\n\n```tsx\n// client/routes/login.tsx\nimport { useState } from 'react';\nimport { Auth } from 'toiljs/client';\n\nexport default function Login() {\n const [u, setU] = useState('');\n const [p, setP] = useState('');\n const [msg, setMsg] = useState('');\n\n const register = async () => {\n try { await Auth.register(u, p); setMsg('registered, now log in'); }\n catch (e) { setMsg(parseError(e)); }\n };\n const login = async () => {\n try { await Auth.login(u, p); setMsg('logged in'); } // sets the session cookie\n catch (e) { setMsg(parseError(e)); }\n };\n\n return (\n <main>\n <input value={u} onChange={(e) => setU(e.currentTarget.value)} placeholder=\"username\" />\n <input value={p} type=\"password\" onChange={(e) => setP(e.currentTarget.value)} placeholder=\"password\" />\n <button onClick={register}>Register</button>\n <button onClick={login}>Log in</button>\n <p>{msg}</p>\n </main>\n );\n}\n```\n\n```ts\n// server/routes/Secret.ts, a route only a logged-in user can reach\nimport { Response } from 'toiljs/server/runtime';\n\n@rest('secret')\nclass Secret {\n @auth // 401 without a valid session\n @get('/')\n public secret(): Response {\n const user = AuthService.getUser()!; // typed: { toilUserId, username }\n return Response.text('hello ' + user.username + '\\n');\n }\n}\n```\n\nThat's a real, production-grade auth system, the password is stretched with Argon2id in the browser into\nan ML-DSA-44 key pair, your server only ever stores a public key, and login is a mutually-authenticated\nML-KEM-768 challenge. You didn't write any of it.\n\n## Where to go next\n\n- **[How it works](./how-it-works.md)**: the protocol (OPRF + Argon2id + ML-DSA + ML-KEM), sessions,\n cookies, and the `ToilUserId`, with sequence diagrams.\n- **[Usage](./usage.md)**: enabling it, the client API, guarding routes, reading the user, the full wire\n contract of each endpoint.\n- **[Configuration](./configuration.md)**: the secrets a deployment MUST set, the audience/domain, tuning\n Argon2id, and the deploy checklist.\n- **[Extending & integrating](./extending.md)**: `ToilUserId`, keying your own data on a user, a custom\n user shape / opting out, and the `AuthService` primitive reference.\n- **[Customizing the auth emails](./emails.md)**: replace the verification, password-reset, and 2FA\n emails with your own branded React templates by dropping `emails/auth-*.tsx` files.\n\n> **One rule before you ship:** built-in auth runs with **insecure DEV fallback secrets** so it Just Works\n> locally. A deployment MUST set `AUTH_SESSION_SECRET`, `AUTH_OPRF_SEED`, and `AUTH_KEM_SK`. See\n> [Configuration](./configuration.md).\n",
|
|
10
|
+
"auth/red-team-audit.md": "# Authentication red team audit\n\nThis audit covers the uncommitted Google sign-in and Google Authenticator changes\nin ToilJS and toil-backend. It exercises the compiled controller, Node production\nHTTP serving, native sync/async hosts, replay counters, and deterministic database\ninterleavings. Tests use locally generated signing keys and isolated databases;\nno production accounts or external systems were attacked.\n\n## Findings and fixes\n\n| Finding | Severity and prerequisite | Evidence | Resolution |\n| --- | --- | --- | --- |\n| Revocation/factor lookup could trust an absent remote replica | High; multi-cell execution with replication lag | A query at a non-owning cell returned Ok(None) for a unique key owned elsewhere | Unique lookups now read the owning cell for both presence and absence. Inline non-owner reads fail closed; async reads bypass replica and negative caches and use the current-owner RPC. Placement denial remains unavailable, never absent. |\n| Factor change survived a failed request without revoking earlier sessions | High; a database/host failure after the factor write | Injecting failure immediately after the original immutable factor claim left the old session accepted with HTTP 200 | The new policy and generation advance are one immutable epoch claim. Failure after that commit leaves the policy enforced and old sessions rejected. |\n| Replacement TOTP guesses were limited only by source IP | High; an attacker already holds a session | Six distinct source IPs all reached code rejection instead of hitting an account limit | Replacement proof and login proof share the per-account five-per-minute limiter, independent of IP and challenge. The sixth replacement attempt returns 429. |\n| A delayed wrong-code request overwrote a newer enrollment | Medium; concurrent setup/verification requests | Pause before the attempt update, replace enrollment, resume: the replacement's correct code failed | Wrong-attempt updates and expired/exhausted deletion now compare against the exact snapshot read. A stale request cannot overwrite or delete a replacement. |\n| Third-party Google email was treated as independently confirmed | Medium; a Google account retains an external address whose ownership has changed | The original registration marked every verified Google email confirmed, including when tenant policy required confirmation | The host reports whether Google is authoritative for the email. Other addresses require independent confirmation when tenant policy requires it; the login issues no session and returns EmailNotConfirmedError. |\n| Malformed second-factor identifiers reached persistent limiter/DB work | Medium; unauthenticated requests | An oversized identifier performed a database lookup; the endpoint also hex-encoded arbitrary identifiers before allocating a keyed limiter entry | Second-factor bodies are bounded, login challenge IDs must be exactly 16 bytes, and only existing unexpired challenges allocate keyed limiter entries. Oversized IDs are rejected before DB work. |\n| The initial atomic redesign could replace another realm's factor policy | High; two routed domains share TOIL_AUTH_DOMAIN and a provider identity | A new regression test enabled different factors under both hosts, then signed into the first without its factor | Generation keys now include the normalized routed Host. A shared stable identity domain cannot merge security policies. This regression was caught and fixed while validating the redesign. |\n\nThe email distinction follows [Google's server-verification guidance](https://developers.google.com/identity/gsi/web/guides/verify-google-id-token).\nThe backend absence regression failed before the fix and passes afterward. A\nloopback mesh test independently checks unique-owner current reads, authoritative\nabsence, and unavailable responses for authorization denial. This uses isolated\nin-memory storage, not a deployed multi-region database.\n\nBoth verifiers also reject future or malformed optional `nbf` claims, with a\n30-second tolerance, following the [JWT not-before requirement](https://www.rfc-editor.org/rfc/rfc7519.html#section-4.1.5).\nThis is defensive validation; the audit did not establish that Google currently\nissues exploitable tokens carrying that claim.\n\n## Regression coverage\n\n`test/google-auth.test.ts` contains the failure injection, stale-enrollment race,\ndistributed replacement guesses, third-party email policy, and shared-identity\nrealm tests. Malformed second-factor requests are rejected before database access.\nIt also covers signature/claim rejection, browser nonce binding,\nemail collision without account linking, provider credential reset prevention,\ndeleted accounts, real Node production HTTP login, TOTP encryption, replay,\nconcurrent counter consumption, and factor disablement.\n\nAdditional cases verify that ordinary and verified-session revocations preserve\nthe factor, a stale verified revocation preserves a concurrently committed\nfactor, and writes to the old generation namespace cannot replace new state.\nSession-state tests retain the three-read authorization budget and conditional\nhead-repair invariants. JWKS and codec tests cover bounded parsing and cache\nfailure behavior. Browser tests exercise production response policies with two\nHTTP workers.\n\n## Verification\n\nThe SDK suite passes 727 tests (5 skipped), including 17 Google/TOTP tests with\ndatabase limits enabled. Browser validation passes all 3 cases. SDK build, lint,\ntypecheck, example build, and native sync/async authentication checks pass.\nThe targeted ToilDB unique-owner suite passes 14 tests, and both current-owner\nmesh tests pass. A broader filter also selected 3 live ScyllaDB cases; those\ncould not run because the configured localhost service refused the connection.\n\nRun the SDK checks from the ToilJS checkout:\n\n```sh\nnpm run build\nnpm run lint\nnpm run typecheck\nnpx vitest run\nTOIL_DEV_CHECK_DB_LIMITS=1 npx vitest run test/google-auth.test.ts\nTOILJS_BROWSER_TESTS=1 npx vitest run test/security-browser.test.ts\nnode build/cli/index.js build --root examples/basic\n```\n\nRun the backend checks from the toil-backend checkout:\n\n```sh\ncargo test --lib host::google::tests\ncargo test --manifest-path toildb/Cargo.toml --lib unique_lookup_rejects_non_owner_absence\ncargo test --manifest-path toildb/Cargo.toml --lib distinguish_denial_from_absence\nTOIL_GOOGLE_AUTH_WASM=/root/toiljs/examples/basic/build/server/release.wasm \\\n cargo test --lib compiled_google_auth_and_totp -- --ignored --test-threads=1\nTOIL_GOOGLE_AUTH_WASM=/root/toiljs/examples/basic/build/server/release.wasm \\\n TOIL_GOOGLE_AUTH_ASYNC=1 \\\n cargo test --lib compiled_google_auth_and_totp -- --ignored --test-threads=1\n```\n\nThe native fixture passes the default 128M gas limit in both modes. Measured sync\noperations: initial Google login uses 6 reads/4 writes; authenticator setup uses\n7 reads/1 write; confirmation uses 6 reads/3 writes; authenticator login proof uses\n7 reads/2 writes. Initialization and invalid Google assertions use no database\noperations. Confirmation measured about 126.1M gas, so long domains, custom user\ncodecs, registration hooks, and contention need workload-specific headroom.\n\n## Deployment and limits\n\nDeploy the matching backend first. Then upgrade every application instance before\nenabling the new features. Session format 3 invalidates existing cookies and\nolder pending challenges. Its separate host-scoped generation keys prevent older\napplication code from overwriting atomic factor state. Existing AuthStateDb\nfactor records remain readable; this change does not require a database reset.\nAdministrative deletion explicitly revokes the selected account realm, including\nwhen invoked from a Job without an HTTP request.\n\nThe audit does not establish production Google origin/client configuration,\nmail delivery, deployed database failover behavior, or protection against all\npossible vulnerabilities. Deterministic request races use the real compiled guest\nand shared-store operations; they do not simulate mesh replication or storage\nlease failures. Recovery for a lost authenticator remains an application-owned,\nidentity-verified operator process.\n",
|
|
9
11
|
"auth/usage.md": "# Using auth\n\n## 1. Enable it\n\nEither the config flag (canonical) or a one-line import, both do the same thing (the build appends the\nframework's auth controller + user shape to your server as compiled entries, so `/auth/*` self-mounts):\n\n```ts\n// toil.config.ts, canonical\nexport default defineConfig({ server: { auth: true } });\n```\n\n```ts\n// server/main.ts, escape hatch (equivalent)\nimport 'toiljs/server/auth';\n```\n\nThere is also an `AuthService.enable()` no-op you can call for discoverability, but enabling is done by the\nflag/import above (it happens at build time). Turn it off by removing the flag/import, with neither, no\n`/auth` routes and no accounts collection are generated. It is strictly opt-in.\n\n## 2. The client\n\n`toiljs/client` ships the browser half, it runs the OPRF blinding, Argon2id, ML-DSA keygen, and ML-KEM\nencapsulation, and talks to `/auth/*`. You never touch the crypto.\n\n```ts\nimport { Auth } from 'toiljs/client';\n\n// Create an account. Throws on a taken username or a transport error.\nawait Auth.register(username, password);\n\n// Log in. On success the browser holds the signed session cookie; subsequent\n// requests to @auth routes are authorized automatically.\nawait Auth.login(username, password);\n```\n\nOptions (second argument, `AuthOptions`):\n\n```ts\nawait Auth.login(username, password, {\n baseUrl: '/auth', // default; change if you mount elsewhere\n serverKemPublicKey: MY_KEM_PUB, // REQUIRED in production, pin your deployment's KEM key\n});\n```\n\n> **Production:** the client ships with the DEV KEM public key pinned. A real deployment MUST pass its own\n> `serverKemPublicKey` (derived from `AUTH_KEM_SK`). See [Configuration](./configuration.md).\n\n## 2b. Client-side: who's logged in, and protecting pages\n\n`register`/`login` set the session cookies; to *render* login state on the client, use the generated\n`getUser()` (emitted from the built-in `@user`). It reads the **readable** `__Secure-toil_user` companion\ncookie and returns the typed user or `null`, instant, no network call. It is **display-only**; the server\nstill enforces access via `@auth`, so never trust it for authorization.\n\n```tsx\nimport { getUser } from 'shared/server'; // generated; typed to the built-in @user\n\nfunction Nav() {\n const user = getUser(); // { toilUserId, username } | null\n return user\n ? <span>Hi {user.username} <button onClick={logout}>Log out</button></span>\n : <a href=\"/login\">Log in</a>;\n}\n\nasync function logout() {\n await fetch('/auth/logout', { method: 'POST' });\n location.href = '/login'; // cookies are cleared; bounce to login\n}\n```\n\nGate a whole client route by redirecting when there's no session:\n\n```tsx\nexport default function Dashboard() {\n const user = getUser();\n if (user == null) { location.href = '/login'; return null; } // not logged in -> to /login\n return <main>Welcome, {user.username}</main>;\n}\n```\n\nThe authoritative check is still the server: any data this page fetches should come from an `@auth` route,\nso a user who forged/deleted the readable cookie sees the redirect OR a `401`, never real data.\n\n## 2c. Handling errors\n\n`Auth.register` / `Auth.login` reject with a message you can show. The important distinguishable cases:\n\n```ts\ntry {\n await Auth.register(username, password);\n} catch (e) {\n const m = String(e);\n if (m.includes('already registered')) setError('That username is taken, log in instead.');\n else setError('Could not register, try again.');\n}\n\ntry {\n await Auth.login(username, password);\n} catch {\n // Wrong password OR unknown user both fail generically (anti-enumeration), one message.\n setError('Incorrect username or password.');\n}\n```\n\n- **Username taken** → `register` throws `auth: username already registered (log in instead)` (a\n distinguishable case so you can guide the user).\n- **Wrong password / unknown user** → `login` throws generically (`auth: request failed`): by design,\n the two are indistinguishable, so use ONE \"incorrect username or password\" message.\n- **Rate limited** → after 5 attempts / 60s a `429` surfaces as the same generic throw; back off and tell\n the user to wait.\n\n## 3. Guard your routes: `@auth`\n\nPut `@auth` on a route method or a whole `@rest` class. The generated dispatcher checks for a valid signed\nsession **before** your handler runs and returns `401` otherwise. `@auth` is unchanged by built-in auth,\nit's the same decorator you'd use with hand-written auth.\n\n```ts\n@rest('account')\nclass AccountApi {\n @auth // this route needs a session\n @get('/settings')\n public settings(): Response { /* … */ }\n\n @get('/public') // this one is open\n public open(): Response { /* … */ }\n}\n\n@auth // …or guard the ENTIRE class\n@rest('admin')\nclass AdminApi { /* every route requires a session */ }\n```\n\n## 4. Read the current user\n\nInside any handler:\n\n```ts\n// The typed logged-in user (the built-in `@user`: toilUserId + username), or null.\nconst user = AuthService.getUser();\nif (user != null) {\n user.username; // string\n user.toilUserId; // Uint8Array(32), the stable id bytes\n}\n\n// The stable identity as a ToilUserId (gate on hasSession() first, see note).\nif (AuthService.hasSession()) {\n const id = AuthService.userId()!; // ToilUserId\n // key your own data on id (see Extending)\n}\n```\n\n> `ToilUserId` overloads `==`, so `AuthService.userId() == null` does not type-check. Gate with\n> `AuthService.hasSession()` and then use `userId()!`, or use `getUser()` and null-check that.\n\n## 5. The endpoint wire contract\n\nYou normally use the `Auth` client, but the raw endpoints are binary (`DataWriter`/`DataReader`, never\nJSON):\n\n| Route | Request body | Response |\n| --- | --- | --- |\n| `POST /auth/register/start` | `str(username) bytes(blinded)` | `u8(0) u32(mem) u32(iters) u32(par) bytes(salt) bytes(evaluated)` |\n| `POST /auth/register/finish` | `str(username) bytes(pubkey) bytes(proof)` | `u8(status)`, `0` ok, `1` username taken |\n| `POST /auth/login/start` | `str(username) bytes(blinded)` | `bytes(cid) str(aud) u32(mem) u32(iters) u32(par) bytes(salt) bytes(nonce) u64(iat) u64(exp) bytes(evaluated)` |\n| `POST /auth/login/finish` | `bytes(cid) bytes(ct) bytes(sig)` | `u8(0) bytes(sessionToken) bytes(serverConfirm)` + `Set-Cookie`, or `u8(≠0)` on failure |\n| `GET /auth/me` *(`@auth`)* | (none) | `bytes(toilUserId) str(username)` |\n| `POST /auth/logout` *(`@auth`)* | (none) | `200` + cookie-clearing `Set-Cookie` |\n\nRate limiting: every register/login POST carries `@ratelimit(SlidingWindow, 5, 60)` (5 requests / 60s per\nclient) out of the box, so brute-force is throttled before it reaches the crypto.\n\n## 6. Under `toiljs dev`\n\nEverything runs locally with **zero setup**: the dev server emulates the ToilDB account/challenge storage\nand the ML-DSA/ML-KEM/OPRF host functions in process, and the auth secrets fall back to insecure DEV\nvalues. Register and login span requests (the accounts persist for the dev session). You'll see a warning\nthat `AUTH_SESSION_SECRET` is unset, that's expected in dev; set it before you deploy (see\n[Configuration](./configuration.md)).\n\n## 7. `Server.REST.auth.*`\n\nBecause the controller is a normal `@rest('auth')` class, a typed `Server.REST.auth.*` fetch client is\ngenerated for free (`me`, `logout`, and the register/login methods). Use it for `/me` and `/logout`; but\n**drive register/login through `toiljs/client` `Auth`**, not the generated client, only the `Auth` helper\nruns the required browser-side OPRF/Argon2id/ML-DSA/ML-KEM crypto.\n",
|
|
10
12
|
"auth/vectors-v1.json": "{\n \"format\": \"toil-auth-protocol-v1\",\n \"description\": \"PUBLIC TEST SEEDS AND KEYS. Never use in a deployment.\",\n \"username\": \"vector-user\",\n \"email\": \"vector@example.com\",\n \"domain\": \"vectors.toil.example\",\n \"password\": \"PaKsswörd-12!\",\n \"passwordNfkcUtf8\": \"50614b737377c3b672642d313221\",\n \"memKiB\": 32768,\n \"iterations\": 2,\n \"parallelism\": 1,\n \"salt\": \"202122232425262728292a2b2c2d2e2f\",\n \"oprfSeed\": \"a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3\",\n \"blind\": \"b372eed50523143885dcbf65883ac7ccadbc846bb62a98ffaee4b667bc407e04\",\n \"blinded\": \"569d286c0a058b86987e5646a2c75888112a4c32fed65f65e973a6e54e1cf600\",\n \"evaluated\": \"807be09d776fb5fcb8440b988c25eb67c29c88d8f0b18eaae5de80ff13e18903\",\n \"oprfOutput\": \"801b033287fe9c5905d99b4cde02a164ebe2e70eb1a73e9abe84a2bdeb5b1b138b4a9d44868fdbe9f2223f1726e1e8b4ea18cf117f26a6abafe3819710b09943\",\n \"signingSeed\": \"3654780bdac4955df7ba4c677a563a837611b2f60de8170a5cfdb5e5cc88e3d7\",\n \"mldsaPublicKey\": \"0196dfbfa00d32dd79024cc5ef5fba8f8a855948489a20940032ae07974571ccd4ebfb4a4c95c504aeb0113a0689c0c06c4e3a43a923dfb0af06d8d71f27a017ef8547598e14ab65de873620921ca79417b39f9457208b77efac7bfa394ba85fce3c47dc1ed6bed672cca4745a6988bafd89b95117d2aca531ece00cd5681b31702e99fac8a68a1b03a727abca08bedfeaf9d47de33069ad52a5a5ad1faf102e431d1d1a9902aafaa4c03a13cbd265345d34440fcac6a9c42e1f0b4fabf4bd781cf2324fca9ba9a49328447737546197b7378ca3aec327db79500fd73a4856e31b2c7507a8168a65918197ddd139055f67a95edbe94d229b1617f3a7a177742fd4a809326ea84bc88054e0e4a9586c6f219f57ce229f3c770a64ee94bbfa5d49cc2be002b45359424da064295372270ffb6eceb4301155ef9c1358c1afa63015dac4bebbc15e510c6f7c80537c4d3047d8eec7239453f45b5ee60463c60521ad322e233c18ad20f0d0e311afc55613f638391d3714aa47c704f49df2acce9cb53bef9f5716f451071a321286401e12b5917f382a52df6ae99aad0e97fb90be9fcb0daa305836c778193161d7c15cae3e892b5ece77b32c8c7f7b25ab5bed20dd49cbfa59be54a65c1c009edffb5c2282ce0d438225bf663fa89a9f1d28562017ad31389137b25d760b3f705932f46c4583ec354057561f38554f15f3f2a6e3463a295d06f610f3dc2d104bdfea5a340ccc0007e335db83e8ce11e3ec7d8fb89ee4cad7fffadfd7c2650c9aca13c72182f0d5e431a4bc0f4136ecaa60ba1dc3a8c81f25156d0b98824e69ed764af523aa02dc70401ba6d7887d32ccb949d86f3f8d6e5ee6659067a15557f8fa760a5799b865fd0aca03686d337832363b672807e8e2fd93197eb6ccc2d73e56422386344260f9c82dcf9adb08482428b604ffe1934f4f5eb4cb977615f9aae744d335ac7e37d90b8031212e2e37ca1ef64acbe5cf3f377c1b7a98c9a9c5fe563882cfd8a31c1986d0b801d016a428d31d105e1f2b8897bd8ef48f6833d39fc3e3ea7c5d39d747351fa4fceefd5ed3aa5e016289e74db7e65c5cb2125070e3e300c0c53c63243002825751f9e9f6584aec77cb87d3001160c3c6930e7f215da3936cdbdf430c65b8ff252185e702385903dbd98fe72328e23f242e3adf474f03f81c89bb6ab3e84d082ab13864707fadade3e563af0609b918063ecff63b56bdb980b0bfe404609e25fd74cf951abfe501be137ac2cdb472133ee0bdf0cd969732acd12bf7e07c07b3e14251439f7a714250a50897354ceb68f0c0448f1d2ff989e33c289e8ee646543112135d7229135f9b972ea2219dd0d182f21c17820a7c10803634387311ebe49fb2f52a1c858f6354a2e965463ddb0d4249b321f863441270718eaef54f6cfa81bceb2237de10e26e0257ad8269f82fc4e4252a691549d438367bcffd951de644ccd0b5bd4060288bb6d160abd0e604324e900d06b9c72497180cc396d18132b8718f63e4369848ede93bc812b702daaf6247d788ebbb610cb6b08d971c122e86e5e9f4f137de0bd88abe1fb1fe0abf9823f51a25ede0d47367789c4b5acf756e671252cabedbf66c7ae7566f0cb78cf969ae0c55b52f78710cef460cd1ed7b94756f4865ed80d1ad71a5ca523edb4248cedbd7d069ff47cbbb1b8589668ce287e743e131900e16c05f30359a8a3e73386045d3094868f4f24e3bd55239c0ff5d17b28adba0636e0e69cfa52012c0c1b8a3a58e2ab6cbc082387a80f58ed05eb74f6630515d742504e39718637264a54f860b2022a755c1f5c9a4fda65d50e78dde67834206a4fb41f5db\",\n \"registerContext\": \"qauth:register:v1\",\n \"registerMessage\": \"010b000000766563746f722d75736572200500000196dfbfa00d32dd79024cc5ef5fba8f8a855948489a20940032ae07974571ccd4ebfb4a4c95c504aeb0113a0689c0c06c4e3a43a923dfb0af06d8d71f27a017ef8547598e14ab65de873620921ca79417b39f9457208b77efac7bfa394ba85fce3c47dc1ed6bed672cca4745a6988bafd89b95117d2aca531ece00cd5681b31702e99fac8a68a1b03a727abca08bedfeaf9d47de33069ad52a5a5ad1faf102e431d1d1a9902aafaa4c03a13cbd265345d34440fcac6a9c42e1f0b4fabf4bd781cf2324fca9ba9a49328447737546197b7378ca3aec327db79500fd73a4856e31b2c7507a8168a65918197ddd139055f67a95edbe94d229b1617f3a7a177742fd4a809326ea84bc88054e0e4a9586c6f219f57ce229f3c770a64ee94bbfa5d49cc2be002b45359424da064295372270ffb6eceb4301155ef9c1358c1afa63015dac4bebbc15e510c6f7c80537c4d3047d8eec7239453f45b5ee60463c60521ad322e233c18ad20f0d0e311afc55613f638391d3714aa47c704f49df2acce9cb53bef9f5716f451071a321286401e12b5917f382a52df6ae99aad0e97fb90be9fcb0daa305836c778193161d7c15cae3e892b5ece77b32c8c7f7b25ab5bed20dd49cbfa59be54a65c1c009edffb5c2282ce0d438225bf663fa89a9f1d28562017ad31389137b25d760b3f705932f46c4583ec354057561f38554f15f3f2a6e3463a295d06f610f3dc2d104bdfea5a340ccc0007e335db83e8ce11e3ec7d8fb89ee4cad7fffadfd7c2650c9aca13c72182f0d5e431a4bc0f4136ecaa60ba1dc3a8c81f25156d0b98824e69ed764af523aa02dc70401ba6d7887d32ccb949d86f3f8d6e5ee6659067a15557f8fa760a5799b865fd0aca03686d337832363b672807e8e2fd93197eb6ccc2d73e56422386344260f9c82dcf9adb08482428b604ffe1934f4f5eb4cb977615f9aae744d335ac7e37d90b8031212e2e37ca1ef64acbe5cf3f377c1b7a98c9a9c5fe563882cfd8a31c1986d0b801d016a428d31d105e1f2b8897bd8ef48f6833d39fc3e3ea7c5d39d747351fa4fceefd5ed3aa5e016289e74db7e65c5cb2125070e3e300c0c53c63243002825751f9e9f6584aec77cb87d3001160c3c6930e7f215da3936cdbdf430c65b8ff252185e702385903dbd98fe72328e23f242e3adf474f03f81c89bb6ab3e84d082ab13864707fadade3e563af0609b918063ecff63b56bdb980b0bfe404609e25fd74cf951abfe501be137ac2cdb472133ee0bdf0cd969732acd12bf7e07c07b3e14251439f7a714250a50897354ceb68f0c0448f1d2ff989e33c289e8ee646543112135d7229135f9b972ea2219dd0d182f21c17820a7c10803634387311ebe49fb2f52a1c858f6354a2e965463ddb0d4249b321f863441270718eaef54f6cfa81bceb2237de10e26e0257ad8269f82fc4e4252a691549d438367bcffd951de644ccd0b5bd4060288bb6d160abd0e604324e900d06b9c72497180cc396d18132b8718f63e4369848ede93bc812b702daaf6247d788ebbb610cb6b08d971c122e86e5e9f4f137de0bd88abe1fb1fe0abf9823f51a25ede0d47367789c4b5acf756e671252cabedbf66c7ae7566f0cb78cf969ae0c55b52f78710cef460cd1ed7b94756f4865ed80d1ad71a5ca523edb4248cedbd7d069ff47cbbb1b8589668ce287e743e131900e16c05f30359a8a3e73386045d3094868f4f24e3bd55239c0ff5d17b28adba0636e0e69cfa52012c0c1b8a3a58e2ab6cbc082387a80f58ed05eb74f6630515d742504e39718637264a54f860b2022a755c1f5c9a4fda65d50e78dde67834206a4fb41f5db\",\n \"registerSignature\": \"6c27811dfc2aa7719cd0a8b1fc9f4ec98ee140f74f989b069994a5f8d5ee7894677d983ec6b367345c9a2b34e9545e74fb41bcdb81ede55e08c202ce8c93b7545daf6a18480d2cb3199b0522d041c943aa59d351972596d13bed713deea47509db04ba2b0de43df7d06290a3844e0beacdf35a72991c480391e94d58cb010efd3e5a18e5691e4f152a5879e3200dc6700fe76740727cf6ac96a5d56995a6adc3bcf23885f5ba9c5fefb5eb0ae1602341008c569cc8f00131f2dbe776ac534e83a4061909d5aacd515689ecda1ad64ea79b4a17abcb9775a066171785914b3e3d3c95768f2d7c317c70d23eb83769e4baa58aed42fd0f108fb2c279b84d13275f2ce2bf875fea13ed0a6f1454d99f51e814c4ce088ce3013d98371d8ef91e6b11a5d235543dfc2019b89f597efabcfa834004bd9e803b0d9b2527686e531363477f064d6daaed8b1900511db59dfe0b518832f845d735817f7590b2bba936986e22b50a1d8d151ec814c264a9070c97540f29c27b1340670430c2b0d8d732bbd538bddf45eca9fe8fe714437455f433c4e634f2872ebb609e6800adf1a4c72e3b9bedbae0e865e3cc612e6b675611683857dfd83f9b87a46b583199ae21560a64c4972e73c87a03ff5389d8f70356b1f936533b5db71c9440ed581efd8c92c0d19eb91dbc92c885bd3e5714bd241c80afa16d24a0652250ace564cb8900afe3ae1abad83ccdd8b87ef9368c38fc4e6bd70d003803dc7606e97863bbeb04b7553de55f0375ee380a94cd088080b1e9c72ed8556ee8c76091057432329e2b98cc5071de8bb70cb8457a9bcf022e036ca15218abb538210c027223ae30cf5e9eea0736261b6f55e39bd8b8ff87f7fa72691541ec96f8e4aaebd48f6fb57195516cc585d2e7ff79ae8ee6f8fa91f33239af9e03ea82e77929e12f406d1cc042d08e07a12e469cea8562644600c5deaecedd2345b4696e44828f4269c0545c35dfb5c80f5c8f2674cfcc75d82134cc74124a2fb93da23f9e4c972bbfa032b34c7e8d9424fa6501970a230030e3387e30778b27412d7a0d875c94f6fb25c83249a0aac60e173c914b722ffa29dd1b949e707e1204ebeea994735e0ae23eb5a90b4dd109a944118cdd27d83b6f6b839d079227d151edeccf2a71f23583b1a335af12070ebb3accb62c3af08542a451ca97442916d027c7040ce41807b0720f1e6147fd3506ba12b3f9facc108554bb0258e71f3941baf370a2b8354a9a79fd8653d7ab39f0ee84e54ebfe1812fe9fae7d1b709a1d62585bebfdcf2bf476b62cd57f8a228551442fa864dfcf551b06b040531db2135c71266297580d3ffd9f77a2bd34739f0dd064f69db9b67f2c59149c6812453f185df10342964c9ad85d4893b0a540f002302c6f1c536f992644df64317114a40f433d4e92bc6deebef1e54b8d1311ba2cc253dc787e40a9b1ff165cde010c41bc75b111ea334005505aa0c399e8a24d2a0a07ed2afae6a8f34317d79615420ba6454f2b398f35982f44f9289f613bdbd355fd519173014bee71ca3654c553628df1b5daa1304f8bf0d57c47b9c935946a4e614e8641bc9803713ccd1d2c6ca21d38b6a1eacd2c3f9103718f16e664b0e5e993b163f1047bf3c1c9b4c8b190bcc2fbd5958c7aad02a41ccd81cf25cef48664ce6f7d2850a3f3ffef3318cbf28f33baab561e2f3a055878a39a48029e333e86f6df7b4f3a6edea221bbeca04cef965b72cfbf3be5117fa956b24f707efbf5ba4757ff2c88a699cb6d8bf1f680823171cdefd7711f414f06614ff666b46f512ed0b81d5f9be6106f029df88d21746b6e98c7f08021a1901b4fb82178c60bec557589b99a13d48891f11c1b005651d860664289bdf81e592cf47f88a1366e119d2490e5d370c23cca098d89d7921471d389b0654c49c5ccfeec02c377a5cc1c6f8a59f14337e19fcf2b62567b002199c1275f049be2fe9edacb7a095adbd8d0772b1043c8252b65f20d166d1a13c1c33e76b8d42fee8bb7e414196da7ab93095395fdbb2f8d9e8193241c87f5f398706d6bcfdc08984876861a8e3c9270ea678d32fd176e17bd81876a94e7bca8814edaae731cae1b26a03ddd9a61d8d02710f8c3f435a9c4ff2afe6255ba334588c006ef49cc752916cf6afb4d525e04b201ee50e0453bd8ae9cecc4ee66d09c23c9fa087c8a932301c9274ac2e4095c110e25eca935b924c4cd3ff3e9d78e3d19220023f412eb02941cd0d9fee332965571790811470f1cbcf3fa97b8308623fe91225c174396892137d6f1c01d76c865f6d304644f15940f3feab5c1be0984ebbf87be21c5e4b293f76fd88b7554f7db5cfa246775d007a31022c0923ac47d2b762e443b8f6170e898fa8cc82727722c5d4bdc8e41885dcb86234bdb5d33125c585a5116fd6fa000fc809599e958d2f3a716426af8b539d64f6e51d10bb2e6877dc7aa7ce41dec7ddff265989132481d143dcf5b367a3dd9f4edef333ffae39d1ca712a375376c9e3ca9f15888ceb3761f2b6519a0221dd9a0a2b1fc534042bcfc998436af71f297a53f981a5dc6649b5f3123db4f0b897b8480420db829c49362fb9b63eb1e44a272fcc30a7d0f8f5f1b80917c6fc42ea6af937faab05a808034d1cd780f9e3935c5a98d048fc09911707f3acbd4d3e3b001af6c099828235c6c821daa5380b389ff223496cdb4740ac604e7d1c0b83f30a0ace1dff2e9c8d9da31f42b58f59d23ddb8a83fe22ccd1fbf59e99ec305711d55d7b56198700d30c5c1b8dde8012fdf7686a4076529b29ecb123e3d64b59fc066f570ff0d936f9217a20fc6fc188b12c7277b94b3fcb4b45023bd6eafc4f2ffde842e7d6ee4344625359881e973e680448db627caeba3253e70fae5917177ef27b4a97096a1738adc5f256fcef120497605691b1270a8a19faabbbc8f67fd2dc6b00d32d391255a6a3245b69650fbaadb12ea677b40ac6b87b2a043f5903672992c49c879a80ffd2e3d812a2379ffd9895f25535ce189d8ff3beefeae6907e2a4f1e0089302279af453e2393f8fe8d4142e5189ec676978f8583eec0ea75aeed093f32827049604117f2bbe9eff5b473889ff89c1e33160b8b271a40df6b0d4345de0bf04bd567fe55f65305032ee68afd5c417102826d91dfbb9f7374aafa66d70413c1423b811e58a71715b0c45ae41343411318d327bdbe2a24d986b4f4c1b52b8dbeea99c6abaccc24ffdd0a2bd7a89cca0cf5487bca393ab653a161944c4b38648718461e1d62ac400343aea6ea27ffbe4e47dd92272e41557e828ba7b8c2d8e9ee245058656c6d73868f98b2c8fc040a0f122339485a5e8b9fa5caecfb001c3a49535a5fa4ccd8e4fa0000000000000000000000000000000000000000000000000000000d1a2935\",\n \"kemSeed\": \"606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f\",\n \"encapsulationSeed\": \"7777777777777777777777777777777777777777777777777777777777777777\",\n \"kemPublicKey\": \"cfc608c61500c0964798231d9552cc0091107087c0476ca810504b4909bc24f7c65d587c11e03eaa947fb76724ad7804279b4df274b7dd27c70168921f5c4b4fc74a06839ceaaa2b46d0b9e600bcde12622c411961db4d335491848526ca8495ee3c1f200556385163541540e94c3efa96c9fde23d4ea9c0629a556d1038cc72276b48bf4914c97b1638c1a129e1d059daa60cc1d5139d115fde44968cdc6112d4378e19baed39b0da7a293528ae9e3c86a846ad018a6b73a10b04f41a05a54116fc0b86a1212692690db05ccaf2610e0803c9c10a4763aefe85cc09b795b2c00fc915486bc86b7d120183b8bb0cf63704a6299163806f918d6021a24ab88d7fd1482709b359778b40115c7e5121510055597a73ed48a125a9265474bb7a16b74bfa2409a8cd4fa606b4d1afad36cd9e0c24661a69c7c60010b470a911536a53b28ab132d6a675576ab50835b24fcc3a6680848b986a6694476b09934310a5d1943f8eba21bbb3b386c223085722aadc646e5670ce2b73ae84bd53bacb8ed1b469972d88323cfae548c2971a695840c7560b56b05427042aeea13eee4815a8b22728aa586a724ddbb92d17a12180fc00ba8c7bdae3caa35cc8bfcaa23c0436339491bbd67bb44b16cb85b6eaf16c48799603b17124e49400414170fa63505814ec012279420281501bb5fc63879c44cfc952f1f2a704f3c3d72cc711d8464c898f48135fe29762c70907e6b6486cc71a832b4caffb95232190053a16c843ab9a85252ba2c866ca196d4bba50923be7a95904ac89674aca6d98541282949856cca5ba4a7018267277453f9138680a8bd8037746e242bc7c3881bc0d4f20af2f537a7d70921ae017d1e00ce1d4c2b502c8d2a73c1c4539333514d615357c2b4a9106b744132b20cb2c273296f2780609f2bac6858c36747e597722a1d34e7189af0c18bab44a1f3d0a6d3c274e104c7943c529ce882bf8783068590cac181a3ed272cbfb3405c2640940aba5a255f40b988416a483b24bea84a30bcb4d838325814724b4023af8b6401922451a1097bc92bbd65cb28c4c51ac8aceafc4296e0c6d61e4b925fa6d6e987cf9142c80d33fc4e7869c5075b533331b92204c97bbccf9ac16b992d14400e4012bba144235e0ab62288cade65692519d9bfcc2c1ac385cd3a6fcf06e8e9b12c4ca301447259f772ee2a0782776b069dbcb0e17c784e44e4ef341c38037e8aa8d5c8b80b4f6181e2753abc843035b5786e997f109ae1c3473067a301ee11576223562610cb540bcf155554787237c9318d23135c56151a0916ccb31b56a84303a9cb91273cf09420e6eb71aeed33295d726d84803aa76ce047929b2234c2dc429752072adc9926da83469a7770705244273cb96f5b5504c6b45f30d7f4620a1c17dff728dbed0281c9294b5db8c0de0649dd9aa70f660c155523447640ffc9568691ccec667c07814045244bd4697dac3c7b1ac03f57581a6c71296039999273ae226be4b74364377c6f970218c5347b4f54fd86c600fb23cb1f4be848a8e602900fe64358cf58702e656ce7c8b448427789306f63582427533e8787c99cc7aaf4926cc5785ea933d8a573f80848e7c932d1b729cf1aabd4f06a8c6793702abf4d273d93b6bf67c31b9057f1c468d6f314d495f854f4a6b\",\n \"kemSecretKey\": \"afbac9549b58d5d0b73f05375b3a5558572d91c19dcf00b8fe285fbdd03f3d48064437ab05071f99b69a99eb60b46161db0b2ca4dc25b7a0c917d5c6296c23aa401fa33123fc27a0457373cc760a1a88bd4ec0b94d0b1827d239c741762aa54bbf6a39b4a0352c92beb1a5515ac40bf5c5373e183bced003e02b63cc04c7d67638f0b8b50e338b1760782890261cd80092c6a36dec180a99c435150ea3791130a75222eb12334436ed6c410c129807053e8fcc66a6ba876aa3393432bb3171075e5cb723d2b9d7a51fd18b8ee660cef67b3aba51c56e4c045eb98eb8658dc61413dda153b49803710ac70d1b44a3554007388f60f370d0a125f3e8b95bd208037b39d823a70d3479bb3b9ce1ccc4ff49150f14666efc49f04c66f91999fb642cd338c99d63b236691e43fa7002a74ccc382635c444947490e284cdadf860cb323c627445d780c8468105fcba8cb232a620ca9f51aa61515ca1c6502df1b8aa4051660101c45ce9ced4a1bf5eaa8f1cb8c54754c9cce195af2a20cc030fc4c15f2bc06d3de23b6576c66f1c601bf509824c6312938619332f6c7a420d3b729c866e84d43cac7c70d0e964dbfc68ea7c9082d329e1227d17b490858635bf4770f96a37f8405371dab84ba43f0714c39c90c2053c4a394671fe58ca11cb3e63bb666637bfe907943af9c044c47c56676e13520e3cc0843f870dd0e1223995c34821c10ff8be7a0522df8b1dc94c34e4066f3ce79833f3c874c03b6ec29f108c8e0c3b65c4b4c3848995e66a3a18a4842de1a60eba5e4b00a0d4273b8f5260b3d75ff154cb49e5b2557cb66654703c5150acdc169f07cb0bc539494517c3b309654c043170216f113b60270a463c8a9cd0029758567087aa176b60eed2349af64beb73002c83313ba1778b2ba0f915b204eac50c994d2d337d8cf7cedb8680f3a617891ba84717435e512113d267fd73608a8b868fe826b8fc0fb526c7c31c5a611294d73137f66517c1cb6676b1974c13aab7a76efc30af6b28b92af4a57ebb9fcf420c391710e7889d67ebbd4446675b825471d6727895c8814351a4617050d9134fccbb07babb6651219f009e86514eabbab032d93568955bca83a155f278c3072ed8e1874594c9cd66be00865fb64bb9ecf116ba70198f468d414888b3981c19bc1c64639ac4c1348c13bd4e724855762725122e29bc2eea6a615a926e0a035043d9456a1a7e9f7b4670c52159782896b9933f8b638720303f13609bc030f8169597c92b85bab6592a9a2ccb0989e91f911134c2669ba22cc04c5b4ab8647c3f379d84c7783ca864bdec2a184c33bb781ada71c5b7412fd27b069e5bbced2017f1c8888102d062895fea5385e7262bd349c914100c74c661ac865432639762f698a2c7347f7c42bf05156d730cec070513b4018962bdb78990647a7fcd63606ef38f8fe29fa7b14b5c38b966403436c669d056c56aa6c2a7b15558815c8525262adc941cf84d9c0c77e2f6b232a5a0cdb2bc2a39bb72271b1ebc4323f58e64059f41674a3ba63067844a599007bad83cc8e47d8905be32e052634624c4232eea103fcaa384769a3362386da59c96eb2527b60b3849776637c594df176753414ecfc608c61500c0964798231d9552cc0091107087c0476ca810504b4909bc24f7c65d587c11e03eaa947fb76724ad7804279b4df274b7dd27c70168921f5c4b4fc74a06839ceaaa2b46d0b9e600bcde12622c411961db4d335491848526ca8495ee3c1f200556385163541540e94c3efa96c9fde23d4ea9c0629a556d1038cc72276b48bf4914c97b1638c1a129e1d059daa60cc1d5139d115fde44968cdc6112d4378e19baed39b0da7a293528ae9e3c86a846ad018a6b73a10b04f41a05a54116fc0b86a1212692690db05ccaf2610e0803c9c10a4763aefe85cc09b795b2c00fc915486bc86b7d120183b8bb0cf63704a6299163806f918d6021a24ab88d7fd1482709b359778b40115c7e5121510055597a73ed48a125a9265474bb7a16b74bfa2409a8cd4fa606b4d1afad36cd9e0c24661a69c7c60010b470a911536a53b28ab132d6a675576ab50835b24fcc3a6680848b986a6694476b09934310a5d1943f8eba21bbb3b386c223085722aadc646e5670ce2b73ae84bd53bacb8ed1b469972d88323cfae548c2971a695840c7560b56b05427042aeea13eee4815a8b22728aa586a724ddbb92d17a12180fc00ba8c7bdae3caa35cc8bfcaa23c0436339491bbd67bb44b16cb85b6eaf16c48799603b17124e49400414170fa63505814ec012279420281501bb5fc63879c44cfc952f1f2a704f3c3d72cc711d8464c898f48135fe29762c70907e6b6486cc71a832b4caffb95232190053a16c843ab9a85252ba2c866ca196d4bba50923be7a95904ac89674aca6d98541282949856cca5ba4a7018267277453f9138680a8bd8037746e242bc7c3881bc0d4f20af2f537a7d70921ae017d1e00ce1d4c2b502c8d2a73c1c4539333514d615357c2b4a9106b744132b20cb2c273296f2780609f2bac6858c36747e597722a1d34e7189af0c18bab44a1f3d0a6d3c274e104c7943c529ce882bf8783068590cac181a3ed272cbfb3405c2640940aba5a255f40b988416a483b24bea84a30bcb4d838325814724b4023af8b6401922451a1097bc92bbd65cb28c4c51ac8aceafc4296e0c6d61e4b925fa6d6e987cf9142c80d33fc4e7869c5075b533331b92204c97bbccf9ac16b992d14400e4012bba144235e0ab62288cade65692519d9bfcc2c1ac385cd3a6fcf06e8e9b12c4ca301447259f772ee2a0782776b069dbcb0e17c784e44e4ef341c38037e8aa8d5c8b80b4f6181e2753abc843035b5786e997f109ae1c3473067a301ee11576223562610cb540bcf155554787237c9318d23135c56151a0916ccb31b56a84303a9cb91273cf09420e6eb71aeed33295d726d84803aa76ce047929b2234c2dc429752072adc9926da83469a7770705244273cb96f5b5504c6b45f30d7f4620a1c17dff728dbed0281c9294b5db8c0de0649dd9aa70f660c155523447640ffc9568691ccec667c07814045244bd4697dac3c7b1ac03f57581a6c71296039999273ae226be4b74364377c6f970218c5347b4f54fd86c600fb23cb1f4be848a8e602900fe64358cf58702e656ce7c8b448427789306f63582427533e8787c99cc7aaf4926cc5785ea933d8a573f80848e7c932d1b729cf1aabd4f06a8c6793702abf4d273d93b6bf67c31b9057f1c468d6f314d495f854f4a6b0d24c71384e7dc44c7848af6f8181c782901dccafb2c4680ba1612fc7080cb61808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f\",\n \"ciphertext\": \"7fd065eb73414ba1bd219f9074433b38c007e21f2ab4632dabae4877aac911e6cca0f85eb8f78ce9c59d52aa46dfbfee337cb008e05ce2fa538f5b1aceed16a85d794481dc96cd8422b4ead175db73dcbf28a4cfb237c366be0f8ae6fa9bc8966e25a69fd45b62838f3e1cac587a8f5a3b1876dbd382e70059480b9f1be3a000ea504d149877965a857708a5a2a2ca078171f90e87b555d5e2c15a8a0131223f65a10d8305121864b65339524989ef64cdc7d98f98a704f86858faf1f80267686493eff37f9323923332b99ec051a69ef078992177cd8abde05142975e9673e732fb82c3494fc8cc2755d6a44435f6df00efa825bcd61ec0d27df1b9712e8de2bd0f3940b7c5758b2c8d2086c56966e0d8c45c9bf5534babb9a1e613db9bfaefc92818a0c7396f3f150b14d90f7479cbd9ae8fb38b08765085865b392a85eaf5a280c10ac057393ca39aab76ddd82d507f091df7782979a54f5dc19e8b134ab3499dac8bc5efc1c3ae22aa62950b8688d5f29df0e07906bd24c80ba03853081ce6e9320c4336679890cdd0734b20d3f7001c116683108bc58f1f2000176949ffbb69349823f62838c5b3170da17dec43c9a76a3e9829abd20299f0f2205e7c15b3e9486f7a047c6818366026898dcea60658db0d7c5de634875c92c9926b7e3e4e23b2307537086194055760b96525ea9ddd9ae109ddc9ccc7b2e85312e6b07476775b199128f6cac377a12f47b1ac895f9b349015cdacbcab02497cfddeabb3fccf79834cb59a8365573b3bc4013aafb4e09aad347a45a357ba328564a671bb6eda63a1ce17e207aee25368e30430531aee71ea2bc14fd94b4a61401510a6080c59cef3b91f3e58581708a284d33872f8d232f3c0b075112efd3e45d7b470be0c387f5c9b9857b879416a9ddd5b0719d97da7ecde1ed187d1f230da76e5c004a18f13f19ac2562ff69f366531a9587fafe923cff1174de7b7ee9b5fe9bea17e503760526684ba6b8b22104f04521d2207bf1ad23fbf4faf8c09749fe0db983f38bb833d7aa87e68b39be6a5c6f0f1b18579ef77a0cc9fd6ccc049f814b8e05898113bd284e388acd90ce68b765c2ac353d5beccf7b782e28a389c0765e22129e85392d3ea2c78377979118c06a0703b9a003646188a6abc5c3d8b3ed5040888e6cb21e91efa05b4583b33428b54bd7a7bfc43c31e163b034b6f50b492ce50d23479e19ad185145bae009bcd4cf29c6fb09e13f4cde4e8e1056e46f4ea07793b8c017895609f4d7bcc648c7d28ee47cc7d08674f43f6e046ed39cae0dd09cdeba551d35ddb85354b51f28004c999c45d5d9e0505e10465499ed7892392d7b180e594d6cba00e6a7731d454d23a7de4b31cc7b52a28b82a37c90c23f7acde352e393ca01217c6260c227a672b04848ef4125cc5d45748c4f41e1c6e734cf7a5d0012562211284bc2ba4c1e89f74ee48d12ed50c86fa5c1543e70f0a47a14e5e83790cddf21890c5303f68097be83d68c78237d9b843ce591d9ebf3cb1dbc7f63d\",\n \"sharedSecret\": \"d931c1f4ae9543efc8bfd3c2d1b5f1c099b4d0d93e8669dd66331ef647a03964\",\n \"serverKemKeyId\": \"2d8e7b15778d1ebafe8679ca00b6830fce21c17fdbab62f7399a1dc279e8d239\",\n \"cid\": \"101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f\",\n \"nonce\": \"404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f\",\n \"iat\": \"1700000000\",\n \"exp\": \"1700000120\",\n \"loginContext\": \"qauth:login:v1\",\n \"loginMessage\": \"010b000000766563746f722d7573657214000000766563746f72732e746f696c2e6578616d706c6520000000101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f20000000404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f00f153650000000078f1536500000000400400007fd065eb73414ba1bd219f9074433b38c007e21f2ab4632dabae4877aac911e6cca0f85eb8f78ce9c59d52aa46dfbfee337cb008e05ce2fa538f5b1aceed16a85d794481dc96cd8422b4ead175db73dcbf28a4cfb237c366be0f8ae6fa9bc8966e25a69fd45b62838f3e1cac587a8f5a3b1876dbd382e70059480b9f1be3a000ea504d149877965a857708a5a2a2ca078171f90e87b555d5e2c15a8a0131223f65a10d8305121864b65339524989ef64cdc7d98f98a704f86858faf1f80267686493eff37f9323923332b99ec051a69ef078992177cd8abde05142975e9673e732fb82c3494fc8cc2755d6a44435f6df00efa825bcd61ec0d27df1b9712e8de2bd0f3940b7c5758b2c8d2086c56966e0d8c45c9bf5534babb9a1e613db9bfaefc92818a0c7396f3f150b14d90f7479cbd9ae8fb38b08765085865b392a85eaf5a280c10ac057393ca39aab76ddd82d507f091df7782979a54f5dc19e8b134ab3499dac8bc5efc1c3ae22aa62950b8688d5f29df0e07906bd24c80ba03853081ce6e9320c4336679890cdd0734b20d3f7001c116683108bc58f1f2000176949ffbb69349823f62838c5b3170da17dec43c9a76a3e9829abd20299f0f2205e7c15b3e9486f7a047c6818366026898dcea60658db0d7c5de634875c92c9926b7e3e4e23b2307537086194055760b96525ea9ddd9ae109ddc9ccc7b2e85312e6b07476775b199128f6cac377a12f47b1ac895f9b349015cdacbcab02497cfddeabb3fccf79834cb59a8365573b3bc4013aafb4e09aad347a45a357ba328564a671bb6eda63a1ce17e207aee25368e30430531aee71ea2bc14fd94b4a61401510a6080c59cef3b91f3e58581708a284d33872f8d232f3c0b075112efd3e45d7b470be0c387f5c9b9857b879416a9ddd5b0719d97da7ecde1ed187d1f230da76e5c004a18f13f19ac2562ff69f366531a9587fafe923cff1174de7b7ee9b5fe9bea17e503760526684ba6b8b22104f04521d2207bf1ad23fbf4faf8c09749fe0db983f38bb833d7aa87e68b39be6a5c6f0f1b18579ef77a0cc9fd6ccc049f814b8e05898113bd284e388acd90ce68b765c2ac353d5beccf7b782e28a389c0765e22129e85392d3ea2c78377979118c06a0703b9a003646188a6abc5c3d8b3ed5040888e6cb21e91efa05b4583b33428b54bd7a7bfc43c31e163b034b6f50b492ce50d23479e19ad185145bae009bcd4cf29c6fb09e13f4cde4e8e1056e46f4ea07793b8c017895609f4d7bcc648c7d28ee47cc7d08674f43f6e046ed39cae0dd09cdeba551d35ddb85354b51f28004c999c45d5d9e0505e10465499ed7892392d7b180e594d6cba00e6a7731d454d23a7de4b31cc7b52a28b82a37c90c23f7acde352e393ca01217c6260c227a672b04848ef4125cc5d45748c4f41e1c6e734cf7a5d0012562211284bc2ba4c1e89f74ee48d12ed50c86fa5c1543e70f0a47a14e5e83790cddf21890c5303f68097be83d68c78237d9b843ce591d9ebf3cb1dbc7f63d008000000200000001000000200000002d8e7b15778d1ebafe8679ca00b6830fce21c17fdbab62f7399a1dc279e8d239\",\n \"loginSignature\": \"6503cf44919e53b9f1cdaec33720dd50d0713641393c904972061a21f1d9c5ed61cd9ef7e39a3a1be1dbed748936e35a1780c0bf2989c8c33316b5de264c9b3db35786adcf0f8e2b656b90fe393095385dea6e3bef30e8a0a12c77c9a9887be09ad3cf87878ebac6a2f6ef26a93d897bb4c76344b505e8e9608a6b1b74ce258664366a0ed87598308ff231c1b6ad0ce88b421872c771d9fb96938ba5d2928c68fbd28bc4fb2efdbde1183a7f4a8872120c6769dfb2ba2a675fc40e9317ab0a13539718cd7522dd10f3a13080c6ba6571c949b1daf77c93e6e8b01adf44bd577d08e9278e23d3e28fbf74270647bae0a00801d454fcab542d2b07094c0b2e776bf510209fb79633226a3ec33d33e0071c5206d2456b4a429261abcefd5f8694b24746446cc054b2c8e73e3c529d49182748073bf7d15239e4aebd8b0816e98bfa642b2ca59c9d24df9dfd5a61466e8882c6ab65025804a3c6019e16c5d25307f69573262e08a5c89d1df52c196e20fa88542b4d5580f4e149eaee49a8d9c87faa4732f0f379a6e35ec65ae7a1bdb61970c9da54cf097fba8121829d55f804966ad346ed7197f15f7e2e6f1cc30c58a7f31b9859dd67bd10cf7182874402d0ccad148ef3ada0688c2524ccbd61a259caab7a56508249c06a9c7c43e0e5d9b7cd66a12376b5b4e57199f0d09f3efaafafce1c6ed10ed5e59ab8e45106254f5c326bcb5cd1a018fa388690478d38c1995d3f362096e7711818b6fdf1abbaf315eb04d40c93b64a236eebbb4fc18a70ab40da0e5c2698ea2ccb7b393dba91fb91527565e493bc0bea5b2c28fef11e89d09003bd4dbc52dc09a7da25bc7ae495957592f444469270bc88988cc66a4202ce1041f52f62fbc4a173bf622f15f69885386ab707aceca2f778e4336fc1dce6b115dc3b20a3138fe702bd808c11f57e3078511716bd4510222b07f7a805dd76a912aad63837c29c6453f0a93e0daad59e90a033dca445d3b45158ae1906bb735b13007c1ea3b2ce89e1d079739e7c064bf238a12184f54a3232626e20271bc2d0fdc252a5a20ba0e3e983c8a2f7026cc4d357dd0149ae0f611aada234d1d0c627890b692a0bfa2e6d5ae9e716c0c518e563356d9f600b2bb095a30aea6083ce1032605d929e804974a21327df62af2950775cd6a9c33684a56132028b92340b932a8f42e11e0691d2de073ea4cdc15af91d557f65f4b4e0ac349ae981afda623fcb629ff89f11bb5cd2d7dd2ef8c456d043b2275f7deb51d25d83192ac6a3cb21b33f6d52b76aed404dfbd6164a179b21883d1e11519cfb8a52d48542e215401a26025984ecb852068551890f94fde187996d2f86a770ed82fcb34e4bba1abc5a037201b67b90bff999414424c90561bb16115319ed8726a315602cc95694b39292b7b3795e50afdf36c8d6e4feb01054a1d00bd14a21b616d19ecb66232275f64194a12bd2772ccd8cbba3e3209efea23661fd5471016f8d9003dfc2249c14f4e01164e17340eeabef475f57b2af5a1c6d2e8d8461e3667f45d18fcb712e4f1e27904e0540b0e1ed639b68bb50a5217e0e67ccac153fcd4658c1ec03d2374388a29c22b19fd8a38b534e98d2f6d3021b7f8b08a681a5b0d3103182d78ac0caed6a2ae60759fbc7f869ea0cdec59b88f7e450c1a3a103c31e60944eb0814abebd01b0752e74d8ddd3e12878b4b158ec0695b735bc6e4eb2ce0da6cd79a356d69919e40bbaa38baec45838645e8ba21d7f538fc0b8dea1f701baa8a2e537ad66bea93145d30504c9046b9d404ebc6a1be620b250170916a7c11211ad939eb8e75dc466cc70a33546f02b80e0267113ab0a466a659317d9ac3d18962df77fc738a796094cb75bf0b96039c97de0b06ad376ce0830bea513512612ed3e6b44b9d6a45d5f4abf4a6189496532bdfdb25e2f16b999d2a3b8eb6225c85e47176ba1269c6f929b4f5c00e7b2b74fb9e6aab4225eb8d26f3e165d9ec3656a7558f82521939b3e6809124c88b54a15b520511e79425c8306f2239dd95fd0f6683aa25f58f3d1ee5ed135afefe2dface3d6e154370b379fd7d7690112dd872898350835bff2c8e5fccacbb115286b983fa7e052ae80ab158c6488e4a242539f685d354b8de242d0c7f9e9b6f92219004d16f34fce6a69536e76f39bee6ddb971968bdd5b93b12715018ae9060861195f0d827cb1088106c14662b58ad206c087b1a8925cc6f4e4af621bc67f15cdbf63fe76933f07619658e92dc19f691a8c1e5dce6f59af7258a9ee02f2ee863a687768200707d723c533d604e50679b91835ffb2979dabb94f665953c03d3752af3dfe8b36c36c3f63f6f0dbe46023eba5fb14aacea0379fb35f110caa2249c077c37fd5c080a82fb18c5abc5d1ecc84c6eec8fb32d89150e077db9c6b9b7869fe35f3ac42242a9dc7825da074c9898403b7395d9b4d701cd6a04dadbac86636df58c05b07ead01f189114fb0798ff3e6736cbf354f681416e29a1295c4834899ad6338ff662ca255574cfd80cb489d47f4d43e0860fa4a334affb66f492eedff606ae685e84608177ebf6f04f1306994f12a5f8b4b534c5c1daf646aee019c4f56b6c58a993b534375905f42f7b460e71fa8cfd71834cfc9d00ce2f66abfd57d55e3917075e03e1a73640f9ee56488ee0b2889d1829fcd2167a0551c64848c584eef0e313b020c6760b1966a4180551298dde0c2297d72cd8a81b28f3ec9f60ddebe86ee053a94c90fd71372183c4c13ffab1c7e5306c147ff9731cb622c7ee9838f428b278197a58ee0aaeaa7d13c0b11a69fcff8c622decafb6d93a221afa0ffb0425ffd38b24bfe2569f0eabcd0628837e7e1c3a3b1ba05525385450cb65a507c209d40859f6ef214f240892c521fb85fe9447407bfe2e24c03405c71cbca20ee5f183d49634d261fa76a1815c3d41ea1538ac1c8eb851eaeafda2301c5aeedc6455af80ff0f0522ee5a95135e5f0df174ba2064701d4310d3c4e18390f6cd0703dbb2244c2509c6bbd57d598979815e09e0d8de53922ce272c9f19fb4aa0b79df37dedd072df71fc9c9b6dc8d18cb17ec5b977129f4e6b673f0c09f561d8a77860ec5a57c943252ffcf239bdea13cbe6d39690f050089df1cdcda8616f8d96df9e5921d9909f98dd6671188fda09d3f97ab0aaefe341ecbb36253e28033400817e5d5825ba050b1fb7e2a6b32d30a8e2cc739cf2bcf3440da5ce3ded927c0b4416cbaee75c4f01d18a78350480755705b464f6ec8671dbff89b06a257015139905768608381f5003041e2b3c3f405464697494d8e6e8fc2d324446606e8693a7b6b7b9bed0eaef00030a18374e596369757f88bbdfe4ecff060d1692b1b7dedfe1e8f300000000000000000000000000000000000000001020313c\",\n \"transcriptHash\": \"d7479af6f20ef5a9a4ea4762cbb114deede86914e2b10c3143f7b71b580dde6f\",\n \"sessionKey\": \"9dd0eda782ccb42ddcc18bbad90f6ee8fdfabac18baa509f838cdfd5bd77de46\",\n \"serverConfirm\": \"ca07bc732387c4799a64437dc3562157cd4f20ba494186e6cde53bc3fe53032f\",\n \"initialUserId\": \"5b286ac280f592bab0f14685d29c7c5b1553d064564ac330d3fede736ba08820\"\n}\n",
|
|
11
13
|
"backend/data.md": "# Data types (`@data`)\n\n`@data` turns a plain class into a typed value that can travel safely between your frontend and your WASM backend, and in and out of the database, with both a binary and a JSON codec generated for you.\n\n## What `@data` is\n\nA **codec** is a pair of functions: one that turns a value into bytes (encode), and one that turns those bytes back into a value (decode). Any time data crosses a boundary (browser to server, server to database, one WASM call to another) it has to become bytes and back. Writing that by hand is tedious and easy to get wrong.\n\n`@data` writes it for you. You declare a class with typed fields, tag it `@data`, and the compiler synthesizes a deterministic binary codec and a JSON codec on the class. The exact same class is also generated into your `shared/server.ts`, so the browser and the WASM backend agree on the format down to the byte.\n\n```ts\n@data\nclass Player {\n username: string = '';\n admin: bool = false;\n score: u64 = 0;\n}\n```\n\nThat is a complete, serializable type. Note every field has a **default value**; that is required (the generated decoder and the client constructor use it).\n\n## Why and when\n\n`@data` is the backbone of almost everything that moves in a toiljs app:\n\n- **Request and response bodies** for [`@rest`](./rest.md) routes.\n- **Arguments and return values** for [`@service` / `@remote`](./rpc.md) calls.\n- **Values stored in [ToilDB](../database/README.md)**.\n- **Sessions**, [stream](../realtime/README.md) messages, and any custom payload you design.\n\nWhenever a route, an RPC method, or the database needs a structured value, that value is a `@data` class. You will define these constantly.\n\n```mermaid\nflowchart LR\n D[\"@data class<br/>(one definition)\"] --> R[\"REST route body\"]\n D --> P[\"RPC argument / result\"]\n D --> B[(\"ToilDB value\")]\n D --> S[\"Stream message\"]\n```\n\n## What the compiler generates\n\nFrom your `@data` class, the compiler adds these members:\n\n| Member | What it does |\n| --- | --- |\n| `encodedSize(): i32` | Exact binary size including the 4-byte type-id frame. It currently encodes the value to measure it. |\n| `encode(): Uint8Array` | Serialize to bytes, with a 4-byte type-id prefix. |\n| `static decode(buf): T` | Rebuild a value from bytes produced by `encode()`. |\n| `encodeInto(w: DataWriter)` | Serialize without the type-id frame, for nesting inside another value. |\n| `static decodeFrom(r: DataReader): T` | The matching read, for nested values. |\n| `toJSON()` / `static fromJSON(v)` | The JSON codec (large integers become decimal strings, so `JSON.parse` keeps them exact). |\n| `static dataId(): u32` | A stable hash (FNV-1a) of the class name, written as the type-id prefix. |\n\nYou mostly do not call these directly; routes, RPC, and the database call them for you. But they are there when you need them (for example `value.toJSON().toString()` to build a `Response.json`).\n\n## Editor support in TypeScript 7\n\n`toiljs build` and `toiljs dev` generate `toilscript.*.generated.d.ts` files\nbeside the server entry, including typed `encode()` and static `decode()`\nmethods. This supports WebStorm and TypeScript 7 without a language-service\nplugin. Keep these files included in the server `tsconfig.json`; the usual\n`\"include\": [\"./**/*.ts\"]` includes them. Run a build after upgrading, and restart\nWebStorm's TypeScript service if old errors remain cached.\n\nUse top-level named exports for module-scoped models (`@data export class ...`).\nFor a direct compiler build, pass\n`--editorTypes server/toilscript.generated.d.ts` or put that path in the\n`editorTypes` option of `toilconfig.json`. The declarations are editor-only and\nleave the runtime codec unchanged.\n\n## Supported field types\n\nA `@data` field may be:\n\n- a scalar: `u8` through `u256`, `i8` through `i256`, `f32`, `f64`, `bool`;\n- a `string`;\n- a `Uint8Array` (a raw byte buffer);\n- a nested `@data` class;\n- an array `T[]` of any of the above.\n\nFor the number types (why `u64` is a `bigint` on the client, when to reach for `u256`, and so on), see [Types](../concepts/types.md).\n\nGive every field a default. The layout is exactly the field declaration order (this matters, see [gotchas](#gotchas)).\n\n## Nested `@data`, arrays, and bytes\n\n`@data` classes compose. A field can be another `@data` class, an array, or a byte buffer, and it all encodes and decodes as one value:\n\n```ts\n@data\nclass Tag {\n label: string = '';\n weight: f32 = 0;\n}\n\n@data\nclass Document {\n id: u64 = 0;\n title: string = '';\n tags: Tag[] = []; // array of nested @data\n authors: string[] = []; // array of strings\n thumbnail: Uint8Array = new Uint8Array(0); // raw bytes\n}\n```\n\n`Document.encode()` walks the whole tree: it writes `id`, `title`, each `Tag` (via `encodeInto`), each author string, and the raw `thumbnail` bytes, in field order. `Document.decode(bytes)` reads them back in the same order. On the JSON side, a `Uint8Array` field becomes a JSON array of byte numbers, and nested `@data` fields become nested JSON objects.\n\n## Using `@data` in a route\n\nA route's body parameter and its return value are `@data` values. Which codec runs depends on the route's stream mode (see [REST bodies](./rest.md#request-and-response-bodies)):\n\n```ts\n// JSON route (the default): body from JSON.parse, result via toJSON()\n@post('/')\npublic create(input: NewPlayer): Player { /* ... */ }\n\n// Binary route: body via decode(), result via encode()\n@route({ method: Methods.POST, path: '/blob', stream: DataStream.Binary })\npublic blob(input: FileData): FileResult { /* ... */ }\n```\n\n- In a **JSON** route, the incoming body is `JSON.parse`d and revived with the type's `fromJSON`, and the returned value is serialized with `toJSON()`.\n- In a **Binary** route, the incoming body is `decode`d and the returned value is `encode`d.\n\nYou do not call the codec yourself in either case; you just declare the types.\n\n## The raw codec: `DataWriter` and `DataReader`\n\nSometimes you want to lay out bytes by hand: a custom body, a session token, a challenge message, a wire format someone else defined. For that, use the codec directly. It lives in the `data` module:\n\n```ts\nimport { DataWriter, DataReader } from 'data';\n```\n\nThis is the same codec `@data` classes are built from, and it has a byte-for-byte identical TypeScript version in `toiljs/io` (`src/io/codec.ts`), so your browser code can read and write the exact same bytes the WASM backend does.\n\n### `DataWriter`\n\nEvery write method returns the writer, so calls chain.\n\n| Method | Signature | Wire format |\n| --- | --- | --- |\n| `writeU8` / `writeI8` | `(v): DataWriter` | 1 byte |\n| `writeU16` / `writeI16` | `(v): DataWriter` | 2 bytes, little-endian |\n| `writeU32` / `writeI32` | `(v): DataWriter` | 4 bytes, LE |\n| `writeU64` / `writeI64` | `(v): DataWriter` | 8 bytes, LE |\n| `writeF32` / `writeF64` | `(v): DataWriter` | 4 / 8 bytes, IEEE-754 LE |\n| `writeBool` | `(v): DataWriter` | 1 byte (`1` / `0`) |\n| `writeBytes` | `(b: Uint8Array): DataWriter` | `u32` length (LE) + the raw bytes |\n| `writeString` | `(s: string): DataWriter` | `u32` length (LE) + UTF-8 bytes |\n| `writeU128` / `writeI128` | `(v): DataWriter` | two `u64` limbs (lo, hi) |\n| `writeU256` / `writeI256` | `(v): DataWriter` | four `u64` limbs |\n| `length` | `(): i32` | bytes written so far |\n| `toBytes` | `(): Uint8Array` | an exact-length copy of the buffer |\n\n### `DataReader`\n\nReads are **bounds-safe**: reading past the end of the buffer never crashes. Instead the read returns a zero or empty default and flips the reader's public `ok` flag to `false`. Check `ok` after a sequence of reads to catch a truncated or malformed buffer.\n\n| Method | Signature | On over-read |\n| --- | --- | --- |\n| `readU8` / `readI8` | `(): integer` | `0` |\n| `readU16`..`readU64`, `readI16`..`readI64` | `(): integer` | `0` |\n| `readF32` / `readF64` | `(): float` | `0` |\n| `readBool` | `(): bool` | `false` |\n| `readBytes` | `(): Uint8Array` | empty array |\n| `readString` | `(): string` | `\"\"` |\n| `readU128` / `readI128` / `readU256` / `readI256` | `(): bignum` | `0` |\n| `remaining` | `(): i32` | bytes left unread |\n| `ok` | `bool` (field) | `false` once any read over-ran |\n\n### Encode and decode, both directions\n\n```ts\nimport { DataWriter, DataReader } from 'data';\n\n// Encode: a version byte, a name, a score, then a blob.\nconst out = new DataWriter()\n .writeU8(1)\n .writeString('alice')\n .writeU64(1234)\n .writeBytes(payload)\n .toBytes();\n\n// Decode: read the fields back in the exact same order.\nconst r = new DataReader(out);\nconst version = r.readU8();\nconst name = r.readString();\nconst score = r.readU64();\nconst blob = r.readBytes();\nif (!r.ok) return Response.badRequest('truncated');\n```\n\nThe order of reads must match the order of writes exactly. The layout is the format.\n\n## JSON vs binary: which to use\n\nYou usually pick this at the route level (see [REST bodies](./rest.md#request-and-response-bodies)), but the trade-off is the same everywhere:\n\n- **JSON** is human-readable and understood by every tool. Pick it for endpoints a browser or a third party calls directly. Large integers ride as decimal strings so they stay exact.\n- **Binary** is smaller, faster, and lossless for big numbers. Pick it for app-to-app traffic and anything performance sensitive. RPC always uses binary under the hood.\n\n## Evolving a `@data` format: `@migrate`\n\nOnce records are stored, changing a `@data` **value** type is a problem: as the [gotchas](#gotchas) explain, the binary layout *is* the field order, so adding or changing a field means the bytes already on disk no longer match the new shape and would fail to decode. `@migrate` is how you evolve a stored type without a backfill and without downtime.\n\n**What it is.** `@migrate` marks a plain (free) function that upgrades one record written under an **old** version of a value type into the **current** shape. The compiler weaves that function into the value type's decoder as a version dispatch: every stored record carries the schema version it was written under, so when a read hits an old record, the decoder decodes it as its old shape and runs your `@migrate` forward to today's shape. This happens **lazily**, per row, only when a record is actually read (nothing rewrites your whole collection up front).\n\n**When to use it.** Any time you change a `@data` type that is already stored in ToilDB: you added a field, renamed one, changed a type. New writes use the new layout; old rows keep working because the migration upgrades them on the way out.\n\nHere is the whole story. You shipped this value type:\n\n```ts\n// server/models/GuestEntry.ts (version 1: what you shipped first)\n@data\nexport class GuestEntry {\n author: string = '';\n message: string = '';\n}\n```\n\nLater you add an `at` timestamp:\n\n```ts\n// server/models/GuestEntry.ts (version 2: gained an `at` field)\n@data\nexport class GuestEntry {\n author: string = '';\n message: string = '';\n at: u64 = 0; // NEW field\n}\n```\n\nEvery entry already stored was written without `at`, so its bytes cannot decode as the new `GuestEntry`. You add a migration file to bridge them:\n\n```ts\n// server/migrations/GuestEntry.migration.ts\nimport { GuestEntry } from '../models/GuestEntry';\n\n// Keep the ORIGINAL layout as its own class so old rows still decode.\n// One kept class per past version.\n@data\nexport class GuestEntryV1 {\n author: string = '';\n message: string = '';\n}\n\n// Upgrade a v1 row to the current GuestEntry. This is the DELTA form:\n// (old, into). The compiler pre-copies the fields the two layouts share\n// (author, message), so your body fills only what is new.\n@migrate\nexport function up(old: GuestEntryV1, into: GuestEntry): void {\n into.at = 0; // unknown for entries written before the timestamp existed\n}\n```\n\nThat is it. Old entries now surface as fully-formed `GuestEntry` values with `at = 0`; new entries carry a real timestamp; the same read path serves both.\n\nA `@migrate` function comes in two shapes, and you pick whichever reads better:\n\n- **Delta form** `up(old: OldType, into: NewType): void` (used above). The compiler copies every field the two layouts share by name and type, and your body fills only the changed or new fields. Least to write when most fields carry over.\n- **Full form** `up(old: OldType): NewType`. Your body builds and returns the whole new value itself. Use it when the transform is not a simple field-for-field copy.\n\n```ts\n// The same migration written in the full form.\n@migrate\nexport function up(old: GuestEntryV1): GuestEntry {\n const e = new GuestEntry();\n e.author = old.author;\n e.message = old.message;\n e.at = 0;\n return e;\n}\n```\n\nGotchas specific to `@migrate`:\n\n- **Location is enforced.** Every `@migrate` must live in a `migrations/<Type>.migration.ts` file (a `*.migration.ts` file under a `migrations/` folder). The build auto-discovers it (nothing imports it), and a `@migrate` placed anywhere else is a hard compile error, because it would silently never run.\n- **A migration is a pure value transform.** It may not touch the database or any host service; it only turns old fields into new ones. Trying to read or write ToilDB from inside a `@migrate` is a compile error.\n- **Migrations chain.** If you evolve a type more than once, keep one old class and one `@migrate` per step (`V0 -> V1`, `V1 -> V2`). The compiler walks the chain, so a row written under the oldest layout is carried all the way forward to the current shape, shortest path first.\n- **When it actually runs.** On any read that decodes an old row (`get`, `getMany`, a view read, events `latest`). It also runs when a [`@derive`](../background/derive.md) rebuilds a view on box load and re-reads old stored events (see [Views](../database/views.md)).\n\n## Dynamic JSON on the server: the `JSON` value tree\n\n`@data` is for shapes you know ahead of time. Sometimes you do not: a webhook whose body varies, a third-party payload with optional fields, or a response you assemble on the fly. For those, toiljs gives you a `JSON` **value tree**: an in-memory value that can be a null, a bool, a number, a string, an array, or an object, which you read and build at runtime.\n\n**What it is.** `JSON` is an ambient global class (no import needed). It represents one dynamic JSON value. `JSON.parse(text)` turns JSON text into one of these trees, and a `@data` class's `toJSON()` actually returns one too. It is the **untyped** counterpart to `@data`'s typed, fixed-shape codec: reach for `@data` when the shape is known and you want type safety, and for `JSON` when the shape is dynamic.\n\nThe statics that make a value:\n\n| Static | What it does |\n| --- | --- |\n| `JSON.parse(text: string): JSON` | Parse JSON text into a value tree (returns an error value on malformed input). |\n| `JSON.obj(): JSON` | A new empty object; fill it with `.set(key, value)`. |\n| `JSON.arr(): JSON` | A new empty array; fill it with `.push(value)`. |\n| `JSON.of<T>(value: T): JSON` | Wrap a scalar, string, bool, or array as a JSON value. |\n| `JSON.nul(): JSON` | A JSON null. |\n| `JSON.stringify<T>(value: T): string` | Serialize a scalar / string / bool / array value straight to a JSON string. |\n\nThe instance methods that read and build a value:\n\n| Method | What it does |\n| --- | --- |\n| `.isObject()` / `.isArray()` / `.isString()` / `.isNumber()` / `.isBool()` / `.isNull(): bool` | Test the value's type before you read it. |\n| `.has(key: string): bool` | Whether an object has `key`. |\n| `.get(key: string): JSON` | The value for `key` on an object. |\n| `.objectKeys(): Array<string>` | The keys of an object. |\n| `.at(index: i32): JSON` | The element at `index` of an array. |\n| `.length(): i32` | The element count of an array (0 otherwise). |\n| `.asString(): string` | Read the value as a string. |\n| `.asF64(): f64` / `.asI64(): i64` / `.asU64(): u64` | Read the value as a number. |\n| `.asBool(): bool` | Read the value as a bool. |\n| `.set(key: string, value: JSON): JSON` | Set a key on an object; returns `this`, so calls chain. |\n| `.push(value: JSON): JSON` | Append to an array; returns `this`, so calls chain. |\n| `.toString(): string` | Serialize this tree back to a JSON string. |\n\nReading an untyped body and building a reply, together:\n\n```ts\nimport { Response, RouteContext } from 'toiljs/server/runtime';\n\n@rest('echo')\nclass Echo {\n // POST /echo with an arbitrary JSON body we do not model as a @data class.\n @post('/')\n public handle(ctx: RouteContext): Response {\n const body = JSON.parse(ctx.text()); // ctx.text() is the raw body as text\n if (!body.isObject() || !body.has('name')) {\n return Response.badRequest('expected an object with a \"name\" field');\n }\n\n // Read fields out of the tree, guarding types and optional keys.\n const name = body.get('name').asString();\n const age = body.has('age') ? body.get('age').asI64() : 0;\n\n // Build a fresh JSON object to send back (chaining .set).\n const out = JSON.obj()\n .set('greeting', JSON.of<string>('hello, ' + name))\n .set('age', JSON.of<i64>(age));\n return Response.json(out.toString());\n }\n}\n```\n\nGotchas specific to `JSON`:\n\n- **Check the type before you read.** `JSON.parse` never throws; a malformed input or a wrong-typed field yields an error or default value rather than a crash. Use `.isObject()` / `.has(...)` / `.isString()` and friends to validate untrusted input before you trust it.\n- **It is a value tree, not a typed struct.** You get no compile-time field checking. When a shape is stable, prefer a `@data` class so the compiler catches typos and the client gets a typed type for free.\n- **Big-integer care still applies.** As with any JSON, integers above 2^53 are best carried as strings; read them with `.asString()` when exactness matters.\n\n## Gotchas\n\n- **Field order is the format.** The binary layout is exactly your field declaration order. Reordering fields, or changing a field's type, is a breaking change: old bytes will decode wrong. To evolve a format safely, add new fields at the **end** (and, for hand-rolled payloads, bump a leading version byte).\n- **Every field needs a default.** The generated decoder and the client constructor rely on it. A field with no default will not compile as `@data`.\n- **`encode()` carries a type id; `encodeInto` does not.** The 4-byte `dataId()` prefix lets a decoder confirm it is reading the type it expected. When nesting one `@data` inside another, `encodeInto` / `decodeFrom` skip that frame (the outer type already identifies the whole value).\n- **Endianness.** The WASM codec is little-endian. The `toiljs/io` codec defaults to little-endian too, and also accepts a per-call big-endian flag for network formats. Keep both ends on the same setting.\n- **Plain JSON numbers lose precision above 2^53.** That is why `@data` sends 64-bit-and-larger integers as decimal strings over JSON. If you hand-build JSON, do the same, or use the binary codec.\n- **`DataReader` never throws; check `ok`.** An over-read returns a default and sets `ok = false`. Always check `ok` after decoding untrusted bytes.\n\n## Related\n\n- [Types](../concepts/types.md): `u64`, `u256`, `f64`, and how each maps to `number` or `bigint`.\n- [HTTP routes (`@rest`)](./rest.md): where `@data` bodies and return values are used, and the JSON vs binary route modes.\n- [Typed RPC](./rpc.md): `@data` as RPC arguments and results, and the generated client classes.\n- [The database](../database/README.md): storing `@data` values in ToilDB.\n- [Backend overview](./README.md): where `@data` fits in the request lifecycle.\n\n\n## Checked integer arithmetic and parsing\n\n`u256.tryParse(text, radix)` returns `u256 | null`, without trapping or wrapping.\nRadix must be 10 or 16. Input must contain at least one valid digit; signs,\nwhitespace and prefixes are rejected. For example, check the pointer with\n`changetype<usize>(value) == 0` before using the result, since u256 overloads\nvalue equality. `u256.fromString` remains the throwing API and rejects overflow.\n\n`Checked.add<T>`, `Checked.subtract<T>`, and `Checked.multiply<T>` return\n`CheckedResult<T>` with `ok` and `value`. They support primitive signed/unsigned\ninteger types, including 64-bit types; a failure returns `ok == false` and a zero\nvalue. They do not rely on assertions, so `--noAssert` does not disable checking.\nFloats and big-integer specializations are compile errors.\n\nConstructing `RegExp` is a compile error until regular expressions are implemented;\nit no longer compiles into a runtime stub that traps.\n\n## Sharing pure code with TypeScript clients\n\nA pure module can be compiled unchanged by both TypeScript and ToilScript. Add\n`/// <reference types=\"toilscript/shared\" />` at its top. This shipped types-only\nentry gives the client compiler the numeric names `i8`, `u8`, `i16`, `u16`,\n`i32`, `u32`, `f64`, and `bool`; ToilScript already understands those names.\nThere is no runtime shim or global installation. Use the same relative source\nimports from the server and the phone or browser build.\n\nThe supported subset consists of explicitly typed functions, local variables,\nconditionals, indexed loops, strings, booleans, `f64` arithmetic, and bounded\n`Uint8Array` access. Use standard operations implemented by both runtimes, such\nas `length`, `charCodeAt`, `slice`, and `subarray`. Keep UI, network, database,\ncodec decorators, pointers, and asynchronous work in adapters around that code.\nUse normal value imports for shared functions; ToilScript does not parse\nTypeScript's `import type` syntax.\n\nInteger semantics need explicit conversions in shared code. JavaScript erases\ntype assertions and does not truncate an assignment to `u8` or `i32`. Write\n`value & 255`, `value | 0`, or `value >>> 0` where byte, signed 32-bit, or unsigned\n32-bit coercion is intended. Widen bytes **before** shifts: ToilScript applies\nbit operations at the operand's integer width.\n\n```ts\n/// <reference types=\"toilscript/shared\" />\nexport function readU32BE(bytes: Uint8Array, offset: i32): u32 {\n if (offset < 0 || offset > bytes.length - 4) return 0;\n const a: u32 = bytes[offset], b: u32 = bytes[offset + 1];\n const c: u32 = bytes[offset + 2], d: u32 = bytes[offset + 3];\n return ((a << 24) | (b << 16) | (c << 8) | d) >>> 0;\n}\n```\n\nCheck bounds before every indexed access and keep integer values within their\ndeclared ranges. Avoid `i64`/`u64`, integer division, implicit wrapping, `f32`,\nexceptions, dynamic objects, and runtime-specific APIs in shared modules.\nTypeScript and Wasm parity tests compile the identical source file and compare\nbyte operations and checked decimal parsing, including malformed input and\ninteger boundaries. Use the same approach for a shared photo metadata parser;\nthis subset does not supply an image decoder or resizing API.\n\n## Unicode normalization and character classes\n\nStrings support `text.normalize()` (NFC by default), plus `normalize('NFD')`,\n`normalize('NFKC')`, and `normalize('NFKD')`. An unknown form traps. Normalization\nuses pinned Unicode 17.0.0 data and preserves unpaired UTF-16 units.\n\n`Unicode.category(codePoint)` returns the two-letter General_Category, such as\n`Lu`, `Ll`, `Mn`, or `Nd`. `Unicode.isLetter`, `isMark`, `isNumber`, and\n`isWhitespace` test the Unicode L, M, N, and White_Space properties. Pass a\nUnicode code point rather than one half of a surrogate pair:\n\n```ts\nconst decomposed = text.normalize('NFKD');\nlet folded = '';\nfor (let i = 0; i < decomposed.length; i++) {\n const cp = decomposed.codePointAt(i);\n if (cp > 0xffff) i++;\n if (!Unicode.isMark(cp)) folded += String.fromCodePoint(cp);\n}\n```\n\nThis example removes marks after compatibility decomposition; decide separately\nwhether that behavior is appropriate for your language and search rules.\n`Unicode.version()` reports the table version. Values outside 0..0x10FFFF have\ncategory `Cn` and fail the property tests. The implementation follows\n[Unicode normalization](https://www.unicode.org/reports/tr15/) and is checked\nagainst all four forms in the official Unicode 17 normalization conformance\ncorpus. Long combining-mark runs use a stable merge sort. The compiler's\n`npm run gen:unicode` regenerates tables from checksum-pinned upstream data;\nthe Unicode data license ships with the generated tables.\n",
|
package/build/compiler/vite.js
CHANGED
|
@@ -50,7 +50,7 @@ export declare function dispatchEnvelopeRequest(options: {
|
|
|
50
50
|
readonly url: string;
|
|
51
51
|
readonly cacheHost: string;
|
|
52
52
|
readonly hasAuth: boolean;
|
|
53
|
-
}): EnvelopeDispatchOutcome
|
|
53
|
+
}): Promise<EnvelopeDispatchOutcome>;
|
|
54
54
|
export declare function dispatchWasmRequest(options: {
|
|
55
55
|
readonly module: WasmServerModule;
|
|
56
56
|
readonly request: Request;
|
|
@@ -3,7 +3,7 @@ import fs from 'node:fs';
|
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import pc from 'picocolors';
|
|
5
5
|
import { writeResponseHeader } from 'toiljs/backend';
|
|
6
|
-
import { builtContentSecurityPolicy, DEFAULT_CSP, withSecurityHeaders } from 'toiljs/shared';
|
|
6
|
+
import { builtContentSecurityPolicy, builtCrossOriginOpenerPolicy, DEFAULT_CSP, withSecurityHeaders } from 'toiljs/shared';
|
|
7
7
|
import { METHOD_CODES } from './envelope.js';
|
|
8
8
|
import { applyCacheRule, lookupCache } from './cache.js';
|
|
9
9
|
import { assembleSsr } from '../ssr.js';
|
|
@@ -249,11 +249,11 @@ export function prepareSsrResponse(out, headOnly, serverHeader) {
|
|
|
249
249
|
export function sendSsr(response, out, headOnly, serverHeader) {
|
|
250
250
|
sendPreparedResponse(response, prepareSsrResponse(out, headOnly, serverHeader));
|
|
251
251
|
}
|
|
252
|
-
export function dispatchEnvelopeRequest(options) {
|
|
252
|
+
export async function dispatchEnvelopeRequest(options) {
|
|
253
253
|
const cached = lookupCache(options.cacheHost, options.method, options.url, options.envelopeReq.body);
|
|
254
254
|
if (cached !== null)
|
|
255
255
|
return { result: cached, handled: true };
|
|
256
|
-
const result = options.module.
|
|
256
|
+
const result = await options.module.dispatchWithNetwork(options.envelopeReq);
|
|
257
257
|
if (result.unhandled)
|
|
258
258
|
return { result: null, handled: false };
|
|
259
259
|
return {
|
|
@@ -266,7 +266,7 @@ export async function dispatchWasmRequest(options) {
|
|
|
266
266
|
const hasAuth = options.request.headers.cookie !== undefined ||
|
|
267
267
|
options.request.headers.authorization !== undefined;
|
|
268
268
|
try {
|
|
269
|
-
const dispatch = dispatchEnvelopeRequest({
|
|
269
|
+
const dispatch = await dispatchEnvelopeRequest({
|
|
270
270
|
module: options.module,
|
|
271
271
|
envelopeReq,
|
|
272
272
|
method: options.request.method,
|
|
@@ -305,5 +305,5 @@ export function assembleRouteSsr(route, module, envelopeReq) {
|
|
|
305
305
|
: assembleSsr(route, module.dispatchRender(envelopeReq));
|
|
306
306
|
if (out === null)
|
|
307
307
|
return null;
|
|
308
|
-
return { ...out, headers: withSecurityHeaders(out.headers, policy).map(([k, v]) => [k, v]) };
|
|
308
|
+
return { ...out, headers: withSecurityHeaders(out.headers, policy, builtCrossOriginOpenerPolicy(templateHtml)).map(([k, v]) => [k, v]) };
|
|
309
309
|
}
|
|
@@ -188,7 +188,7 @@ function startBuiltDaemon(options, paths) {
|
|
|
188
188
|
daemon: options.daemon,
|
|
189
189
|
});
|
|
190
190
|
}
|
|
191
|
-
function handleBuiltRuntimeRequest(runtime, request) {
|
|
191
|
+
async function handleBuiltRuntimeRequest(runtime, request) {
|
|
192
192
|
const envelopeReq = {
|
|
193
193
|
method: request.method,
|
|
194
194
|
path: request.url,
|
|
@@ -201,7 +201,7 @@ function handleBuiltRuntimeRequest(runtime, request) {
|
|
|
201
201
|
const hasAuth = headerValue(request.headers, 'cookie') !== undefined ||
|
|
202
202
|
headerValue(request.headers, 'authorization') !== undefined;
|
|
203
203
|
try {
|
|
204
|
-
const dispatch = dispatchEnvelopeRequest({
|
|
204
|
+
const dispatch = await dispatchEnvelopeRequest({
|
|
205
205
|
module: runtime.module,
|
|
206
206
|
envelopeReq,
|
|
207
207
|
method: request.method,
|
|
@@ -338,7 +338,7 @@ async function startBuiltServerSingle(options) {
|
|
|
338
338
|
const daemon = startBuiltDaemon(options, paths);
|
|
339
339
|
try {
|
|
340
340
|
const server = await startBuiltHttpServer(options, paths, async (request, response) => {
|
|
341
|
-
const reply = handleBuiltRuntimeRequest(runtime, await toThreadedRequest(request, 0));
|
|
341
|
+
const reply = await handleBuiltRuntimeRequest(runtime, await toThreadedRequest(request, 0));
|
|
342
342
|
return sendThreadedReply(response, reply);
|
|
343
343
|
});
|
|
344
344
|
return {
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
export function buildBase64Imports(ref) {
|
|
2
|
+
const span = (ptr, length) => {
|
|
3
|
+
const buffer = ref.memory?.buffer;
|
|
4
|
+
if (!buffer ||
|
|
5
|
+
ptr < 0 ||
|
|
6
|
+
length < 0 ||
|
|
7
|
+
ptr > buffer.byteLength ||
|
|
8
|
+
length > buffer.byteLength - ptr)
|
|
9
|
+
throw new RangeError('base64 codec memory bounds');
|
|
10
|
+
return Buffer.from(buffer, ptr, length);
|
|
11
|
+
};
|
|
12
|
+
return {
|
|
13
|
+
'codec.base64url_encode': (ptr, length, output, capacity) => {
|
|
14
|
+
if (length < 0 || length > 65536 || capacity < 0 || capacity > 196608)
|
|
15
|
+
return -1;
|
|
16
|
+
const encoded = span(ptr, length).toString('base64url');
|
|
17
|
+
if (encoded.length * 2 > capacity)
|
|
18
|
+
return -1;
|
|
19
|
+
span(output, capacity).write(encoded, 'utf16le');
|
|
20
|
+
return encoded.length;
|
|
21
|
+
},
|
|
22
|
+
'codec.base64url_decode': (ptr, chars, output, capacity) => {
|
|
23
|
+
if (chars < 0 || chars > 65536 || capacity < 0 || capacity > 65536)
|
|
24
|
+
return -1;
|
|
25
|
+
const encoded = span(ptr, chars * 2)
|
|
26
|
+
.toString('utf16le')
|
|
27
|
+
.replace(/[= \t\r\n]/g, '')
|
|
28
|
+
.replace(/\+/g, '-')
|
|
29
|
+
.replace(/\//g, '_');
|
|
30
|
+
if (!/^[A-Za-z0-9_-]*$/.test(encoded) || encoded.length % 4 === 1)
|
|
31
|
+
return -1;
|
|
32
|
+
const bytes = Buffer.from(encoded, 'base64url');
|
|
33
|
+
if (bytes.length > capacity)
|
|
34
|
+
return -1;
|
|
35
|
+
span(output, capacity).set(bytes);
|
|
36
|
+
return bytes.length;
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
}
|
|
@@ -14,5 +14,5 @@ export interface CryptoState {
|
|
|
14
14
|
lastResult: Buffer | null;
|
|
15
15
|
}
|
|
16
16
|
export declare function freshCryptoState(): CryptoState;
|
|
17
|
-
export declare function buildCryptoImports(ref: MemoryRef, cs: CryptoState): Record<string,
|
|
17
|
+
export declare function buildCryptoImports(ref: MemoryRef, cs: CryptoState): Record<string, WebAssembly.ImportValue>;
|
|
18
18
|
export {};
|
|
@@ -163,6 +163,30 @@ export function buildCryptoImports(ref, cs) {
|
|
|
163
163
|
'crypto.sign': (h, pp, pl, dp, dl) => signOp(cs, ref, h, pp, pl, dp, dl),
|
|
164
164
|
'crypto.verify': (h, pp, pl, sp, sl, dp, dl) => verifyOp(cs, ref, h, pp, pl, sp, sl, dp, dl),
|
|
165
165
|
'crypto.derive_bits': (h, pp, pl, lengthBits) => deriveBitsOp(cs, ref, h, pp, pl, lengthBits),
|
|
166
|
+
'crypto.totp_verify': (ptr, length, codePtr, codeLength, step) => {
|
|
167
|
+
if (length !== 20 || codeLength !== 6 || step < 1n || step >= 0x7fffffffffffffffn)
|
|
168
|
+
return 0n;
|
|
169
|
+
const secret = readBytes(ref, ptr, length);
|
|
170
|
+
const code = readBytes(ref, codePtr, codeLength);
|
|
171
|
+
try {
|
|
172
|
+
if (!code.every(byte => byte >= 48 && byte <= 57))
|
|
173
|
+
return 0n;
|
|
174
|
+
let matched = 0n;
|
|
175
|
+
for (let candidate = step - 1n; candidate <= step + 1n; candidate++) {
|
|
176
|
+
const counter = Buffer.alloc(8);
|
|
177
|
+
counter.writeBigUInt64BE(candidate);
|
|
178
|
+
const hash = nodeCrypto.createHmac('sha1', secret).update(counter).digest();
|
|
179
|
+
const value = (hash.readUInt32BE(hash[19] & 15) & 0x7fffffff) % 1000000;
|
|
180
|
+
const expected = Buffer.from(value.toString().padStart(6, '0'));
|
|
181
|
+
if (nodeCrypto.timingSafeEqual(code, expected))
|
|
182
|
+
matched = candidate;
|
|
183
|
+
}
|
|
184
|
+
return matched;
|
|
185
|
+
}
|
|
186
|
+
finally {
|
|
187
|
+
secret.fill(0);
|
|
188
|
+
}
|
|
189
|
+
},
|
|
166
190
|
'crypto.mldsa_verify': (pkPtr, pkLen, msgPtr, msgLen, sigPtr, sigLen, ctxPtr, ctxLen) => {
|
|
167
191
|
if (pkLen !== 1312 || sigLen !== 2420 || ctxLen > 255)
|
|
168
192
|
return -4;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { MemoryRef } from './host.js';
|
|
2
|
+
export declare function prepareGoogleKeys(): Promise<void>;
|
|
3
|
+
export declare function verifyGoogleToken(token: string, audience: string, nonce: string): {
|
|
4
|
+
sub: string;
|
|
5
|
+
email: string;
|
|
6
|
+
issuedAt: number;
|
|
7
|
+
emailAuthoritative: boolean;
|
|
8
|
+
} | null;
|
|
9
|
+
export declare function googleVerifyImport(ref: MemoryRef, tp: number, tl: number, ap: number, al: number, np: number, nl: number, out: number, cap: number): number;
|