@kayjs/auth 1.105.0 → 1.106.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.
@@ -21,7 +21,7 @@ import { passkeyAttestation } from '@kayjs/auth'
21
21
 
22
22
  // The app's actions, `response` typed as `passkeys.register` takes it and refused before the handler when a part is missing
23
23
  export const passkeyOptions = action(proofSchema, async (proof, ctx) => ctx.locals.auth.passkeys.registrationOptions(proof))
24
- export const addPasskey = action(s.Object({ response: passkeyAttestation, name: s.Optional(s.String()) }), async ({ response, name }, ctx) => ctx.locals.auth.passkeys.register(response, name))
24
+ export const addPasskey = action({ response: passkeyAttestation, name: s.string({ optional: true }) }, async ({ response, name }, ctx) => ctx.locals.auth.passkeys.register(response, name))
25
25
  ```
26
26
 
27
27
  ```ts
@@ -47,7 +47,7 @@ catch (caught) {
47
47
  - The provider presets (github, discord, google, microsoft, gitlab, apple, linkedin, facebook, twitch, slack, x), their options, `oidcProvider` and `kay env` names are in [OAuth provider presets](oauth-providers.md); a preset takes `{ scopes, params }` and a provider of your own is any `OAuthProvider`.
48
48
  - The flow keeps its state and PKCE verifier in the session, so a callback works once, in the browser that started it, within ten minutes. A callback whose `state` is wrong or missing is refused without spending the flow, so a page on another site loading the callback URL cannot kill a sign-in in flight. Starting the same sign-in again (`GET /auth/<provider>`, same `redirect`) goes on with the pending flow, the same `state`; a start with another `redirect` replaces a sign-in in flight, and none replaces a provider link in flight (`oauth.link`): it answers `?error=oauth`. A site whose `site` is https refuses a provider endpoint, discovered ones included, on plain http whatever `NODE_ENV` says. A provider failing the exchange is logged, and a sign-in refused for a known account (`banned`, or `taken` when linking) reports `sign-in-failed` with `method` `oauth`. `redirect` is kept to a path on the site. For the app's own redirects, kay's `localPath(path, fallback)` answers the path normalised, dot segments resolved, and `fallback` for anything that would leave the site once resolved or decoded; a bare `%` in the query or hash is kept, while a malformed escape in the path is refused.
49
49
  - A provider account signs into the user it is linked to. A new one signs up a new user, taking its email and its name only when no other user has them: no account is ever merged into another by email. `afterSignUp({ user, profile, context })` runs for every new user, to create the app's own records; `profile` is `undefined` for a password sign-up. A throw is logged and reported (source `auth.afterSignUp`) and the sign-up stands.
50
- - `profileFields({ user, profile })` runs whenever a provider answers for a user (every OAuth sign-in, the first included after `afterSignUp`, and a link), before any second factor, to refresh what the app keeps from the profile, such as an avatar or a display name. A failure in it is logged and the sign-in goes on. With a `user` schema (`user: s.Object({ avatar: s.Optional(s.String()) })`) what it returns is laid over `user.data`: only declared top-level fields count, one left out or `undefined` keeps its value, and a result the schema refuses or over 16 KB of JSON drops the whole patch, logged. The update is read-modify-write, so sign-ins at once can overwrite each other's fields. With `profileFields: ({ profile }) => ({ avatar: profile.avatar ?? undefined })`, `(await auth.user()).data.avatar` is typed from the schema, and `user.providers.discord?.id` is the id a linked provider gave.
50
+ - `profileFields({ user, profile })` runs whenever a provider answers for a user (every OAuth sign-in, the first included after `afterSignUp`, and a link), before any second factor, to refresh what the app keeps from the profile, such as an avatar or a display name. A failure in it is logged and the sign-in goes on. With a `user` schema (`user: s.object({ avatar: s.string({ optional: true }) })`) what it returns is laid over `user.data`: only declared top-level fields count, one left out or `undefined` keeps its value, and a result the schema refuses or over 16 KB of JSON drops the whole patch, logged. The update is read-modify-write, so sign-ins at once can overwrite each other's fields. With `profileFields: ({ profile }) => ({ avatar: profile.avatar ?? undefined })`, `(await auth.user()).data.avatar` is typed from the schema, and `user.providers.discord?.id` is the id a linked provider gave.
51
51
  - `allow(profile)` is asked before any user is touched; false refuses, as an allowlist of provider ids does.
52
52
  - `oauth.link(provider, proof, { redirect })` links a provider account to the signed-in user instead, refused when another user has it linked: from an action, `ctx.redirect(result.url)` sends the browser to the provider, which comes back to `redirect`. A linked provider is a way in that outlives every sign-out, so linking takes a proof, the second factor when it is on (see Re-proof); `'not-found'` for a provider the app did not configure, `'unavailable'` when the provider failed.
53
53
  - A failure goes to `failurePage` as it is when set, else to `signInPage?error=<code>`, with `&redirect=` keeping the page the sign-in was started for: `oauth` (a state or code that did not check out, or a provider account without an id), `cancelled`, `refused`, `taken`, `unavailable` (the provider failed, answered nonsense or took over 10 seconds to answer), `signed-out` (a link whose user signed out before coming back).
@@ -10,7 +10,7 @@ An action signs a visitor in with `password.signIn` and redirects to where they
10
10
  --- server
11
11
  import { s, action } from 'kay'
12
12
 
13
- export const signIn = action(s.Object({ identifier: s.String({ maxLength: 254 }), password: s.String() }), async (input, ctx) => {
13
+ export const signIn = action({ identifier: s.string({ max: 254 }), password: s.string() }, async (input, ctx) => {
14
14
  const result = await ctx.locals.auth.password.signIn(input, { redirect: ctx.url.searchParams.get('redirect') ?? '/' })
15
15
 
16
16
  if (!result.ok)
@@ -47,9 +47,9 @@ The page a mailed link opens shows a button posting the token to an action, so o
47
47
  --- server
48
48
  import { s, action } from 'kay'
49
49
 
50
- export const query = s.Object({ token: s.Optional(s.String()) })
50
+ export const query = s.object({ token: s.string({ optional: true }) })
51
51
 
52
- export const spend = action(s.Object({ token: s.String() }), async ({ token }, ctx) => {
52
+ export const spend = action({ token: s.string() }, async ({ token }, ctx) => {
53
53
  const result = await ctx.locals.auth.magicLink.signIn(token)
54
54
 
55
55
  if (!result.ok)
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kayjs/auth",
3
3
  "type": "module",
4
- "version": "1.105.0",
4
+ "version": "1.106.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",
@@ -65,10 +65,10 @@
65
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"
66
66
  },
67
67
  "peerDependencies": {
68
- "@kayjs/ui": "~1.105.0",
68
+ "@kayjs/ui": "~1.106.0",
69
69
  "@kaynooo/pg-orm": "^7.1.2 || ^8.0.0",
70
70
  "elysia": "^1.4.31",
71
- "kay": "~1.105.0"
71
+ "kay": "~1.106.0"
72
72
  },
73
73
  "peerDependenciesMeta": {
74
74
  "@kaynooo/pg-orm": {
@@ -80,9 +80,9 @@
80
80
  "jose": "^6.2.13"
81
81
  },
82
82
  "devDependencies": {
83
- "@kayjs/mail": "~1.105.0",
84
- "@kayjs/ui": "~1.105.0",
85
- "@kaynooo/eslint": "^7.1.6",
83
+ "@kayjs/mail": "~1.106.0",
84
+ "@kayjs/ui": "~1.106.0",
85
+ "@kaynooo/eslint": "^8.0.3",
86
86
  "@kaynooo/pg-orm": "^8.1.4",
87
87
  "@types/bun": "^1.4.4",
88
88
  "elysia": "^1.4.31",
@@ -194,7 +194,7 @@ export function oidcProvider(opts: OpenIdOptions & { issuer: string, name?: stri
194
194
 
195
195
  for (const field of ['authorization_endpoint', 'token_endpoint', 'jwks_uri']) {
196
196
  if (typeof doc[field] !== 'string')
197
- throw new Error(`discovery document has no ${field}`)
197
+ throw new TypeError(`discovery document has no ${field}`)
198
198
  }
199
199
 
200
200
  for (const field of ['authorization_endpoint', 'token_endpoint', 'userinfo_endpoint', 'revocation_endpoint', 'jwks_uri']) {
package/src/own.ts CHANGED
@@ -91,11 +91,11 @@ function isPreset(app: true | PresetApp | OAuthApp): app is true | PresetApp {
91
91
  export function ownEnv(options: Pick<OwnOptions, 'oauth' | 'store'>) {
92
92
  const names = Object.entries(options.oauth ?? {}).filter(([, app]) => isPreset(app) && (app === true || app.clientId === undefined || app.clientSecret === undefined)).map(([name]) => name)
93
93
 
94
- return s.Object({
95
- ...options.store === undefined && { AUTH_DATABASE_URL: s.Optional(s.String({ description: 'the database kayjs-auth keeps its users in, a Postgres or SQLite url; the one of the app\'s store, else data/auth.sqlite (SQLite; data/auth.db where it exists), when unset' })) },
94
+ return s.object({
95
+ ...options.store === undefined && { AUTH_DATABASE_URL: s.string({ optional: true, description: 'the database kayjs-auth keeps its users in, a Postgres or SQLite url; the one of the app\'s store, else data/auth.sqlite (SQLite; data/auth.db where it exists), when unset' }) },
96
96
  ...Object.fromEntries(names.flatMap(name => [
97
- [`${name.toUpperCase()}_CLIENT_ID`, s.String({ description: `the ${name} OAuth app's client id`, requiredInProduction: true })],
98
- [`${name.toUpperCase()}_CLIENT_SECRET`, s.String({ description: `the ${name} OAuth app's client secret`, requiredInProduction: true })],
97
+ [`${name.toUpperCase()}_CLIENT_ID`, s.string({ description: `the ${name} OAuth app's client id`, requiredInProduction: true })],
98
+ [`${name.toUpperCase()}_CLIENT_SECRET`, s.string({ description: `the ${name} OAuth app's client secret`, requiredInProduction: true })],
99
99
  ])),
100
100
  })
101
101
  }
package/src/webauthn.ts CHANGED
@@ -248,7 +248,7 @@ function parseAuthData(bytes: Uint8Array): AuthData {
248
248
  const [extensions, end] = decodeCbor(bytes, offset)
249
249
 
250
250
  if (!(extensions instanceof Map))
251
- throw new Error('invalid extensions')
251
+ throw new TypeError('invalid extensions')
252
252
 
253
253
  offset = end
254
254
  }
@@ -286,7 +286,7 @@ async function importCoseKey(bytes: Uint8Array): Promise<CoseKey> {
286
286
  const [cose] = decodeCbor(bytes)
287
287
 
288
288
  if (!(cose instanceof Map))
289
- throw new Error('COSE key is not a map')
289
+ throw new TypeError('COSE key is not a map')
290
290
 
291
291
  const kty = cose.get(1)
292
292
  const alg = cose.get(3)