@kayjs/auth 1.104.3 → 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/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 +6 -6
- 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
package/src/pg.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { Database, InferEntity } from '@kaynooo/pg-orm'
|
|
2
2
|
import type { AuditRecord, AuthStore, BearerTokenRecord, IdentityRecord, InvitationRecord, MemberRecord, OAuthClientRecord, OAuthCodeRecord, OAuthGrantRecord, OAuthRefreshRecord, OrganizationRecord, PasskeyRecord, PruneLimits, SessionRecord, TokenRecord, TokenType, UserRecord } from './store'
|
|
3
3
|
import { defineTable } from '@kaynooo/pg-orm'
|
|
4
|
-
import { durationSeconds } from 'kay/library'
|
|
4
|
+
import { durationSeconds, KayError, lengthMs } from 'kay/library'
|
|
5
5
|
import { log } from './log'
|
|
6
6
|
|
|
7
7
|
// Each table keeps the `renamedFrom` of its pre-1.71 `auth_*` name for good, unlike a deprecated form: an app jumping several minors at once still gets its users renamed rather than empty tables beside them, and a rename finding no old table does nothing.
|
|
@@ -203,7 +203,7 @@ const UNUSED_CLIENT_MS = 24 * 60 * 60 * 1000
|
|
|
203
203
|
// kayjs-auth's data in the app's Postgres or SQLite database, through pg-orm: list `authTables` in the database's tables.
|
|
204
204
|
export function pgAuth(db: Database): AuthStore {
|
|
205
205
|
if (typeof (db as Partial<Database> | null)?.repo !== 'function')
|
|
206
|
-
throw new
|
|
206
|
+
throw new KayError('config-invalid', 'kayjs-auth: pgAuth takes a pg-orm `Database` listing `authTables`, not a connection URL or a Bun `SQL`: give `auth({ store: { url } })` for a URL')
|
|
207
207
|
|
|
208
208
|
const users = db.repo(AuthUsers)
|
|
209
209
|
const identities = db.repo(AuthIdentities)
|
|
@@ -482,7 +482,7 @@ export function pgAuth(db: Database): AuthStore {
|
|
|
482
482
|
|
|
483
483
|
// One statement, so two attempts at once both count: a window still open is raised, an ended one starts over.
|
|
484
484
|
const [row] = await db.raw<{ count: number, reset_at: Date | string | number }>`
|
|
485
|
-
INSERT INTO "kay_attempts" ("key", "count", "reset_at") VALUES (${key}, ${weight}, ${new Date(now.getTime() + window)})
|
|
485
|
+
INSERT INTO "kay_attempts" ("key", "count", "reset_at") VALUES (${key}, ${weight}, ${new Date(now.getTime() + lengthMs(window))})
|
|
486
486
|
ON CONFLICT ("key") DO UPDATE SET
|
|
487
487
|
"count" = CASE WHEN "kay_attempts"."reset_at" > ${now} THEN "kay_attempts"."count" + ${weight} ELSE ${weight} END,
|
|
488
488
|
"reset_at" = CASE WHEN "kay_attempts"."reset_at" > ${now} THEN "kay_attempts"."reset_at" ELSE EXCLUDED."reset_at" END
|
package/src/profile.ts
CHANGED
|
@@ -1,12 +1,10 @@
|
|
|
1
1
|
import type { BareUser } from './core'
|
|
2
|
-
import type {
|
|
2
|
+
import type { AuthRejected } from './failure'
|
|
3
3
|
import type { ProfileFieldView, ProfileOptions, ProfileProblem } from './pages'
|
|
4
4
|
import { rejected } from './failure'
|
|
5
5
|
import { profileLabel, profileValue } from './pages'
|
|
6
6
|
import { PROFILE_MAX_LENGTH } from './rules'
|
|
7
7
|
|
|
8
|
-
export type SaveProfileResult = { ok: true } | AuthFailed<'signed-out'> | AuthRejected<Record<string, ProfileProblem>>
|
|
9
|
-
|
|
10
8
|
// The fields of the profile form with what `user` holds in each.
|
|
11
9
|
export async function profileFields(profile: ProfileOptions, user: BareUser, locale: string | undefined): Promise<ProfileFieldView[]> {
|
|
12
10
|
const held = await profile.load(user)
|
package/src/proof.ts
CHANGED
|
@@ -23,8 +23,6 @@ export interface Proof {
|
|
|
23
23
|
// `proof` when the proof was wrong or missing; `stale` when the account has neither a password nor a second factor and was signed into too long ago, so the user signs in again first; `impersonating` when an admin acts as the user, who proves nothing for them.
|
|
24
24
|
export type ProofFailure = 'signed-out' | 'proof' | 'stale' | 'limited' | 'impersonating'
|
|
25
25
|
|
|
26
|
-
export type ReproveResult = { ok: true } | AuthFailed<ProofFailure>
|
|
27
|
-
|
|
28
26
|
// What a sign-in waiting for its second factor keeps in the session.
|
|
29
27
|
export interface Challenge {
|
|
30
28
|
user: string
|
|
@@ -102,9 +100,9 @@ export async function reprove(state: RequestState, proof: Proof, options: { seco
|
|
|
102
100
|
return { ok: true, record }
|
|
103
101
|
}
|
|
104
102
|
|
|
105
|
-
// Whether this session signed in or re-proved its user
|
|
106
|
-
export async function provedLately(state: RequestState): Promise<boolean> {
|
|
103
|
+
// Whether this session signed in or re-proved its user within `within` milliseconds, the last ten minutes by default.
|
|
104
|
+
export async function provedLately(state: RequestState, within = FRESH_SIGN_IN_MS): Promise<boolean> {
|
|
107
105
|
const signedIn = await state.session.get('auth')
|
|
108
106
|
|
|
109
|
-
return signedIn !== undefined && Date.now() - signedIn.at <
|
|
107
|
+
return signedIn !== undefined && Date.now() - signedIn.at < within
|
|
110
108
|
}
|
package/src/request.ts
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
import type { GuardContext } from 'kay'
|
|
1
|
+
import type { Duration, GuardContext } from 'kay'
|
|
2
2
|
import type { KayConfig, Session } from 'kay/server'
|
|
3
3
|
import type { CaptchaAction } from './captcha'
|
|
4
4
|
import type { AuthSessionData, BareUser, Core, SignedIn, User } from './core'
|
|
5
|
+
import type { Result } from './failure'
|
|
5
6
|
import type { ScopeRequirement } from './gate'
|
|
6
7
|
import type { AuthFeatures } from './pages'
|
|
7
|
-
import type { Proof,
|
|
8
|
-
import type { GuestSignInResult } from './sessions'
|
|
8
|
+
import type { Proof, ProofFailure } from './proof'
|
|
9
9
|
import type { RequestState } from './state'
|
|
10
10
|
import type { SessionRecord, UserRecord } from './store'
|
|
11
11
|
import type { Requirement } from './types'
|
|
12
12
|
import { localPath } from 'kay'
|
|
13
|
-
import { durationSeconds, nameUser, overHttps, READ_METHODS, stoppers } from 'kay/library'
|
|
13
|
+
import { durationSeconds, KayError, nameUser, overHttps, READ_METHODS, stoppers } from 'kay/library'
|
|
14
14
|
import { clientAddress, crossSiteRefused, crossSiteResponse, forgetLocalMirrors, forgetPushDevice, rateKey, toolCall } from 'kay/server'
|
|
15
|
-
|
|
15
|
+
|
|
16
16
|
import { bearerRequest, bearerToken } from './bearerHeader'
|
|
17
|
-
import { admit
|
|
17
|
+
import { admit } from './captcha'
|
|
18
18
|
import { banned, guardPageOf, isNavigation, linkedProviders, linkedUser, newUserRecord, publicUser, unlinked, withBack } from './core'
|
|
19
19
|
import { report } from './events'
|
|
20
20
|
import { failed } from './failure'
|
|
@@ -24,6 +24,7 @@ import { acceptedLocales } from './locale'
|
|
|
24
24
|
import { AccountMethods } from './methods/account'
|
|
25
25
|
import { AdminMethods } from './methods/admin'
|
|
26
26
|
import { AuditMethods } from './methods/audit'
|
|
27
|
+
import { CaptchaMethods } from './methods/captcha'
|
|
27
28
|
import { EmailMethods } from './methods/email'
|
|
28
29
|
import { MagicLinkMethods } from './methods/magicLink'
|
|
29
30
|
import { OAuthMethods } from './methods/oauth'
|
|
@@ -31,11 +32,12 @@ import { OAuthServerMethods } from './methods/oauthServer'
|
|
|
31
32
|
import { OrganizationMethods } from './methods/organizations'
|
|
32
33
|
import { PasskeyMethods } from './methods/passkeys'
|
|
33
34
|
import { PasswordMethods } from './methods/password'
|
|
35
|
+
import { ProofMethods } from './methods/proof'
|
|
34
36
|
import { SessionMethods } from './methods/sessions'
|
|
35
37
|
import { TokenMethods } from './methods/tokens'
|
|
36
38
|
import { TwoFactorMethods } from './methods/twoFactor'
|
|
37
39
|
import { featuresOf } from './pages'
|
|
38
|
-
import { completeSignIn
|
|
40
|
+
import { completeSignIn } from './proof'
|
|
39
41
|
import { pruneWhenDue } from './prune'
|
|
40
42
|
import { sendToEnrolment } from './requiredTwoFactor'
|
|
41
43
|
import { roleHierarchy } from './roles'
|
|
@@ -47,6 +49,8 @@ export interface RequireUserOptions<Scope extends string, Role extends string> {
|
|
|
47
49
|
redirect?: string | undefined
|
|
48
50
|
scope?: ScopeRequirement<Scope> | undefined
|
|
49
51
|
require?: AuthRequirement<Role> | undefined
|
|
52
|
+
// A duration such as `'10m'`: the user signed in or re-proved (`reprove`) within it, else a 403, as `guard({ fresh })` does.
|
|
53
|
+
fresh?: Duration | undefined
|
|
50
54
|
bare?: true | undefined
|
|
51
55
|
}
|
|
52
56
|
|
|
@@ -71,6 +75,14 @@ const servedSockets = new WeakSet<object>()
|
|
|
71
75
|
// What a route, a guard or a gate asks of the user: a role, a predicate, or a list of which any one passes.
|
|
72
76
|
export type AuthRequirement<Role extends string> = Requirement<BareUser, Role>
|
|
73
77
|
|
|
78
|
+
// What a request with a `fresh` requirement is refused with while the user's last proof is older: the page or the app's client then asks for the password or the passkey again (`reprove`) and retries.
|
|
79
|
+
export const STALE_PROOF = { message: 'Confirm your identity to continue', data: { code: 'stale' } } as const
|
|
80
|
+
|
|
81
|
+
// The milliseconds of a `fresh` duration; a value that is no positive duration throws where the guard is made, not on a request.
|
|
82
|
+
export function freshMs(fresh: Duration): number {
|
|
83
|
+
return durationSeconds(fresh, 'fresh') * 1000
|
|
84
|
+
}
|
|
85
|
+
|
|
74
86
|
// A session a browser's cross-site POST or websocket upgrade reads as signed out and cannot write, a write answered with a 403: a plain Elysia app has no Origin check of kay's own.
|
|
75
87
|
function guardSession(session: Session<AuthSessionData>, refuse: () => boolean, refusal: () => Response): Session<AuthSessionData> {
|
|
76
88
|
const write = <Args extends unknown[]>(call: (...args: Args) => Promise<void>) => async (...args: Args): Promise<void> => {
|
|
@@ -88,10 +100,11 @@ function guardSession(session: Session<AuthSessionData>, refuse: () => boolean,
|
|
|
88
100
|
settings: session.settings,
|
|
89
101
|
regenerate: write(async () => session.regenerate()),
|
|
90
102
|
maxAge: write(async maxAge => session.maxAge(maxAge)),
|
|
103
|
+
start: write(async (data, options) => session.start(data, options)),
|
|
91
104
|
}
|
|
92
105
|
}
|
|
93
106
|
|
|
94
|
-
interface Groups<Scope extends string, Role extends string, OrgRole extends string> {
|
|
107
|
+
interface Groups<Scope extends string, Role extends string, OrgRole extends string, UserData extends object> {
|
|
95
108
|
password: PasswordMethods
|
|
96
109
|
email: EmailMethods
|
|
97
110
|
magicLink: MagicLinkMethods
|
|
@@ -100,11 +113,13 @@ interface Groups<Scope extends string, Role extends string, OrgRole extends stri
|
|
|
100
113
|
sessions: SessionMethods
|
|
101
114
|
tokens: TokenMethods<Scope>
|
|
102
115
|
oauthServer: OAuthServerMethods
|
|
103
|
-
admin: AdminMethods<Role>
|
|
116
|
+
admin: AdminMethods<Role, UserData>
|
|
104
117
|
organizations: OrganizationMethods<OrgRole>
|
|
105
118
|
account: AccountMethods
|
|
106
119
|
oauth: OAuthMethods
|
|
107
120
|
audit: AuditMethods
|
|
121
|
+
captcha: CaptchaMethods
|
|
122
|
+
proof: ProofMethods
|
|
108
123
|
}
|
|
109
124
|
|
|
110
125
|
// Auth for one request, as `auth` in the context: `ctx.locals.auth` in a page, an action or a guard.
|
|
@@ -116,7 +131,7 @@ export class Auth<Scope extends string = string, Role extends string = string, O
|
|
|
116
131
|
private tokenScopes: string[] | null = null
|
|
117
132
|
private linked = new WeakMap<UserRecord, Promise<User['providers']>>()
|
|
118
133
|
// Each group of methods, made on its first use.
|
|
119
|
-
private readonly groups: Partial<Groups<Scope, Role, OrgRole>> = {}
|
|
134
|
+
private readonly groups: Partial<Groups<Scope, Role, OrgRole, UserData>> = {}
|
|
120
135
|
|
|
121
136
|
private readonly session: Session<AuthSessionData>
|
|
122
137
|
// Set-Cookie lines this request's sign-in or sign-out adds to its response, which the plugin sends.
|
|
@@ -235,7 +250,7 @@ export class Auth<Scope extends string = string, Role extends string = string, O
|
|
|
235
250
|
|
|
236
251
|
// The signed-in user's bearer tokens.
|
|
237
252
|
get tokens(): TokenMethods<Scope> {
|
|
238
|
-
return this.groups.tokens ??= new TokenMethods<Scope>(this[STATE])
|
|
253
|
+
return this.groups.tokens ??= new TokenMethods<Scope>(this[STATE], async () => this.heldScopes())
|
|
239
254
|
}
|
|
240
255
|
|
|
241
256
|
// The consent page MCP clients send the user to, and the apps they approved.
|
|
@@ -244,8 +259,8 @@ export class Auth<Scope extends string = string, Role extends string = string, O
|
|
|
244
259
|
}
|
|
245
260
|
|
|
246
261
|
// Listing, banning and impersonating users and granting them roles, for the `admin` option's users.
|
|
247
|
-
get admin(): AdminMethods<Role> {
|
|
248
|
-
return this.groups.admin ??= new AdminMethods<Role>(this[STATE])
|
|
262
|
+
get admin(): AdminMethods<Role, UserData> {
|
|
263
|
+
return this.groups.admin ??= new AdminMethods<Role, UserData>(this[STATE], async () => this.adminUser())
|
|
249
264
|
}
|
|
250
265
|
|
|
251
266
|
// The organizations of the `organizations` option.
|
|
@@ -270,6 +285,16 @@ export class Auth<Scope extends string = string, Role extends string = string, O
|
|
|
270
285
|
return this.groups.audit ??= new AuditMethods(this[STATE])
|
|
271
286
|
}
|
|
272
287
|
|
|
288
|
+
// What a page needs to show the CAPTCHA the next action asks for.
|
|
289
|
+
get captcha(): CaptchaMethods {
|
|
290
|
+
return this.groups.captcha ??= new CaptchaMethods(this[STATE])
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// Whether the user proved themselves lately, and proving again before a sensitive change.
|
|
294
|
+
get proof(): ProofMethods {
|
|
295
|
+
return this.groups.proof ??= new ProofMethods(this[STATE], freshMs)
|
|
296
|
+
}
|
|
297
|
+
|
|
273
298
|
// The signed-in user, or the owner of the request's `Authorization: Bearer` token, or null; read on first use, and again past 30 seconds on a websocket.
|
|
274
299
|
async user(): Promise<User<UserData> | null> {
|
|
275
300
|
const record = await this.record()
|
|
@@ -309,7 +334,7 @@ export class Auth<Scope extends string = string, Role extends string = string, O
|
|
|
309
334
|
if (signIn !== undefined && isNavigation(this.request))
|
|
310
335
|
redirect(this.signInLink(signIn))
|
|
311
336
|
|
|
312
|
-
return deny(401, 'Sign in to continue')
|
|
337
|
+
return deny(401, { message: 'Sign in to continue' })
|
|
313
338
|
}
|
|
314
339
|
|
|
315
340
|
const user = publicUser(record) as BareUser<UserData>
|
|
@@ -317,14 +342,22 @@ export class Auth<Scope extends string = string, Role extends string = string, O
|
|
|
317
342
|
if (options.require !== undefined && !(await this.core.access.authorize(user as BareUser, options.require, READ_METHODS.has(this.request.method) ? 'read' : 'write', {})))
|
|
318
343
|
return deny(403)
|
|
319
344
|
|
|
320
|
-
if (!scopeAllows(await this.
|
|
345
|
+
if (!scopeAllows(await this.heldScopes(), options.scope))
|
|
321
346
|
return deny(403)
|
|
322
347
|
|
|
348
|
+
if (options.fresh !== undefined && !(await this.proof.recent(options.fresh)))
|
|
349
|
+
return deny(403, STALE_PROOF)
|
|
350
|
+
|
|
323
351
|
return options.bare ? user : { ...user, providers: await this.providersOf(record) }
|
|
324
352
|
}
|
|
325
353
|
|
|
326
|
-
|
|
354
|
+
/** @deprecated Use `admin.require()`. Removed in 1.108.0; `deprecated-auth-methods` rewrites it. */
|
|
327
355
|
async requireAdmin(): Promise<User<UserData>> {
|
|
356
|
+
return this.admin.require()
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// What `admin.require()` answers with.
|
|
360
|
+
private async adminUser(): Promise<User<UserData>> {
|
|
328
361
|
if (!this.core.admin)
|
|
329
362
|
return stoppers(this.request).deny(404)
|
|
330
363
|
|
|
@@ -365,10 +398,10 @@ export class Auth<Scope extends string = string, Role extends string = string, O
|
|
|
365
398
|
const record = await this.core.store.users.get(user.id)
|
|
366
399
|
|
|
367
400
|
if (!record)
|
|
368
|
-
throw new
|
|
401
|
+
throw new KayError('helper-failed', `kayjs-auth: no user ${user.id} to sign in`)
|
|
369
402
|
|
|
370
403
|
if (banned(record))
|
|
371
|
-
throw new
|
|
404
|
+
throw new KayError('helper-failed', `kayjs-auth: user ${user.id} is banned`)
|
|
372
405
|
|
|
373
406
|
await chooseRemember(this[STATE], options.remember)
|
|
374
407
|
await this.establish(record, 'app')
|
|
@@ -439,7 +472,7 @@ export class Auth<Scope extends string = string, Role extends string = string, O
|
|
|
439
472
|
}
|
|
440
473
|
|
|
441
474
|
// Signs this browser in as a new guest, a user with no email and no password whom registering or an OAuth sign-in later makes a real account, keeping their id; the guest signed in already answers as is. Counted as registering is, and CAPTCHA-checked as `guest`.
|
|
442
|
-
async signInAsGuest(options: { captcha?: string | undefined } = {}): Promise<
|
|
475
|
+
async signInAsGuest(options: { captcha?: string | undefined } = {}): Promise<Result<{ user: BareUser }, 'limited' | 'captcha' | 'signed-in' | 'off'>> {
|
|
443
476
|
const current = await this.record()
|
|
444
477
|
|
|
445
478
|
if (current)
|
|
@@ -467,58 +500,56 @@ export class Auth<Scope extends string = string, Role extends string = string, O
|
|
|
467
500
|
return featuresOf(this.core)
|
|
468
501
|
}
|
|
469
502
|
|
|
470
|
-
|
|
503
|
+
/** @deprecated Use `oauthServer.resource()`. Removed in 1.108.0; `deprecated-auth-methods` rewrites it. */
|
|
471
504
|
oauthResource(path: string, name: string): Record<string, unknown> | null {
|
|
472
|
-
|
|
473
|
-
return null
|
|
474
|
-
|
|
475
|
-
const root = siteRoot(this.core, this.request)
|
|
476
|
-
|
|
477
|
-
return protectedResourceMetadata(this.core, root, `${root}${path}`, name)
|
|
505
|
+
return this.oauthServer.resource(path, name)
|
|
478
506
|
}
|
|
479
507
|
|
|
480
|
-
|
|
508
|
+
/** @deprecated Use `oauthServer.origin()`. Removed in 1.108.0; `deprecated-auth-methods` rewrites it. */
|
|
481
509
|
oauthOrigin(): string | undefined {
|
|
482
|
-
return this.
|
|
510
|
+
return this.oauthServer.origin()
|
|
483
511
|
}
|
|
484
512
|
|
|
485
|
-
|
|
513
|
+
/** @deprecated Use `oauthServer.fixed()`. Removed in 1.108.0; `deprecated-auth-methods` rewrites it. */
|
|
486
514
|
oauthFixed(): boolean {
|
|
487
|
-
return
|
|
515
|
+
return this.oauthServer.fixed()
|
|
488
516
|
}
|
|
489
517
|
|
|
490
|
-
|
|
518
|
+
/** @deprecated Use `captcha.required()`. Removed in 1.108.0; `deprecated-auth-methods` rewrites it. */
|
|
491
519
|
async captchaRequired(action: CaptchaAction): Promise<boolean> {
|
|
492
|
-
return
|
|
520
|
+
return this.captcha.required(action)
|
|
493
521
|
}
|
|
494
522
|
|
|
495
|
-
|
|
523
|
+
/** @deprecated Use `captcha.challenge()`. Removed in 1.108.0; `deprecated-auth-methods` rewrites it. */
|
|
496
524
|
async captchaChallenge(action: CaptchaAction): Promise<string | null> {
|
|
497
|
-
return
|
|
525
|
+
return this.captcha.challenge(action)
|
|
498
526
|
}
|
|
499
527
|
|
|
500
|
-
|
|
501
|
-
async provedLately(): Promise<boolean> {
|
|
502
|
-
return
|
|
528
|
+
/** @deprecated Use `proof.recent()`. Removed in 1.108.0; `deprecated-auth-methods` rewrites it. */
|
|
529
|
+
async provedLately(fresh?: Duration): Promise<boolean> {
|
|
530
|
+
return this.proof.recent(fresh)
|
|
503
531
|
}
|
|
504
532
|
|
|
505
|
-
|
|
506
|
-
async reprove(proof: Proof): Promise<
|
|
507
|
-
|
|
533
|
+
/** @deprecated Use `proof.renew()`. Removed in 1.108.0; `deprecated-auth-methods` rewrites it. */
|
|
534
|
+
async reprove(proof: Proof): Promise<Result<object, ProofFailure>> {
|
|
535
|
+
return this.proof.renew(proof)
|
|
536
|
+
}
|
|
508
537
|
|
|
509
|
-
|
|
538
|
+
/** @deprecated Use `tokens.scopes()`. Removed in 1.108.0; `deprecated-auth-methods` rewrites it. */
|
|
539
|
+
async scopes(): Promise<string[] | null> {
|
|
540
|
+
return this.heldScopes()
|
|
510
541
|
}
|
|
511
542
|
|
|
512
543
|
// The scopes of the bearer token this request came with; null for a session, or a token with every scope.
|
|
513
|
-
async
|
|
544
|
+
private async heldScopes(): Promise<string[] | null> {
|
|
514
545
|
await this.record()
|
|
515
546
|
|
|
516
547
|
return this.tokenScopes && [...this.tokenScopes]
|
|
517
548
|
}
|
|
518
549
|
|
|
519
|
-
|
|
550
|
+
/** @deprecated Use `tokens.hasScope()`. Removed in 1.108.0; `deprecated-auth-methods` rewrites it. */
|
|
520
551
|
async hasScope(scope: Scope): Promise<boolean> {
|
|
521
|
-
return
|
|
552
|
+
return this.tokens.hasScope(scope)
|
|
522
553
|
}
|
|
523
554
|
|
|
524
555
|
// The ids of the users holding `role`, one of the `roles` option or a role above it in its hierarchy, banned users left out, for server code that tells them something (a notification). Needs a signed-in user, and reads the 10,000 newest users at most.
|
|
@@ -654,7 +685,7 @@ export function authOf(ctx: object): Auth {
|
|
|
654
685
|
const auth = (ctx as { auth?: unknown }).auth
|
|
655
686
|
|
|
656
687
|
if (!(auth instanceof Auth))
|
|
657
|
-
throw new
|
|
688
|
+
throw new KayError('config-invalid', 'kayjs-auth: no `auth` in this context; `.use(auth.plugin)` before the routes and pages that read it')
|
|
658
689
|
|
|
659
690
|
return auth as Auth
|
|
660
691
|
}
|
|
@@ -665,7 +696,7 @@ export function requestAuth<Scope extends string, Role extends string, OrgRole e
|
|
|
665
696
|
|
|
666
697
|
// Elysia uses a plugin once per app, so a plugin of the app's own that used the session plugin first keeps it to itself, out of the routes auth reaches.
|
|
667
698
|
if (!session)
|
|
668
|
-
throw new
|
|
699
|
+
throw new KayError('outside-request', 'kayjs-auth: no session reaches this route. Use the session plugin on the app itself, or leave it to auth.plugin, rather than in a plugin of the app\'s own before auth.plugin')
|
|
669
700
|
|
|
670
701
|
core.settle()
|
|
671
702
|
|
package/src/requiredTwoFactor.ts
CHANGED
|
@@ -55,7 +55,7 @@ export async function lacksTwoFactor(state: RequestState, user: BareUser, ask: T
|
|
|
55
55
|
// What `ctx.redirect` and `ctx.deny` are in a guard, a page or an action.
|
|
56
56
|
export interface Stoppers {
|
|
57
57
|
redirect: (location: string) => never
|
|
58
|
-
deny: (status?: number, message?: string) => never
|
|
58
|
+
deny: (status?: number, options?: { message?: string | undefined }) => never
|
|
59
59
|
}
|
|
60
60
|
|
|
61
61
|
// A page opening goes to the security page to turn two-factor on, coming back after; anything else, and an app with no such page, gets the 403.
|
|
@@ -67,5 +67,5 @@ export function sendToEnrolment(core: Core, request: Request, { redirect, deny }
|
|
|
67
67
|
redirect(withBack(core.securityPage, localPath(here.pathname + here.search, '/')))
|
|
68
68
|
}
|
|
69
69
|
|
|
70
|
-
return deny(403, 'Two-factor authentication is required')
|
|
70
|
+
return deny(403, { message: 'Two-factor authentication is required' })
|
|
71
71
|
}
|
package/src/routes.ts
CHANGED
|
@@ -20,7 +20,7 @@ const UNSAFE_FILE_NAME = /[^\w.-]/g
|
|
|
20
20
|
|
|
21
21
|
// What the routes read of Elysia's context.
|
|
22
22
|
interface RouteContext {
|
|
23
|
-
auth: Pick<Auth, typeof STATE | 'account' | 'signOut'
|
|
23
|
+
auth: Pick<Auth, typeof STATE | 'account' | 'signOut'> & { admin: Pick<Auth['admin'], 'stopImpersonating'> }
|
|
24
24
|
request: Request
|
|
25
25
|
body: unknown
|
|
26
26
|
query: Record<string, unknown>
|
|
@@ -117,7 +117,7 @@ export async function cancelDeletionRoute({ auth, body, redirect, request }: Rou
|
|
|
117
117
|
return redirect(afterwards(body, core), 303)
|
|
118
118
|
}
|
|
119
119
|
|
|
120
|
-
// A GET, so a sign-in link works without JavaScript: give it `data-
|
|
120
|
+
// A GET, so a sign-in link works without JavaScript: give it `data-prefetch="false"` so a hover starts nothing.
|
|
121
121
|
export async function startOAuthRoute({ auth, params: { provider = '' }, query, redirect, status }: RouteContext, core: Core, failurePage: string | undefined) {
|
|
122
122
|
const started = !core.oauth.has(provider) ? undefined : await (await load.flow()).startOAuth(auth[STATE], provider, { redirect: text(query.redirect), remember: query.remember === undefined ? undefined : query.remember === '1' })
|
|
123
123
|
|
package/src/sessions.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { SessionSettings } from 'kay/server'
|
|
2
|
-
import type {
|
|
2
|
+
import type { Core } from './core'
|
|
3
3
|
import type { Device } from './device'
|
|
4
|
-
import type {
|
|
4
|
+
import type { Result } from './failure'
|
|
5
5
|
import type { RequestState } from './state'
|
|
6
6
|
import type { SessionRecord, UserRecord } from './store'
|
|
7
7
|
import { durationSeconds } from 'kay/library'
|
|
@@ -12,10 +12,6 @@ import { log } from './log'
|
|
|
12
12
|
|
|
13
13
|
const USER_AGENT_MAX_LENGTH = 512
|
|
14
14
|
|
|
15
|
-
export type RevokeSessionResult = { ok: true } | AuthFailed<'signed-out' | 'not-found'>
|
|
16
|
-
|
|
17
|
-
export type GuestSignInResult = { ok: true, user: BareUser } | AuthFailed<'limited' | 'captcha' | 'signed-in' | 'off'>
|
|
18
|
-
|
|
19
15
|
// Where the user is signed in, as the app lists it.
|
|
20
16
|
export interface UserSession {
|
|
21
17
|
id: string
|
|
@@ -55,7 +51,7 @@ export async function liveSession(state: RequestState, found: SessionRecord | un
|
|
|
55
51
|
}
|
|
56
52
|
|
|
57
53
|
// Ends one of the signed-in user's sessions, effective on its next request; ending this one signs out through `signOut`.
|
|
58
|
-
export async function revokeSession(state: RequestState, id: string, signOut: () => Promise<void>): Promise<
|
|
54
|
+
export async function revokeSession(state: RequestState, id: string, signOut: () => Promise<void>): Promise<Result<object, 'signed-out' | 'not-found'>> {
|
|
59
55
|
const record = await state.current()
|
|
60
56
|
const signedIn = await state.session.get('auth')
|
|
61
57
|
|
package/src/setup.ts
CHANGED
|
@@ -70,9 +70,11 @@ function hooked<Args extends unknown[], Result>(hook: ((...args: never[]) => Res
|
|
|
70
70
|
return hook && ((...args: Args) => hook(event(...args) as never))
|
|
71
71
|
}
|
|
72
72
|
|
|
73
|
-
// `
|
|
74
|
-
function signUpHook(hook: AuthOptions<AuthSessionData, string
|
|
75
|
-
|
|
73
|
+
// `afterSignUp` as the flows call it: told through `dispatch`, so a throw is reported and never fails the sign-up that happened.
|
|
74
|
+
function signUpHook({ afterSignUp: hook = undefined, onSignUp }: Pick<AuthOptions<AuthSessionData, string>, 'afterSignUp' | 'onSignUp'>): Core['onSignUp'] {
|
|
75
|
+
hook ??= onSignUp
|
|
76
|
+
|
|
77
|
+
return hook && (async (user, profile) => dispatch('auth.afterSignUp', [hook as never], { user, profile }, { context: await authContext() }))
|
|
76
78
|
}
|
|
77
79
|
|
|
78
80
|
// `beforeDelete` as the erase asks it: a refusal answers the failure of kind `refused`, carrying the status and message the hook gave.
|
|
@@ -329,7 +331,7 @@ export function createCore<Data extends AuthSessionData, Role extends string, Pr
|
|
|
329
331
|
access: access as unknown as Access<string>,
|
|
330
332
|
...admin !== undefined && { admin: async user => access.authorize(user, admin, 'write', {}) },
|
|
331
333
|
guard: guardOptions => guardOf(core, guardOptions),
|
|
332
|
-
onSignUp: signUpHook(options
|
|
334
|
+
onSignUp: signUpHook(options),
|
|
333
335
|
onProviderProfile: hooked(options.profileFields, (user, profile) => ({ user, profile })),
|
|
334
336
|
userData: options.user && userDataRules(options.user),
|
|
335
337
|
beforeDelete: deleteHook(options.beforeDelete),
|
package/src/sqlite.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { StoreUrl } from './own'
|
|
2
|
+
|
|
3
|
+
// kayjs-auth's data in a SQLite file, through pg-orm: `auth({ store: sqliteAuth('data/users.sqlite') })`. The file is made, and its `kay_*` tables with it, when the server starts; a relative path is kept under the project root.
|
|
4
|
+
export function sqliteAuth(path: string): StoreUrl {
|
|
5
|
+
return { url: `sqlite://${path}` }
|
|
6
|
+
}
|
package/src/test.ts
CHANGED
|
@@ -2,7 +2,9 @@ import type { BareUser } from './core'
|
|
|
2
2
|
import type { OAuthSite, OAuthTest } from './oauthTest'
|
|
3
3
|
import type { CreateUserInput } from './password'
|
|
4
4
|
import type { TotpEnrolment } from './twoFactor'
|
|
5
|
+
import { KayError } from 'kay/library'
|
|
5
6
|
import { builtOwn } from './own'
|
|
7
|
+
import { signInHook } from './testHook'
|
|
6
8
|
|
|
7
9
|
// What `auth.test(site)` gives.
|
|
8
10
|
export interface AuthTest {
|
|
@@ -10,6 +12,8 @@ export interface AuthTest {
|
|
|
10
12
|
signInAs: (who: Omit<CreateUserInput, 'roles'> & { roles?: string[] | undefined, data?: object | undefined }) => Promise<BareUser>
|
|
11
13
|
// Signs the site out, its other cookies kept.
|
|
12
14
|
signOut: () => void
|
|
15
|
+
// Signs the site out, as the start of a test wants.
|
|
16
|
+
reset: () => void
|
|
13
17
|
// The `Cookie` header of a new session signed in as that user.
|
|
14
18
|
sessionCookie: (userId: string, options?: { secure?: boolean }) => Promise<string>
|
|
15
19
|
// Turns two-factor on for that member as the app would, so a password sign-in asks for a code: the authenticator's `secret`, `code(offset?)` for the current step and the `recoveryCodes`, all usable at the next sign-in. Throws for a missing member or one who has it already.
|
|
@@ -23,19 +27,20 @@ export interface OwnTest {
|
|
|
23
27
|
}
|
|
24
28
|
|
|
25
29
|
// The `auth.test(site)` of an app whose kay.config.ts holds `auth()` and no `src/auth.ts` module: the auth that site's `testSite()` built, found as a call needs it, so call it after `testSite()`.
|
|
26
|
-
export function
|
|
30
|
+
export function test(site: OAuthSite): AuthTest {
|
|
27
31
|
const made = () => {
|
|
28
32
|
const own = builtOwn(site)
|
|
29
33
|
|
|
30
34
|
if (!own)
|
|
31
|
-
throw new
|
|
35
|
+
throw new KayError('config-invalid', 'kayjs-auth: test(site) found no `auth()` built for this test site: await `testSite()` first, and give `test` the site it returned, of a project whose kay.config.ts registers `auth()` with no `module`')
|
|
32
36
|
|
|
33
37
|
return own.test(site)
|
|
34
38
|
}
|
|
35
39
|
|
|
36
|
-
|
|
40
|
+
const helper: AuthTest = {
|
|
37
41
|
signInAs: async who => made().signInAs(who),
|
|
38
42
|
signOut: () => made().signOut(),
|
|
43
|
+
reset: () => made().signOut(),
|
|
39
44
|
sessionCookie: async (userId, options) => made().sessionCookie(userId, options),
|
|
40
45
|
enrollTotp: async userId => made().enrollTotp(userId),
|
|
41
46
|
oauth: {
|
|
@@ -43,4 +48,11 @@ export function authTest(site: OAuthSite): AuthTest {
|
|
|
43
48
|
signIn: async (provider, options) => made().oauth.signIn(provider, options),
|
|
44
49
|
},
|
|
45
50
|
}
|
|
51
|
+
|
|
52
|
+
site.joinSignIn?.(signInHook(helper))
|
|
53
|
+
|
|
54
|
+
return helper
|
|
46
55
|
}
|
|
56
|
+
|
|
57
|
+
/** @deprecated `test(site)`, the same helper under the name every library's test entry shares. Removed in 1.108.0; `deprecated-test-helpers` rewrites it. */
|
|
58
|
+
export const authTest = test
|
package/src/testHelpers.ts
CHANGED
|
@@ -2,9 +2,11 @@ import type { Elysia } from 'elysia'
|
|
|
2
2
|
import type { BareUser, Core } from './core'
|
|
3
3
|
import type { OAuthSite, OAuthTest } from './oauthTest'
|
|
4
4
|
import type { CreateUserInput } from './password'
|
|
5
|
+
import type { AuthTest } from './test'
|
|
5
6
|
import type { TotpEnrolment } from './twoFactor'
|
|
6
7
|
import { load } from './load'
|
|
7
8
|
import { dropSession } from './testCookies'
|
|
9
|
+
import { signInHook } from './testHook'
|
|
8
10
|
|
|
9
11
|
// Who `signInAs` signs in: `createUser`'s fields and the app's own user `data` fields.
|
|
10
12
|
export type TestMember<Role extends string, UserData extends object> = Omit<CreateUserInput, 'roles'> & { roles?: Role[] | undefined, data?: { [Field in keyof UserData]?: UserData[Field] | undefined } | undefined }
|
|
@@ -47,12 +49,19 @@ export function testHelpers<Role extends string, UserData extends object>(core:
|
|
|
47
49
|
return {
|
|
48
50
|
...helpers,
|
|
49
51
|
// The test calls on one test site, so a test names the site once: `const as = auth.test(site)`, then `await as.signInAs({ email })` and `as.signOut()`.
|
|
50
|
-
test: (site: OAuthSite) =>
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
52
|
+
test: (site: OAuthSite) => {
|
|
53
|
+
const own = {
|
|
54
|
+
signInAs: async (who: TestMember<Role, UserData>) => helpers.signInAs(site, who),
|
|
55
|
+
signOut: () => helpers.signOut(site),
|
|
56
|
+
reset: () => helpers.signOut(site),
|
|
57
|
+
sessionCookie: async (userId: string, cookieOptions?: { secure?: boolean }) => helpers.sessionCookie(userId, cookieOptions),
|
|
58
|
+
enrollTotp: async (userId: string) => helpers.enrollTotp(userId),
|
|
59
|
+
oauth: helpers.oauth(site),
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
site.joinSignIn?.(signInHook(own as unknown as AuthTest))
|
|
63
|
+
|
|
64
|
+
return own
|
|
65
|
+
},
|
|
57
66
|
}
|
|
58
67
|
}
|
package/src/testHook.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { SignInHook } from 'kay/test'
|
|
2
|
+
import type { BareUser } from './core'
|
|
3
|
+
import type { CreateUserInput } from './password'
|
|
4
|
+
import type { AuthTest } from './test'
|
|
5
|
+
|
|
6
|
+
declare module 'kay/test' {
|
|
7
|
+
interface SignInFields extends Omit<CreateUserInput, 'roles'> {
|
|
8
|
+
// The roles of the member `site.signInAs` makes, with the `email` or `username` kayjs-auth reads.
|
|
9
|
+
roles?: string[] | undefined
|
|
10
|
+
// The fields of the app's `user` schema.
|
|
11
|
+
data?: object | undefined
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
interface SignedIn {
|
|
15
|
+
// The member the site was signed in as.
|
|
16
|
+
user?: BareUser | undefined
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// The part `site.signInAs` and `site.signOut` take in auth: a `who` with an `email` or a `username` signs a member in.
|
|
21
|
+
export function signInHook(as: Pick<AuthTest, 'signInAs' | 'signOut'>): SignInHook {
|
|
22
|
+
return {
|
|
23
|
+
name: 'auth',
|
|
24
|
+
signIn: async (who) => {
|
|
25
|
+
const { email, username } = who as { email?: string, username?: string }
|
|
26
|
+
|
|
27
|
+
return email === undefined && username === undefined ? undefined : { user: await as.signInAs(who) }
|
|
28
|
+
},
|
|
29
|
+
signOut: () => as.signOut(),
|
|
30
|
+
}
|
|
31
|
+
}
|
package/src/testing.ts
CHANGED
|
@@ -2,6 +2,7 @@ import type { Elysia } from 'elysia'
|
|
|
2
2
|
import type { BareUser, Core } from './core'
|
|
3
3
|
import type { CreateUserInput } from './password'
|
|
4
4
|
import { Elysia as ElysiaApp } from 'elysia'
|
|
5
|
+
import { KayError } from 'kay/library'
|
|
5
6
|
import { publicUser } from './core'
|
|
6
7
|
import { normalizeEmail, normalizeUsername } from './rules'
|
|
7
8
|
import { dropSession, signedInCookies } from './testCookies'
|
|
@@ -10,12 +11,12 @@ import { mergedData } from './userData'
|
|
|
10
11
|
// `held` with `data` laid over it as the `user` schema accepts it; throws for data it refuses, or when the app declared no schema.
|
|
11
12
|
function signInAsData(core: Core, held: Record<string, unknown> | undefined, data: object): Record<string, unknown> {
|
|
12
13
|
if (!core.userData)
|
|
13
|
-
throw new
|
|
14
|
+
throw new KayError('argument-invalid', 'kayjs-auth: signInAs was given `data`, and authCore has no `user` schema')
|
|
14
15
|
|
|
15
16
|
const merged = mergedData(core.userData, held, data)
|
|
16
17
|
|
|
17
18
|
if (merged === undefined)
|
|
18
|
-
throw new
|
|
19
|
+
throw new KayError('argument-invalid', 'kayjs-auth: signInAs was given `data` that does not fit the `user` schema')
|
|
19
20
|
|
|
20
21
|
return merged
|
|
21
22
|
}
|
|
@@ -37,7 +38,7 @@ function signInAsMismatch(core: Core, user: BareUser, given: { email: string | u
|
|
|
37
38
|
differs.push('data')
|
|
38
39
|
|
|
39
40
|
if (differs.length > 0)
|
|
40
|
-
throw new
|
|
41
|
+
throw new KayError('argument-invalid', `kayjs-auth: signInAs found a member whose ${differs.join(', ')} differ from the fields given`)
|
|
41
42
|
}
|
|
42
43
|
|
|
43
44
|
// The Set-Cookie lines of a new session signed in as `userId`, minted by the plugin signing them in over a request of its own.
|
|
@@ -87,7 +88,7 @@ export async function signInAs(core: Core, plugin: Elysia, site: { cookies: Bun.
|
|
|
87
88
|
const created = await (await import('./password')).createUser(core, fields)
|
|
88
89
|
|
|
89
90
|
if (!created.ok)
|
|
90
|
-
throw new
|
|
91
|
+
throw new KayError('argument-invalid', `kayjs-auth: signInAs could not make the member: ${JSON.stringify(created.errors)}`)
|
|
91
92
|
|
|
92
93
|
user = created.user
|
|
93
94
|
|