@kayjs/auth 1.104.2 → 1.105.0
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/README.md +2 -2
- package/llms/admin-and-organizations.md +8 -8
- package/llms/admin-pages.md +2 -2
- package/llms/grouped-methods.md +33 -17
- package/llms/hardening-and-testing.md +9 -9
- package/llms/oauth-passkeys-two-factor.md +13 -13
- package/llms/oauth-providers.md +1 -1
- package/llms/oauth-server-and-tokens.md +7 -7
- package/llms/passwords-and-mails.md +12 -12
- package/llms/sessions-and-guards.md +9 -1
- package/llms/setup.md +7 -7
- package/llms/signed-in-components.md +20 -11
- package/llms.txt +1 -1
- package/package.json +9 -5
- package/src/account.ts +6 -15
- package/src/admin.ts +9 -25
- package/src/auth.ts +9 -6
- package/src/authorize/clients.ts +1 -1
- package/src/authorize/grants.ts +2 -4
- package/src/authorize/request.ts +2 -4
- package/src/bearer.ts +5 -11
- package/src/captcha.ts +5 -3
- package/src/components/sign-in-link.kay +19 -0
- package/src/components/sign-out-button.kay +17 -0
- package/src/components/signed-in.kay +7 -2
- package/src/components/user-menu.kay +11 -8
- package/src/context.ts +1 -1
- package/src/deletion.ts +2 -4
- package/src/email.ts +16 -28
- package/src/erase.ts +5 -4
- package/src/export.ts +2 -4
- package/src/failure.ts +37 -9
- package/src/guard.ts +8 -1
- package/src/guards.ts +12 -5
- package/src/index.ts +14 -16
- package/src/limits.ts +97 -5
- package/src/mail.ts +5 -3
- package/src/memoryStore.ts +6 -6
- package/src/messages/fr.ts +1 -0
- package/src/methods/account.ts +30 -14
- package/src/methods/admin.ts +31 -14
- package/src/methods/captcha.ts +18 -0
- package/src/methods/email.ts +16 -7
- package/src/methods/magicLink.ts +5 -5
- package/src/methods/oauth.ts +16 -7
- package/src/methods/oauthServer.ts +32 -6
- package/src/methods/organizations.ts +51 -20
- package/src/methods/passkeys.ts +13 -7
- package/src/methods/password.ts +10 -10
- package/src/methods/proof.ts +22 -0
- package/src/methods/sessions.ts +3 -2
- package/src/methods/tokens.ts +17 -5
- package/src/methods/twoFactor.ts +10 -10
- package/src/oauth/flow.ts +2 -4
- package/src/oauthTest.ts +8 -4
- package/src/organizations.ts +12 -30
- package/src/organizationsCore.ts +1 -1
- package/src/own.ts +17 -15
- package/src/pages/components/frame.kay +3 -3
- package/src/pages/components/passkey-add.kay +2 -2
- package/src/pages/components/passkey-sign-in.kay +2 -2
- package/src/pages/components/passkey-two-factor.kay +2 -2
- package/src/pages/components/provider-buttons.kay +1 -1
- package/src/pages/forms.ts +6 -6
- package/src/pages/index.ts +9 -8
- package/src/pages/routes/account/clients.kay +2 -2
- package/src/pages/routes/account/connections.kay +4 -4
- package/src/pages/routes/account/data.kay +7 -7
- package/src/pages/routes/account/index.kay +15 -15
- package/src/pages/routes/account/organizations/[org].kay +15 -15
- package/src/pages/routes/account/organizations/index.kay +5 -5
- package/src/pages/routes/account/security.kay +15 -15
- package/src/pages/routes/account/tokens.kay +4 -4
- package/src/pages/routes/admin/_layout.kay +1 -1
- package/src/pages/routes/admin/audit.kay +1 -1
- package/src/pages/routes/admin/users/[id].kay +11 -11
- package/src/pages/routes/confirm-email.kay +3 -3
- package/src/pages/routes/invitation.kay +8 -8
- package/src/pages/routes/magic-link.kay +3 -3
- package/src/pages/routes/oauth/authorize.kay +2 -2
- package/src/pages/routes/register.kay +4 -4
- package/src/pages/routes/reset-password.kay +6 -6
- package/src/pages/routes/sign-in.kay +10 -10
- package/src/pages/routes/two-factor.kay +4 -4
- package/src/pages/routes/verify-email.kay +8 -8
- package/src/passkeys.ts +10 -21
- package/src/password.ts +8 -11
- package/src/pg.ts +3 -3
- package/src/profile.ts +1 -3
- package/src/proof.ts +3 -5
- package/src/request.ts +77 -46
- package/src/requiredTwoFactor.ts +2 -2
- package/src/routes.ts +2 -2
- package/src/sessions.ts +3 -7
- package/src/setup.ts +6 -4
- package/src/sqlite.ts +6 -0
- package/src/test.ts +15 -3
- package/src/testHelpers.ts +16 -7
- package/src/testHook.ts +31 -0
- package/src/testing.ts +5 -4
- package/src/twoFactor.ts +9 -18
- package/src/viewer.ts +26 -4
- package/types/account.d.ts +10 -23
- package/types/account.d.ts.map +1 -1
- package/types/admin.d.ts +21 -39
- package/types/admin.d.ts.map +1 -1
- package/types/auth.d.ts +18 -5
- package/types/auth.d.ts.map +1 -1
- package/types/authorize/grants.d.ts +2 -5
- package/types/authorize/grants.d.ts.map +1 -1
- package/types/authorize/request.d.ts +3 -5
- package/types/authorize/request.d.ts.map +1 -1
- package/types/bearer.d.ts +9 -17
- package/types/bearer.d.ts.map +1 -1
- package/types/captcha.d.ts +3 -1
- package/types/captcha.d.ts.map +1 -1
- package/types/context.d.ts +1 -1
- package/types/deletion.d.ts +2 -5
- package/types/deletion.d.ts.map +1 -1
- package/types/email.d.ts +23 -28
- package/types/email.d.ts.map +1 -1
- package/types/erase.d.ts.map +1 -1
- package/types/export.d.ts +3 -5
- package/types/export.d.ts.map +1 -1
- package/types/failure.d.ts +22 -3
- package/types/failure.d.ts.map +1 -1
- package/types/guard.d.ts +2 -0
- package/types/guard.d.ts.map +1 -1
- package/types/guards.d.ts +2 -1
- package/types/guards.d.ts.map +1 -1
- package/types/index.d.ts +14 -16
- package/types/index.d.ts.map +1 -1
- package/types/limits.d.ts +57 -1
- package/types/limits.d.ts.map +1 -1
- package/types/mail.d.ts +5 -0
- package/types/mail.d.ts.map +1 -1
- package/types/messages/fr.d.ts +1 -0
- package/types/methods/account.d.ts +27 -13
- package/types/methods/account.d.ts.map +1 -1
- package/types/methods/admin.d.ts +39 -15
- package/types/methods/admin.d.ts.map +1 -1
- package/types/methods/captcha.d.ts +9 -0
- package/types/methods/captcha.d.ts.map +1 -0
- package/types/methods/email.d.ts +21 -7
- package/types/methods/email.d.ts.map +1 -1
- package/types/methods/magicLink.d.ts +9 -4
- package/types/methods/magicLink.d.ts.map +1 -1
- package/types/methods/oauth.d.ts +12 -7
- package/types/methods/oauth.d.ts.map +1 -1
- package/types/methods/oauthServer.d.ts +13 -5
- package/types/methods/oauthServer.d.ts.map +1 -1
- package/types/methods/organizations.d.ts +40 -15
- package/types/methods/organizations.d.ts.map +1 -1
- package/types/methods/passkeys.d.ts +18 -7
- package/types/methods/passkeys.d.ts.map +1 -1
- package/types/methods/password.d.ts +23 -10
- package/types/methods/password.d.ts.map +1 -1
- package/types/methods/proof.d.ts +12 -0
- package/types/methods/proof.d.ts.map +1 -0
- package/types/methods/sessions.d.ts +3 -2
- package/types/methods/sessions.d.ts.map +1 -1
- package/types/methods/tokens.d.ts +12 -5
- package/types/methods/tokens.d.ts.map +1 -1
- package/types/methods/twoFactor.d.ts +22 -10
- package/types/methods/twoFactor.d.ts.map +1 -1
- package/types/oauth/flow.d.ts +4 -6
- package/types/oauth/flow.d.ts.map +1 -1
- package/types/oauthTest.d.ts +2 -0
- package/types/oauthTest.d.ts.map +1 -1
- package/types/organizations.d.ts +24 -48
- package/types/organizations.d.ts.map +1 -1
- package/types/own.d.ts +1 -1
- package/types/own.d.ts.map +1 -1
- package/types/pages/forms.d.ts +5 -3
- package/types/pages/forms.d.ts.map +1 -1
- package/types/pages/index.d.ts +5 -2
- package/types/pages/index.d.ts.map +1 -1
- package/types/passkeys.d.ts +20 -27
- package/types/passkeys.d.ts.map +1 -1
- package/types/password.d.ts +13 -20
- package/types/password.d.ts.map +1 -1
- package/types/profile.d.ts +1 -4
- package/types/profile.d.ts.map +1 -1
- package/types/proof.d.ts +1 -4
- package/types/proof.d.ts.map +1 -1
- package/types/request.d.ts +33 -7
- package/types/request.d.ts.map +1 -1
- package/types/requiredTwoFactor.d.ts +3 -1
- package/types/requiredTwoFactor.d.ts.map +1 -1
- package/types/routes.d.ts +3 -1
- package/types/routes.d.ts.map +1 -1
- package/types/sessions.d.ts +3 -10
- package/types/sessions.d.ts.map +1 -1
- package/types/setup.d.ts.map +1 -1
- package/types/sqlite.d.ts +3 -0
- package/types/sqlite.d.ts.map +1 -0
- package/types/test.d.ts +4 -1
- package/types/test.d.ts.map +1 -1
- package/types/testHelpers.d.ts +1 -0
- package/types/testHelpers.d.ts.map +1 -1
- package/types/testHook.d.ts +15 -0
- package/types/testHook.d.ts.map +1 -0
- package/types/testing.d.ts.map +1 -1
- package/types/twoFactor.d.ts +10 -21
- package/types/twoFactor.d.ts.map +1 -1
- package/types/viewer.d.ts +3 -1
- package/types/viewer.d.ts.map +1 -1
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
### Guards and gates
|
|
6
6
|
|
|
7
|
-
A `_guard.ts` default-exports kayjs-auth's guard, `authGuard({ redirect, require, scope })` from the package, which asks the request's `auth`, so imports no module (`auth.guard()` is the same):
|
|
7
|
+
A `_guard.ts` default-exports kayjs-auth's guard, `authGuard({ redirect, require, scope, fresh })` from the package, which asks the request's `auth`, so imports no module (`auth.guard()` is the same):
|
|
8
8
|
|
|
9
9
|
```ts
|
|
10
10
|
import { authGuard } from '@kayjs/auth'
|
|
@@ -12,6 +12,14 @@ import { authGuard } from '@kayjs/auth'
|
|
|
12
12
|
export default authGuard({ redirect: '/login', require: 'editor' })
|
|
13
13
|
```
|
|
14
14
|
|
|
15
|
+
### Ask for the password or passkey again
|
|
16
|
+
|
|
17
|
+
`fresh: '10m'` on a guard, or on `requireUser({ fresh })`, asks that the user signed in or re-proved within that long, as before changing a password, an email or a payment method. A session signed in longer ago is refused with a 403 whose `data.code` is `'stale'`, and a bearer token, which has no session to prove with, always is. The page or the app's client then shows a proof form, calls `auth.proof.renew({ password })` (or `{ passkey }`, `{ code }`) and retries; `auth.proof.recent('10m')` tells whether to show it first. `proof.renew` resets the clock for every `fresh` of the session, and a `fresh` that is no duration fails where the guard is made.
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
export default authGuard({ require: 'admin', fresh: '10m' })
|
|
21
|
+
```
|
|
22
|
+
|
|
15
23
|
Plain Elysia routes, such as an API, close behind a gate:
|
|
16
24
|
|
|
17
25
|
```ts
|
package/llms/setup.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
### Setup
|
|
6
6
|
|
|
7
|
-
kayjs-auth is published as `@kayjs/auth` to
|
|
7
|
+
kayjs-auth is published as `@kayjs/auth` to npm, beside kay. kay, Elysia (an implementation detail of kay: an app names `KayPlugin` and `Schema`, never Elysia's types), kayjs-ui (for the prebuilt pages) and `@kaynooo/pg-orm` (for the default store) are peer dependencies.
|
|
8
8
|
|
|
9
9
|
One line in kay.config.ts is the whole setup, and the app has no auth file:
|
|
10
10
|
|
|
@@ -18,7 +18,7 @@ export default defineConfig({
|
|
|
18
18
|
})
|
|
19
19
|
```
|
|
20
20
|
|
|
21
|
-
`auth()` takes `authCore`'s options (see Setup rules) and finds the rest. The session is kay's `session()` on the app secret. The site is kay's `site`. The store is, in order: `store` (`{ url }`, a `pgAuth(db)` over the app's own database in a function, or an `AuthStore`); the database at `AUTH_DATABASE_URL`; the database of the app's `store` in kay.config.ts, `sqliteData(path)` or `pgData(url)` (a `pgData` given a connection names none), where it creates its `kay_*` tables and leaves every other table alone; else
|
|
21
|
+
`auth()` takes `authCore`'s options (see Setup rules) and finds the rest. The session is kay's `session()` on the app secret. The site is kay's `site`. The store is, in order: `store` (`{ url }`, a `pgAuth(db)` over the app's own database in a function, or an `AuthStore`); the database at `AUTH_DATABASE_URL`; the database of the app's `store` in kay.config.ts, `sqliteData(path)` or `pgData(url)` (a `pgData` given a connection names none), where it creates its `kay_*` tables and leaves every other table alone; else the SQLite file `data/app.sqlite`, shared with kay and the other libraries (`sqliteAuth(path)` from `@kayjs/auth/sqlite` names another). An existing `data/auth.sqlite` or `data/auth.db` is kept (logged once), so an upgrade loses no user. It is in memory under `bun test` unless one of the first two is given, and in a static export. An app running its own pg-orm `sync` on that database lists `authTables` in its tables. The mailer is `mail.enqueue` of `src/mail.ts` when it exports `mail`, else the one `mail()` of kay.config.ts built (kayjs-mail's `enqueue`), through `authMailer` when kay.config.ts registers `mail()`; `email: false` sends no mail, and an `email` of your own replaces it. `oauth: { github: true }` reads `GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET` (presets: github, discord, google, microsoft, gitlab, linkedin, facebook, twitch, slack, x), which `kay env` lists; an object adds preset options, `label`, `keepTokens` or the credentials. Hooks (`afterSignUp`, `beforeDelete`, `profileFields`, `exportData`, `onEvent`, `allow`, `authorize`, `locate`) are options too (they win), or `export const hooks = {...} satisfies AuthHooks` in an optional `src/auth.ts`, found by convention, or `hooks: () => import('./src/auth')`. An executable carries both files, and `kay dev` reloads them. The pages are on under `prefix` (`/auth`), sign-ins and sign-outs going to `home` (`/`); `pages: false` leaves them out and `pages: { remember, profile }` tunes them. `cookie` names the session cookie.
|
|
22
22
|
|
|
23
23
|
`kay add auth` (needs `server` and `tailwind`) writes `auth({ name })` and kayjs-ui's `ui()` in kay.config.ts (with a `store` over the project's pg-orm `Database`, to which it adds `...authTables`), a root `src/routes/_guard.ts` exporting `authGuard()`, and `KAY_SECRET` and `SITE_URL` in `.env.example` (`AUTH_DATABASE_URL` too without a project `Database`), with no `src/auth.ts`. Delete the guard for public pages.
|
|
24
24
|
|
|
@@ -87,7 +87,7 @@ A plain Elysia app, or one mounting the plugin by hand, gives `auth({ server: fa
|
|
|
87
87
|
- `store`: see Stores. `authTables` of `@kayjs/auth/pg` is every table below, each exported on its own for an app table's foreign key: `AuthUsers`, `AuthSessions`, `AuthIdentities`, `AuthPasskeys`, `AuthRecoveryCodes`, `AuthTokens`, `AuthAttempts`, `AuthAudit`, `AuthBearerTokens`, `AuthOrganizations`, `AuthMembers`, `AuthInvitations`, `AuthOAuthClients`, `AuthOAuthCodes`, `AuthOAuthGrants` and `AuthOAuthRefresh`.
|
|
88
88
|
- `site`: the site's public origin, for OAuth callbacks, mailed links and passkeys; kay's `site` (kay.config.ts, else `SITE_URL`) when left out; a plain Elysia app gives its own. With OAuth or mail configured and no origin anywhere, the server refuses to start and a request answers 500, naming `SITE_URL`; `kay dev` supplies `http://localhost:<port>`. `name`: the site's name in mails and authenticator apps, the origin's host by default.
|
|
89
89
|
- `signInPage`: where a failed OAuth sign-in goes with `?error=`, `/` by default, and where `authGuard()` and `requireUser()` send an anonymous visitor opening a page when there are no `pages`. `failurePage`: where every failed OAuth sign-in goes instead, with no reason in the URL, so that whether an account may sign in does not leak through an `allow` list. `twoFactorPage`: where a sign-in goes to ask for the code, `/two-factor` by default. `securityPage`: where `twoFactor.require` sends a user to turn two-factor on, the pages' account security page by default. `pages`: see Prebuilt pages, which these then default to.
|
|
90
|
-
- The rest sit with their topic: `oauth`, `allow`, `
|
|
90
|
+
- The rest sit with their topic: `oauth`, `allow`, `afterSignUp`, `profileFields` (OAuth); `signUp`, `rules` (Passwords); `email` (Mailed links); `beforeDelete` (Account); `account` (Deleting an account after a grace period); `onEvent` (Security mails); `roles`, `defaultRoles`, `authorize` (Guards and gates); `scopes` (Bearer tokens); `rateLimit` (Limits); `captcha`, `breachedPasswords` (Bots and breached passwords); `remember`, `sessionsPage`, `locate` (Sessions); `passkeys`; `audit` (Events and the audit log); `admin`; `organizations`; `oauthServer` (OAuth server for MCP clients). The hooks follow [kay's hook convention](../../kay/llms/hooks.md) and take one event object with a `context` (an `AuthHookContext`): `afterSignUp({ user, profile, context })`, `beforeDelete({ user, context })`, `onEvent({ event, user, context, ... })`. `afterSignUp` and `onEvent` only observe: a throw is logged, reported to the app's `onError` with source `auth.afterSignUp` or `auth.onEvent`, and never fails the sign-up or the sign-in.
|
|
91
91
|
|
|
92
92
|
### Prebuilt pages rules
|
|
93
93
|
|
|
@@ -97,8 +97,8 @@ A plain Elysia app, or one mounting the plugin by hand, gives `auth({ server: fa
|
|
|
97
97
|
- With `pages`, `signInPage`, `twoFactorPage`, `sessionsPage` and every `email.links` default to those pages, and `auth.guard()` without `redirect` sends an anonymous GET or HEAD to the sign-in page (a browser fetch, or a request whose `Accept` names neither `text/html` nor `*/*`, gets the 401), `?redirect=` back, in the page's language (`/fr/page` goes to `/fr/auth/sign-in?redirect=%2Ffr%2Fpage`). Without `pages`, `email.links` names a page for each kind, or `authCore` throws.
|
|
98
98
|
- An app file at a page's path replaces that page alone: `src/routes/auth/magic-link.kay` is the app's own magic-link page. Its texts live under `auth` in kay's messages, the English in the code and the French shipped with the package: a key in the app's `src/messages/en.ts`, such as `auth: { signIn: { title: 'Welcome back' } }`, replaces that text and keeps the rest.
|
|
99
99
|
- The pages reached before signing in, `sign-in`, `password.register`, `two-factor`, `reset-password`, `verify-email`, `magic-link` and `confirm-email`, set `guards: false`, and the four that open from a mailed link (`reset-password`, `verify-email`, `magic-link`, `confirm-email`) send `Referrer-Policy: same-origin` so the token in the address never reaches another site: none of the app's guards above them runs there, whatever it checks. A root `_guard.ts` asking for a session, `export default auth.guard()`, keeps the rest of the site to signed-in users and still lets visitors sign in, the `account` pages keeping it; but a guard for maintenance, an IP allow-list or invite-only access skips those pages too. An app needing it on one of them replaces that page with its own, which the app's guards cover unless it sets `guards: false`; an app page replacing one under a session guard sets it. kayjs-auth's own routes, OAuth and the rest, are its plugin's, which page guards never reach.
|
|
100
|
-
- A site with data of its own on its users keeps these pages: `pages: { profile }` adds fields to the account page's profile form. `profile` is `{ fields, load, save }`: `fields` maps a name to `{ label, type?, autocomplete?, required?, maxLength? }` (`type` `'text'` by default, `'textarea'`, `'tel'`, `'url'` or `'email'`; `label` a string, or a map by locale such as `{ en: 'Bio', fr: 'Biographie' }`, the first when none matches); `load(user)` answers what each field holds, a string, `null` or `undefined` (anything else throws); `save(user, values)` stores the trimmed values once `required` and `maxLength` (500 by default) passed, may return `{ errors: { field: 'message' } }` to refuse, and answers 500 when it throws. `auth.account.
|
|
101
|
-
- `captcha.widget`, `turnstileWidget(siteKey)` or `hcaptchaWidget(siteKey)`, is the widget the pages show where `
|
|
100
|
+
- A site with data of its own on its users keeps these pages: `pages: { profile }` adds fields to the account page's profile form. `profile` is `{ fields, load, save }`: `fields` maps a name to `{ label, type?, autocomplete?, required?, maxLength? }` (`type` `'text'` by default, `'textarea'`, `'tel'`, `'url'` or `'email'`; `label` a string, or a map by locale such as `{ en: 'Bio', fr: 'Biographie' }`, the first when none matches); `load(user)` answers what each field holds, a string, `null` or `undefined` (anything else throws); `save(user, values)` stores the trimmed values once `required` and `maxLength` (500 by default) passed, may return `{ errors: { field: 'message' } }` to refuse, and answers 500 when it throws. `auth.account.getProfile(locale?)` and `auth.account.updateProfile(values)` are what the form calls, for a page of the app's own (`saveProfile` throws without `pages.profile`): both need a session, a bearer token cannot edit a profile, and an admin acting as a user can.
|
|
101
|
+
- `captcha.widget`, `turnstileWidget(siteKey)` or `hcaptchaWidget(siteKey)`, is the widget the pages show where `captcha.required` asks for one; with the proof of work they carry its field instead, and say JavaScript is needed to a browser without it.
|
|
102
102
|
- A provider's button reads its `label`, set on each preset (`GitHub`, `Google`) and overridden by `oauth.<name>.label`.
|
|
103
103
|
- The pages render with the app's own kayjs-ui, which with Tailwind and `@iconify-json/tabler` the app keeps; kayjs-auth and kayjs-ui are released with kay at its version and peer on kay's minor, so the app moves them together.
|
|
104
104
|
|
|
@@ -110,11 +110,11 @@ The register page's notice: `pages: { privacy: '/privacy', purpose: 'Your addres
|
|
|
110
110
|
|
|
111
111
|
### Signed-in user rules
|
|
112
112
|
|
|
113
|
-
- `auth.user()` is a method returning a promise, `await` it. It answers `{ id, email, emailVerified, username, roles, hasPassword, twoFactor, locale, guest, data, providers }`, or `null`: `data` is what the `user` schema keeps (see OAuth), `{}` without one, and `providers` the id of each linked provider (`providers.discord?.id`), read for `user()`, `requireUser()` and the hooks (`
|
|
113
|
+
- `auth.user()` is a method returning a promise, `await` it. It answers `{ id, email, emailVerified, username, roles, hasPassword, twoFactor, locale, guest, data, providers }`, or `null`: `data` is what the `user` schema keeps (see OAuth), `{}` without one, and `providers` the id of each linked provider (`providers.discord?.id`), read for `user()`, `requireUser()` and the hooks (`afterSignUp`, `profileFields`, `beforeDelete`, `exportData`, `admin`, `onEvent`, `impersonator()`, `userFromToken`); guards, gates, `authorize`, admin lists and results such as `password.register` give a `BareUser` without it, and `bareUser()` is `user()` without it and without the read. Returning `await auth.user()` whole to the client sends provider ids. Secrets never leave the store: no hash, no TOTP secret, no token.
|
|
114
114
|
- It reads the session first, then the request's `Authorization: Bearer` token. `via()` says which: `'session'`, `'bearer'` or `null`.
|
|
115
115
|
- `requireUser()` is `user()` for a page or an action that needs one, with no guard above it: it answers the `User`, and for an anonymous request it stops as `auth.guard()` does, a visitor reading a page going to the sign-in page with `?redirect=` set to where they were, with `pages`, and any other request, an action's call included, refused with a 401. The user is read once per request however many of them ask.
|
|
116
116
|
- `requireUser({ redirect, scope, require })` names the sign-in page of an app without `pages` or `signInPage` (empty by default, as in `guard`), a scope a scoped bearer token needs, and a requirement `authorize` checks, as in `authGuard({ require })` but with no `params`; either missing is a 403. `bare: true` answers the `BareUser` of `bareUser()` and reads no providers, for a caller that only wants the checks (kayjs-cms's `role` does). `signInUrl(back?)` is that URL for a link of the app's own: `a(href={ctx.locals.auth.signInUrl()}) Sign in` leads back to its page, `signInUrl('/pricing')` to another path. A `back` that is not a path of this site, `//evil.example` or `https://...`, leads home instead.
|
|
117
|
-
- A sign-out button is a form posting to kayjs-auth's own route
|
|
117
|
+
- A sign-out button is `SignOutButton` (`@kayjs/auth/components/sign-out-button.kay`, `redirect` for where to go after, [components](signed-in-components.md)), a form posting to kayjs-auth's own route with no action of the app; the route reads a `redirect` field, a path of the site, else the pages' `home` or `/`. It answers 303, only to a post: a link or a prefetch signs no one out, and a post from another site gets a 403.
|
|
118
118
|
- `signOut()` signs this session out under a new session id, keeping the rest of the app's session data, and takes it off the user's sessions, so a copy of the cookie is worth nothing either. `signOutEverywhere()` ends every session of the user, copied cookies included, and every bearer token they hold; `signOutEverywhere({ keepThisOne: true })` keeps this session, the tokens still ending.
|
|
119
119
|
- `signIn({ id })` signs a user in directly, without their second factor, for a way of signing in the app proves itself. kayjs-auth's own flows all go through the second factor.
|
|
120
120
|
- A deleted user, one signed out everywhere since, or a session ended or unseen past its lifetime, reads as `null`, and the stale entry leaves the session.
|
|
@@ -4,26 +4,35 @@
|
|
|
4
4
|
|
|
5
5
|
### Show or hide a part for the signed-in user
|
|
6
6
|
|
|
7
|
-
`SignedIn
|
|
7
|
+
`SignedIn` and `UserMenu` read the request's user themselves, so a layout or a component shows the user with no `--- server` fence. They are sugar over `ctx.user`, `ctx.can(requirement)` and `ctx.impersonator`, which any template reads the same way, `if ctx.user then user` or `if ctx.can('admin')` ([Request values](../../kay/llms/request-values.md)):
|
|
8
8
|
|
|
9
9
|
```kay
|
|
10
10
|
---
|
|
11
11
|
import SignedIn from '@kayjs/auth/components/signed-in.kay'
|
|
12
|
-
import
|
|
12
|
+
import SignInLink from '@kayjs/auth/components/sign-in-link.kay'
|
|
13
|
+
import SignOutButton from '@kayjs/auth/components/sign-out-button.kay'
|
|
13
14
|
import UserMenu from '@kayjs/auth/components/user-menu.kay'
|
|
14
15
|
---
|
|
15
16
|
nav
|
|
16
|
-
|
|
17
|
-
a(href="/
|
|
18
|
-
|
|
17
|
+
SignedIn
|
|
18
|
+
a(href="/account") Account
|
|
19
|
+
@else
|
|
20
|
+
SignInLink
|
|
21
|
+
SignedIn(require="admin")
|
|
19
22
|
a(href="/admin") Admin
|
|
20
23
|
UserMenu
|
|
24
|
+
SignInLink(button tone="accent" label="Join")
|
|
25
|
+
SignOutButton(redirect="/goodbye" variant="ghost")
|
|
21
26
|
```
|
|
22
27
|
|
|
23
|
-
- `SignedIn` renders its children for a signed-in user, and with `
|
|
24
|
-
- `
|
|
25
|
-
-
|
|
26
|
-
- `
|
|
28
|
+
- `SignedIn` renders its children for a signed-in user, and with `require` for one meeting it, what `auth.guard({ require })` takes: a role under the app's `roles` hierarchy, `{ type, resourceId }`, a list of which any one passes, or a predicate `user => user.email.endsWith('@acme.com')`. A predicate gets the user and an empty context (no `params` or `request`) and answers a boolean at once, as a template renders without waiting, so a check that reads a store or the route is done in the page's server fence; a `{ type, resourceId }` naming a record never passes. `ctx.can(requirement)` takes the same.
|
|
29
|
+
- Its `@else` block renders for anyone who does not meet that: a visitor, a guest, or a signed-in user lacking `require`. It is the place for a sign-in link, and replaces `SignedOut`.
|
|
30
|
+
- `SignedIn(role=)` and `SignedOut` still work until 1.108: `deprecated-auth-signed` renames `role` to `require` and reports `SignedOut`, whose children go into an `@else` block of the `SignedIn` beside it.
|
|
31
|
+
- `UserMenu` shows the user's username or email, a link to their account when the prebuilt pages are on (`account={false}` leaves it out), its children, and a sign-out button back to the pages' home (`redirect` names another path). A visitor gets a link to the sign-in page instead, `signIn={false}` leaving it out. The account pages' own header is one.
|
|
32
|
+
- `SignOutButton` is the form posting to the sign-out route, a Button inside it: `redirect` is the path to go to after, put in the page's locale (the pages' `home` by default), `label` words the button and children follow it, and `variant`, `tone`, `size`, `icon` and attributes are the Button's. `class` styles the form, `parts={{ button: '...' }}` the button. It never reads the prefix: the app writes no `features().prefix`.
|
|
33
|
+
- `SignInLink` is a link to the sign-in page leading back to the page it is on: `redirect` names another path of the site, `href` another page altogether (the app's own sign-in), `label` the wording, children following it. `button` draws it as a Button, taking `variant`, `tone`, `size` and `icon`.
|
|
34
|
+
- A guest is signed out for all of them.
|
|
35
|
+
- `require` only hides markup, the page and its data are still served: guard the route with `auth.guard` for access.
|
|
27
36
|
- They read the request being answered, so a page with `prerender: true` fails the build asking you to render it per request. They nest in one another and in the app's own `await` blocks.
|
|
28
37
|
|
|
29
38
|
### Show the impersonation banner
|
|
@@ -47,7 +56,7 @@ With `account.deleteAfter`, `DeletionBanner` (`@kayjs/auth/components/deletion-b
|
|
|
47
56
|
|
|
48
57
|
### Show them with the first bytes
|
|
49
58
|
|
|
50
|
-
A page reads the user before it renders when its imports reach `SignedIn`, `
|
|
59
|
+
A page reads the user before it renders when its imports reach `SignedIn`, `UserMenu`, `SignInLink`, `SignOutButton` or any template reading `ctx`, through its layouts, components and helpers however deep, so they show in the first bytes, with JavaScript off too. A page not reaching them reads no session, and no option is needed.
|
|
51
60
|
|
|
52
61
|
- A page reading the session is the visitor's own: no cache shares it between visitors, and a page kept by the build is rendered per request.
|
|
53
62
|
- A read that fails there is left to the components, which read again and report it, showing nothing meanwhile.
|
|
@@ -56,4 +65,4 @@ A page reads the user before it renders when its imports reach `SignedIn`, `Sign
|
|
|
56
65
|
## Reference
|
|
57
66
|
|
|
58
67
|
- `viewer` goes beside `module` and `pages` in `auth({ ... })`: left out, the pages reaching a template reading `ctx` read the user; `true` reads it on every page.
|
|
59
|
-
- `SignedIn` takes `
|
|
68
|
+
- `SignedIn` takes `require` and an `@else` block; `UserMenu` takes `account`, `signIn` and `redirect`; `SignOutButton` takes `redirect`, `label` and a Button's props; `SignInLink` takes `redirect`, `href`, `button`, `label` and a Button's props (`variant`, `tone`, `size`, `icon`, `busy` and `spinner` apply only with `button`); `ImpersonationBanner` and `DeletionBanner` take none. `SignedOut` takes none and is deprecated. All import from `@kayjs/auth/components/<name>.kay`.
|
package/llms.txt
CHANGED
|
@@ -21,7 +21,7 @@ The rest is split by topic, each file read whole with one command:
|
|
|
21
21
|
- [The prebuilt admin pages](llms/admin-pages.md): users, roles, bans, impersonation, the audit log and the banner
|
|
22
22
|
- [The prebuilt organization pages](llms/organization-pages.md): the account tab for organizations, members, roles and invitations, and the invitation page
|
|
23
23
|
- [Bots, breached passwords, limits, stores, testing and the dev tool](llms/hardening-and-testing.md): proof of work, breached passwords, limits, stores, testing, the dev tool
|
|
24
|
-
- [The signed-in user in templates](llms/signed-in-components.md): SignedIn,
|
|
24
|
+
- [The signed-in user in templates](llms/signed-in-components.md): SignedIn (with `require` and `@else`), SignOutButton, SignInLink, UserMenu and ImpersonationBanner, read in the first bytes of the pages using them
|
|
25
25
|
|
|
26
26
|
## Environment
|
|
27
27
|
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kayjs/auth",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "1.
|
|
4
|
+
"version": "1.105.0",
|
|
5
5
|
"description": "Auth for kay apps on kay sessions: OAuth, passwords, two-factor, magic links and bearer tokens",
|
|
6
6
|
"author": "Kaynooo <https://github.com/Kayno0o>",
|
|
7
7
|
"license": "MIT",
|
|
@@ -33,6 +33,10 @@
|
|
|
33
33
|
"./pg": {
|
|
34
34
|
"types": "./types/pg.d.ts",
|
|
35
35
|
"default": "./src/pg.ts"
|
|
36
|
+
},
|
|
37
|
+
"./sqlite": {
|
|
38
|
+
"types": "./types/sqlite.d.ts",
|
|
39
|
+
"default": "./src/sqlite.ts"
|
|
36
40
|
}
|
|
37
41
|
},
|
|
38
42
|
"files": [
|
|
@@ -61,10 +65,10 @@
|
|
|
61
65
|
"test": "$npm_execpath test --parallel=6 --timeout 20000 --path-ignore-patterns='**/{pgStore,lastOne,sharedDatabase}.test.ts' && $npm_execpath test --isolate --timeout 20000 pgStore.test lastOne.test sharedDatabase.test"
|
|
62
66
|
},
|
|
63
67
|
"peerDependencies": {
|
|
64
|
-
"@kayjs/ui": "~1.
|
|
68
|
+
"@kayjs/ui": "~1.105.0",
|
|
65
69
|
"@kaynooo/pg-orm": "^7.1.2 || ^8.0.0",
|
|
66
70
|
"elysia": "^1.4.31",
|
|
67
|
-
"kay": "~1.
|
|
71
|
+
"kay": "~1.105.0"
|
|
68
72
|
},
|
|
69
73
|
"peerDependenciesMeta": {
|
|
70
74
|
"@kaynooo/pg-orm": {
|
|
@@ -76,8 +80,8 @@
|
|
|
76
80
|
"jose": "^6.2.13"
|
|
77
81
|
},
|
|
78
82
|
"devDependencies": {
|
|
79
|
-
"@kayjs/mail": "~1.
|
|
80
|
-
"@kayjs/ui": "~1.
|
|
83
|
+
"@kayjs/mail": "~1.105.0",
|
|
84
|
+
"@kayjs/ui": "~1.105.0",
|
|
81
85
|
"@kaynooo/eslint": "^7.1.6",
|
|
82
86
|
"@kaynooo/pg-orm": "^8.1.4",
|
|
83
87
|
"@types/bun": "^1.4.4",
|
package/src/account.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { BareUser } from './core'
|
|
2
|
-
import type {
|
|
2
|
+
import type { Result } from './failure'
|
|
3
3
|
import type { Proof, ProofFailure } from './proof'
|
|
4
4
|
import type { PasswordProblem, UsernameProblem } from './rules'
|
|
5
5
|
import type { RequestState } from './state'
|
|
@@ -21,10 +21,8 @@ const NO_ASIDE = { restore: async () => {
|
|
|
21
21
|
await Promise.resolve()
|
|
22
22
|
} }
|
|
23
23
|
|
|
24
|
-
export type ChangePasswordResult = { ok: true } | AuthFailed<ProofFailure> | AuthRejected<{ password: PasswordProblem | 'breached' }>
|
|
25
|
-
|
|
26
24
|
// Sets the signed-in user's password, or a first one, and ends their other sessions.
|
|
27
|
-
export async function changePassword(state: RequestState, proof: Proof, password: string): Promise<
|
|
25
|
+
export async function changePassword(state: RequestState, proof: Proof, password: string): Promise<Result<object, ProofFailure, { password: PasswordProblem | 'breached' }>> {
|
|
28
26
|
const problem = await newPasswordProblem(state.core, password)
|
|
29
27
|
|
|
30
28
|
if (problem !== undefined)
|
|
@@ -46,10 +44,8 @@ export async function changePassword(state: RequestState, proof: Proof, password
|
|
|
46
44
|
return { ok: true }
|
|
47
45
|
}
|
|
48
46
|
|
|
49
|
-
export type UpdateLocaleResult = { ok: true } | AuthFailed<'signed-out' | 'invalid-locale'>
|
|
50
|
-
|
|
51
47
|
// Sets the language the signed-in user's mails are written in, a BCP 47 tag such as `fr`.
|
|
52
|
-
export async function updateLocale(state: RequestState, locale: string): Promise<
|
|
48
|
+
export async function updateLocale(state: RequestState, locale: string): Promise<Result<object, 'signed-out' | 'invalid-locale'>> {
|
|
53
49
|
const record = await state.current()
|
|
54
50
|
|
|
55
51
|
if (!record)
|
|
@@ -63,10 +59,8 @@ export async function updateLocale(state: RequestState, locale: string): Promise
|
|
|
63
59
|
return { ok: true }
|
|
64
60
|
}
|
|
65
61
|
|
|
66
|
-
export type ChangeUsernameResult = { ok: true, user: BareUser } | AuthFailed<'signed-out'> | AuthRejected<{ username: UsernameProblem | 'taken' | 'unchanged' }>
|
|
67
|
-
|
|
68
62
|
// Names the signed-in user, or renames them, under the rules register checks. A name is no credential, so it takes no proof and sends no mail; a session is needed all the same, so a device's token cannot rename the account it was given for.
|
|
69
|
-
export async function changeUsername(state: RequestState, username: string): Promise<
|
|
63
|
+
export async function changeUsername(state: RequestState, username: string): Promise<Result<{ user: BareUser }, 'signed-out', { username: UsernameProblem | 'taken' | 'unchanged' }>> {
|
|
70
64
|
const record = await state.current()
|
|
71
65
|
|
|
72
66
|
if (!record || state.via() !== 'session')
|
|
@@ -110,10 +104,8 @@ export async function changeUsername(state: RequestState, username: string): Pro
|
|
|
110
104
|
return { ok: true, user: publicUser(updated) }
|
|
111
105
|
}
|
|
112
106
|
|
|
113
|
-
export type UnlinkResult = { ok: true } | AuthFailed<ProofFailure | 'not-linked' | 'last-way-in'>
|
|
114
|
-
|
|
115
107
|
// Unlinks a provider from the signed-in user, unless it is their last way in, and ends their other sessions.
|
|
116
|
-
export async function unlink(state: RequestState, provider: string, proof: Proof): Promise<
|
|
108
|
+
export async function unlink(state: RequestState, provider: string, proof: Proof): Promise<Result<object, ProofFailure | 'not-linked' | 'last-way-in'>> {
|
|
117
109
|
const proved = await reprove(state, proof)
|
|
118
110
|
|
|
119
111
|
if (!proved.ok)
|
|
@@ -146,10 +138,9 @@ export async function unlink(state: RequestState, provider: string, proof: Proof
|
|
|
146
138
|
}
|
|
147
139
|
|
|
148
140
|
// `deleteAt` is set with `account.deleteAfter`: the account is pending until then and the session stays signed in, so the user can cancel.
|
|
149
|
-
export type DeleteAccountResult = { ok: true, deleteAt?: Date } | AuthFailed<ProofFailure | 'last-admin' | 'last-owner' | 'refused'>
|
|
150
141
|
|
|
151
142
|
// Deletes the signed-in user and everything kayjs-auth keeps for them, then signs this session out. The last admin, and the only owner of an organization with other members, are refused before the proof is spent; an organization the user is alone in is deleted with them. With `account.deleteAfter` it only marks the account pending: the prune deletes it, `beforeDelete` and the notices included, once the period ends.
|
|
152
|
-
export async function deleteAccount(state: RequestState, proof: Proof, signOut: () => Promise<void>): Promise<
|
|
143
|
+
export async function deleteAccount(state: RequestState, proof: Proof, signOut: () => Promise<void>): Promise<Result<{ deleteAt?: Date }, ProofFailure | 'last-admin' | 'last-owner' | 'refused'>> {
|
|
153
144
|
const current = await state.current()
|
|
154
145
|
// Without the `admin` option nobody is an admin: no last one to keep and no roles to set aside.
|
|
155
146
|
const admins = state.core.admin ? await import('./admin') : undefined
|
package/src/admin.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { BareUser, SignedIn } from './core'
|
|
2
2
|
import type { AuditCursorInput, AuditEntry } from './events'
|
|
3
|
-
import type { AuthFailed } from './failure'
|
|
3
|
+
import type { AuthFailed, Result } from './failure'
|
|
4
4
|
import type { RequestState } from './state'
|
|
5
5
|
import type { UserRecord } from './store'
|
|
6
6
|
import { clamp } from '@kaynooo/utils'
|
|
@@ -31,14 +31,6 @@ export type AdminFailure = 'forbidden' | 'not-found' | 'two-factor-required'
|
|
|
31
31
|
// `stale` when the admin's session neither signed in nor re-proved in the last ten minutes.
|
|
32
32
|
export type AdminChangeFailure = AdminFailure | 'stale'
|
|
33
33
|
|
|
34
|
-
export type RoleResult = { ok: true, user: ManagedUser } | AuthFailed<AdminChangeFailure | 'unknown-role' | 'self' | 'last-admin'>
|
|
35
|
-
|
|
36
|
-
export type BanResult = { ok: true, user: ManagedUser } | AuthFailed<AdminChangeFailure | 'self' | 'admin' | 'until'>
|
|
37
|
-
|
|
38
|
-
export type UnbanResult = { ok: true, user: ManagedUser } | AuthFailed<AdminChangeFailure>
|
|
39
|
-
|
|
40
|
-
export type DeleteResult = { ok: true } | AuthFailed<AdminChangeFailure | 'self' | 'admin' | 'refused'>
|
|
41
|
-
|
|
42
34
|
export function managedUser(record: UserRecord): ManagedUser {
|
|
43
35
|
return {
|
|
44
36
|
...publicUser(record),
|
|
@@ -130,10 +122,8 @@ async function anotherAdmin(state: RequestState, exceptId: string): Promise<bool
|
|
|
130
122
|
}
|
|
131
123
|
}
|
|
132
124
|
|
|
133
|
-
export type ListUsersResult = { ok: true, users: ManagedUser[], total: number } | AuthFailed<'forbidden' | 'two-factor-required'>
|
|
134
|
-
|
|
135
125
|
// Newest first, a page of `limit` (50 by default) from `offset`.
|
|
136
|
-
export async function listUsers(state: RequestState, query: { search?: string | undefined, offset?: number | undefined, limit?: number | undefined }): Promise<
|
|
126
|
+
export async function listUsers(state: RequestState, query: { search?: string | undefined, offset?: number | undefined, limit?: number | undefined }): Promise<Result<{ users: ManagedUser[], total: number }, 'forbidden' | 'two-factor-required'>> {
|
|
137
127
|
const acting = await askingAdmin(state)
|
|
138
128
|
|
|
139
129
|
if (!acting.ok)
|
|
@@ -149,9 +139,7 @@ export async function listUsers(state: RequestState, query: { search?: string |
|
|
|
149
139
|
return { ok: true, users: found.users.map(managedUser), total: found.total }
|
|
150
140
|
}
|
|
151
141
|
|
|
152
|
-
export
|
|
153
|
-
|
|
154
|
-
export async function getUser(state: RequestState, userId: string): Promise<GetUserResult> {
|
|
142
|
+
export async function getUser(state: RequestState, userId: string): Promise<Result<{ user: ManagedUser, admin: boolean }, AdminFailure>> {
|
|
155
143
|
const acting = await askingAdmin(state)
|
|
156
144
|
|
|
157
145
|
if (!acting.ok)
|
|
@@ -163,7 +151,7 @@ export async function getUser(state: RequestState, userId: string): Promise<GetU
|
|
|
163
151
|
}
|
|
164
152
|
|
|
165
153
|
// Takes effect on the user's next request, roles being read with the user each time.
|
|
166
|
-
export async function changeRole(state: RequestState, userId: string, role: string, granted: boolean): Promise<
|
|
154
|
+
export async function changeRole(state: RequestState, userId: string, role: string, granted: boolean): Promise<Result<{ user: ManagedUser }, AdminChangeFailure | 'unknown-role' | 'self' | 'last-admin'>> {
|
|
167
155
|
const acting = await changingAdmin(state)
|
|
168
156
|
|
|
169
157
|
if (!acting.ok)
|
|
@@ -202,7 +190,7 @@ export async function changeRole(state: RequestState, userId: string, role: stri
|
|
|
202
190
|
}
|
|
203
191
|
|
|
204
192
|
// Bars the user from signing in, for good or `until` then, and signs them out everywhere, devices included. Another admin is refused: revoke their role first.
|
|
205
|
-
export async function banUser(state: RequestState, userId: string, options: { reason?: string | undefined, until?: Date | undefined }): Promise<
|
|
193
|
+
export async function banUser(state: RequestState, userId: string, options: { reason?: string | undefined, until?: Date | undefined }): Promise<Result<{ user: ManagedUser }, AdminChangeFailure | 'self' | 'admin' | 'until'>> {
|
|
206
194
|
const acting = await changingAdmin(state)
|
|
207
195
|
|
|
208
196
|
if (!acting.ok)
|
|
@@ -235,7 +223,7 @@ export async function banUser(state: RequestState, userId: string, options: { re
|
|
|
235
223
|
return { ok: true, user: managedUser(updated) }
|
|
236
224
|
}
|
|
237
225
|
|
|
238
|
-
export async function unbanUser(state: RequestState, userId: string): Promise<
|
|
226
|
+
export async function unbanUser(state: RequestState, userId: string): Promise<Result<{ user: ManagedUser }, AdminChangeFailure>> {
|
|
239
227
|
const acting = await changingAdmin(state)
|
|
240
228
|
|
|
241
229
|
if (!acting.ok)
|
|
@@ -260,7 +248,7 @@ export async function unbanUser(state: RequestState, userId: string): Promise<Un
|
|
|
260
248
|
}
|
|
261
249
|
|
|
262
250
|
// Deletes the user with everything kayjs-auth keeps for them, asks `beforeDelete`, calls `onDelete` and mails them the account-deleted notice. Another admin is refused: revoke their role first. An organization the user solely owns with other members passes to its longest-standing member, its new owner told, so an abandoned account is never a dead end.
|
|
263
|
-
export async function deleteUser(state: RequestState, userId: string): Promise<
|
|
251
|
+
export async function deleteUser(state: RequestState, userId: string): Promise<Result<object, AdminChangeFailure | 'self' | 'admin' | 'refused'>> {
|
|
264
252
|
const acting = await changingAdmin(state)
|
|
265
253
|
|
|
266
254
|
if (!acting.ok)
|
|
@@ -279,19 +267,15 @@ export async function deleteUser(state: RequestState, userId: string): Promise<D
|
|
|
279
267
|
return await isAdmin(state, record) ? failed('admin') : eraseLeavingUser(state, record, { actor, handOver: true })
|
|
280
268
|
}
|
|
281
269
|
|
|
282
|
-
export type AdminAuditLogResult = { ok: true, entries: AuditEntry[] } | AuthFailed<'forbidden' | 'two-factor-required'>
|
|
283
|
-
|
|
284
270
|
// Everyone's audit log, or one user's, newest first.
|
|
285
|
-
export async function adminAuditLog(state: RequestState, query: { userId?: string | undefined, before?: AuditCursorInput | undefined, limit?: number | undefined }): Promise<
|
|
271
|
+
export async function adminAuditLog(state: RequestState, query: { userId?: string | undefined, before?: AuditCursorInput | undefined, limit?: number | undefined }): Promise<Result<{ entries: AuditEntry[] }, 'forbidden' | 'two-factor-required'>> {
|
|
286
272
|
const acting = await askingAdmin(state)
|
|
287
273
|
|
|
288
274
|
return !acting.ok ? acting : { ok: true, entries: await auditEntries(state.core, query) }
|
|
289
275
|
}
|
|
290
276
|
|
|
291
|
-
export type ImpersonateResult = { ok: true } | AuthFailed<AdminFailure | 'stale' | 'self' | 'admin' | 'banned'>
|
|
292
|
-
|
|
293
277
|
// Signs this browser in as `userId`, the admin's own sign-in kept for `admin.stopImpersonating`; 'stale' unless the admin signed in or re-proved lately. Nothing that takes a proof works meanwhile, nothing is written to the user's organizations, another admin cannot be impersonated, it ends after 30 minutes, and the user is mailed.
|
|
294
|
-
export async function impersonate(state: RequestState, userId: string): Promise<
|
|
278
|
+
export async function impersonate(state: RequestState, userId: string): Promise<Result<object, AdminFailure | 'stale' | 'self' | 'admin' | 'banned'>> {
|
|
295
279
|
const acting = await changingAdmin(state)
|
|
296
280
|
const own = await state.session.get('auth')
|
|
297
281
|
|
package/src/auth.ts
CHANGED
|
@@ -2,19 +2,20 @@ import type { DefinitionBase, EphemeralType, MetadataBase, RouteBase, SingletonB
|
|
|
2
2
|
import type { Duration, Guard, Schema } from 'kay'
|
|
3
3
|
import type { KayConfig, Session } from 'kay/server'
|
|
4
4
|
import type { Access } from './access'
|
|
5
|
-
import type {
|
|
5
|
+
import type { TokenOptions, TokenProblem } from './bearer'
|
|
6
6
|
import type { CaptchaOptions } from './captcha'
|
|
7
7
|
import type { AuthSessionData, BareUser, OAuthApp, Profile, User } from './core'
|
|
8
8
|
import type { AccountOptions } from './deletion'
|
|
9
9
|
import type { EmailOptions } from './email'
|
|
10
10
|
import type { AuthEventInfo, AuthHookContext } from './events'
|
|
11
|
+
import type { Result } from './failure'
|
|
11
12
|
import type { ForwardAuthOptions, ForwardDomains } from './forwardAuth'
|
|
12
13
|
import type { ScopeRequirement } from './gate'
|
|
13
14
|
import type { RouteGuardOptions } from './guards'
|
|
14
15
|
import type { LimitsOption } from './limits'
|
|
15
16
|
import type { OrganizationsOptions } from './organizations'
|
|
16
17
|
import type { AuthPagesConfig } from './pages'
|
|
17
|
-
import type { CreateUserInput,
|
|
18
|
+
import type { CreateUserInput, RegisterErrors } from './password'
|
|
18
19
|
import type { AuthRequirement } from './request'
|
|
19
20
|
import type { CredentialRules } from './rules'
|
|
20
21
|
import type { AuthStore } from './store'
|
|
@@ -73,9 +74,11 @@ export interface AuthOptions<Data extends AuthSessionData, Role extends string,
|
|
|
73
74
|
allow?: ((profile: Profile) => boolean | Promise<boolean>) | undefined
|
|
74
75
|
// Whether visitors make their own accounts, by registering, as a guest or with a provider account no user has linked: on by default, `false` closes it. Then registering and `signInAsGuest` answer `{ ok: false, error: { code: 'off' } }`, users come from `auth.admin.createUser` alone, and the prebuilt pages offer no registering. `true` is not accepted, it is the default.
|
|
75
76
|
signUp?: false | undefined
|
|
76
|
-
// Called once a new user exists, to create the app's own records for them. It gets one object: `user`, the provider's `profile` for a sign-up by a provider account, and `context`. A throw is logged and reported to the app's `onError` with source `auth.
|
|
77
|
+
// Called once a new user exists, to create the app's own records for them. It gets one object: `user`, the provider's `profile` for a sign-up by a provider account, and `context`. A throw is logged and reported to the app's `onError` with source `auth.afterSignUp`, and never fails the sign-up.
|
|
78
|
+
afterSignUp?: ((event: { user: User, profile: Profile | undefined, context: AuthHookContext }) => unknown) | undefined
|
|
79
|
+
/** @deprecated Written `afterSignUp`; `deprecated-hook-names` rewrites it. Removed in 1.108. */
|
|
77
80
|
onSignUp?: ((event: { user: User, profile: Profile | undefined, context: AuthHookContext }) => unknown) | undefined
|
|
78
|
-
// Called with the provider's profile whenever one answers for a user: every OAuth sign-in, the first included after `
|
|
81
|
+
// Called with the provider's profile whenever one answers for a user: every OAuth sign-in, the first included after `afterSignUp`, and a link.
|
|
79
82
|
// What the app keeps on each user, an object schema such as `s.Object({ avatar: s.Optional(s.String()) })`: `auth.user()` returns it typed as `data`, `profileFields` fills it, and a store keeps it as JSON.
|
|
80
83
|
user?: (Schema & { static: UserData }) | undefined
|
|
81
84
|
// Called on every provider sign-in, the first and a link included, with `{ user, profile }`: the user as the app has them and the provider's profile. It runs before any second factor. What it returns is laid over `user().data`, only the fields `user` declares, and kept when the result fits the schema; return nothing to keep what is there, such as an avatar.
|
|
@@ -184,13 +187,13 @@ export function authCore<Data extends AuthSessionData, Role extends string = str
|
|
|
184
187
|
|
|
185
188
|
admin: {
|
|
186
189
|
// A user made by the app, as a script or an admin page makes one: checked as registering is, open with `signUp: false` too, signing no one in and mailing no one.
|
|
187
|
-
async createUser(input: Omit<CreateUserInput, 'roles'> & { roles?: Role[] | undefined }): Promise<
|
|
190
|
+
async createUser(input: Omit<CreateUserInput, 'roles'> & { roles?: Role[] | undefined }): Promise<Result<{ user: BareUser }, never, RegisterErrors>> {
|
|
188
191
|
return (await load.password()).createUser(core, input)
|
|
189
192
|
},
|
|
190
193
|
},
|
|
191
194
|
|
|
192
195
|
// A bearer token for `userId` taking no proof and sending no mail, for a flow the app gates itself, such as pairing a device, or a script. `token` adopts one the app handed out before, so its devices keep working through a migration.
|
|
193
|
-
async issueToken(userId: string, label: string, tokenOptions: TokenOptions<Scope> & { token?: string | undefined } = {}): Promise<
|
|
196
|
+
async issueToken(userId: string, label: string, tokenOptions: TokenOptions<Scope> & { token?: string | undefined } = {}): Promise<Result<{ token: string, id: string }, TokenProblem | 'token' | 'not-found' | 'banned'>> {
|
|
194
197
|
return (await load.bearer()).issueToken(core, userId, label, tokenOptions)
|
|
195
198
|
},
|
|
196
199
|
|
package/src/authorize/clients.ts
CHANGED
|
@@ -152,7 +152,7 @@ async function cachedClient(documents: Kv, href: string): Promise<OAuthClient |
|
|
|
152
152
|
|
|
153
153
|
async function cacheClient(documents: Kv, href: string, client: OAuthClient): Promise<void> {
|
|
154
154
|
try {
|
|
155
|
-
await documents.set(href, JSON.stringify(client), CACHE_MS)
|
|
155
|
+
await documents.set(href, JSON.stringify(client), `${CACHE_MS}ms`)
|
|
156
156
|
}
|
|
157
157
|
catch {
|
|
158
158
|
// Fetched again on the next ask.
|
package/src/authorize/grants.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { Result } from '../failure'
|
|
2
2
|
import type { RequestState } from '../state'
|
|
3
3
|
import { report } from '../events'
|
|
4
4
|
import { failed } from '../failure'
|
|
@@ -23,10 +23,8 @@ export async function approvedClients(state: RequestState): Promise<ApprovedClie
|
|
|
23
23
|
return (await state.core.store.oauth.grants.listByUser(record.id)).map(grant => ({ id: grant.clientId, name: grant.clientName, scopes: grant.scopes, createdAt: grant.createdAt, lastUsedAt: grant.lastUsedAt }))
|
|
24
24
|
}
|
|
25
25
|
|
|
26
|
-
export type RevokeGrantResult = { ok: true } | AuthFailed<'signed-out' | 'not-found'>
|
|
27
|
-
|
|
28
26
|
// Takes the approval back with every token the app was given; `not-found` when there was none, `signed-out` when this is not the user's own session.
|
|
29
|
-
export async function revokeClient(state: RequestState, clientId: string): Promise<
|
|
27
|
+
export async function revokeClient(state: RequestState, clientId: string): Promise<Result<object, 'signed-out' | 'not-found'>> {
|
|
30
28
|
const record = await approver(state)
|
|
31
29
|
const oauth = state.core.store.oauth
|
|
32
30
|
|
package/src/authorize/request.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Core } from '../core'
|
|
2
|
-
import type {
|
|
2
|
+
import type { Result } from '../failure'
|
|
3
3
|
import type { RequestState } from '../state'
|
|
4
4
|
import type { OAuthGrantRecord, UserRecord } from '../store'
|
|
5
5
|
import type { OAuthClient } from './clients'
|
|
@@ -232,10 +232,8 @@ export async function authorize(state: RequestState, params: AuthorizeParams, ro
|
|
|
232
232
|
}
|
|
233
233
|
}
|
|
234
234
|
|
|
235
|
-
export type DecideResult = { ok: true, redirect: string } | AuthFailed<'client' | 'redirect_uri' | 'signed-out'>
|
|
236
|
-
|
|
237
235
|
// The user's answer on the consent page, checked again as the request is: where the browser goes back to the client.
|
|
238
|
-
export async function decide(state: RequestState, fields: AuthorizeParams, allow: boolean, root: string): Promise<
|
|
236
|
+
export async function decide(state: RequestState, fields: AuthorizeParams, allow: boolean, root: string): Promise<Result<{ redirect: string }, 'client' | 'redirect_uri' | 'signed-out'>> {
|
|
239
237
|
const checked = await check(state, { ...fields, response_type: 'code', code_challenge_method: 'S256' }, root)
|
|
240
238
|
|
|
241
239
|
if (isOutcome(checked))
|
package/src/bearer.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { Duration } from 'kay'
|
|
2
2
|
import type { Core } from './core'
|
|
3
|
-
import type {
|
|
3
|
+
import type { Result } from './failure'
|
|
4
4
|
import type { Proof, ProofFailure } from './proof'
|
|
5
5
|
import type { RequestState } from './state'
|
|
6
6
|
import type { BearerTokenRecord, UserRecord } from './store'
|
|
@@ -53,11 +53,7 @@ function expirySeconds(maxAge: Duration): number | undefined {
|
|
|
53
53
|
}
|
|
54
54
|
}
|
|
55
55
|
|
|
56
|
-
type TokenProblem = 'label' | 'scope' | 'expiry'
|
|
57
|
-
|
|
58
|
-
export type CreateTokenResult = { ok: true, token: string, id: string } | AuthFailed<ProofFailure | TokenProblem>
|
|
59
|
-
|
|
60
|
-
export type IssueTokenResult = { ok: true, token: string, id: string } | AuthFailed<TokenProblem | 'token' | 'not-found' | 'banned'>
|
|
56
|
+
export type TokenProblem = 'label' | 'scope' | 'expiry'
|
|
61
57
|
|
|
62
58
|
function tokenProblem(core: Core, name: string, options: TokenOptions): TokenProblem | undefined {
|
|
63
59
|
if (name.length === 0 || name.length > LABEL_MAX_LENGTH)
|
|
@@ -98,7 +94,7 @@ async function storeToken(core: Core, userId: string, name: string, options: Tok
|
|
|
98
94
|
}
|
|
99
95
|
|
|
100
96
|
// A token for a device or an API client of the signed-in user, minted from a session only, never from another token.
|
|
101
|
-
export async function createToken(state: RequestState, proof: Proof, label: string, options: TokenOptions = {}): Promise<
|
|
97
|
+
export async function createToken(state: RequestState, proof: Proof, label: string, options: TokenOptions = {}): Promise<Result<{ token: string, id: string }, ProofFailure | TokenProblem>> {
|
|
102
98
|
const name = plainName(label)
|
|
103
99
|
const problem = tokenProblem(state.core, name, options)
|
|
104
100
|
|
|
@@ -122,7 +118,7 @@ export async function createToken(state: RequestState, proof: Proof, label: stri
|
|
|
122
118
|
}
|
|
123
119
|
|
|
124
120
|
// A token for `userId` with no proof, for the app to gate; `token` adopts one it handed out before, 32 to 4096 characters without whitespace, as a bearer header carries.
|
|
125
|
-
export async function issueToken(core: Core, userId: string, label: string, options: TokenOptions & { token?: string | undefined } = {}): Promise<
|
|
121
|
+
export async function issueToken(core: Core, userId: string, label: string, options: TokenOptions & { token?: string | undefined } = {}): Promise<Result<{ token: string, id: string }, TokenProblem | 'token' | 'not-found' | 'banned'>> {
|
|
126
122
|
const name = plainName(label)
|
|
127
123
|
const problem = tokenProblem(core, name, options)
|
|
128
124
|
|
|
@@ -151,9 +147,7 @@ export async function listTokens(state: RequestState): Promise<BearerToken[]> {
|
|
|
151
147
|
return record && state.via() === 'session' ? (await state.core.store.bearerTokens.listByUser(record.id)).filter(token => !token.oauth).map(publicToken) : []
|
|
152
148
|
}
|
|
153
149
|
|
|
154
|
-
export
|
|
155
|
-
|
|
156
|
-
export async function revokeToken(state: RequestState, id: string): Promise<RevokeTokenResult> {
|
|
150
|
+
export async function revokeToken(state: RequestState, id: string): Promise<Result<object, 'signed-out' | 'not-found'>> {
|
|
157
151
|
const record = await state.current()
|
|
158
152
|
|
|
159
153
|
if (!record || state.via() !== 'session')
|
package/src/captcha.ts
CHANGED
|
@@ -41,6 +41,8 @@ export interface AuthProofOfWorkOptions {
|
|
|
41
41
|
// The highest number the browser may hash up to past the threshold, 100,000 by default, doubled with each attempt after up to 16 times.
|
|
42
42
|
difficulty?: number | undefined
|
|
43
43
|
// How long a challenge stays good, an hour by default.
|
|
44
|
+
ttl?: Duration | undefined
|
|
45
|
+
/** @deprecated Written `ttl`; `deprecated-ttl-names` rewrites it. Removed in 1.108. */
|
|
44
46
|
maxAge?: Duration | undefined
|
|
45
47
|
// Where the solutions already used are kept, this process's memory by default: `sqliteRates(path)` from `kay/server` shares them between processes.
|
|
46
48
|
store?: RateStore | undefined
|
|
@@ -49,7 +51,7 @@ export interface AuthProofOfWorkOptions {
|
|
|
49
51
|
}
|
|
50
52
|
|
|
51
53
|
export interface ProofOfWorkCaptcha {
|
|
52
|
-
proofOfWork: { difficulty: number,
|
|
54
|
+
proofOfWork: { difficulty: number, ttl: Duration, store: RateStore | undefined }
|
|
53
55
|
on: CaptchaRules
|
|
54
56
|
}
|
|
55
57
|
|
|
@@ -79,7 +81,7 @@ export function proofOfWork(options: AuthProofOfWorkOptions = {}): ProofOfWorkCa
|
|
|
79
81
|
throw configError('auth', 'proofOfWork', `proofOfWork's difficulty is ${difficulty}; it takes a whole number from 1 to ${1e9 / 2 ** MOST_DOUBLINGS}`)
|
|
80
82
|
|
|
81
83
|
return {
|
|
82
|
-
proofOfWork: { difficulty,
|
|
84
|
+
proofOfWork: { difficulty, ttl: options.ttl ?? options.maxAge ?? '1h', store: options.store },
|
|
83
85
|
on: { 'register': 'always', 'guest': false, 'reset': 'always', 'magic-link': 'always', 'sign-in': 3, ...options.on },
|
|
84
86
|
}
|
|
85
87
|
}
|
|
@@ -138,7 +140,7 @@ export async function captchaChallenge(state: RequestState, action: CaptchaActio
|
|
|
138
140
|
|
|
139
141
|
const past = await pastThreshold(state, action)
|
|
140
142
|
|
|
141
|
-
return past === undefined ? null : workChallenge(workScope(action), { difficulty: workDifficulty(captcha, past),
|
|
143
|
+
return past === undefined ? null : workChallenge(workScope(action), { difficulty: workDifficulty(captcha, past), ttl: captcha.proofOfWork.ttl })
|
|
142
144
|
}
|
|
143
145
|
|
|
144
146
|
// Spends one attempt of `action` against this client and answers what refuses it: `limited` past the limit, `captcha` without a token that checks out where one is needed.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
---
|
|
2
|
+
import { localize } from 'kay/i18n'
|
|
3
|
+
import { wording } from 'kay/words'
|
|
4
|
+
import type { AsLink } from '@kayjs/ui/lib/button-props'
|
|
5
|
+
import Button from '@kayjs/ui/button.kay'
|
|
6
|
+
import { currentViewer } from '../viewer'
|
|
7
|
+
|
|
8
|
+
// A link to the sign-in page, leading back to this page (`redirect` names another path of the site; `href` another page altogether, such as the app's own sign-in). `button` draws it as a Button, with its `variant`, `tone`, `size` and `icon`; children follow the label.
|
|
9
|
+
const { redirect, href, button = false, label, variant, tone, size, icon, busy, spinner, ...rest } = props<Omit<AsLink, 'href'> & { href?: string | undefined, redirect?: string | undefined, button?: boolean | undefined }>()
|
|
10
|
+
const target = href ?? localize(currentViewer().auth.signInUrl(redirect))
|
|
11
|
+
const text = label ?? wording('auth.signIn.link', 'Sign in')
|
|
12
|
+
---
|
|
13
|
+
if button
|
|
14
|
+
Button(part="root" {...rest} href={target} label={text} variant={variant} tone={tone} size={size} icon={icon} busy={busy} spinner={spinner})
|
|
15
|
+
slot
|
|
16
|
+
else
|
|
17
|
+
a(part="root" {...rest} href={target})
|
|
18
|
+
| {text}
|
|
19
|
+
slot
|