@cubicecho/server-kit 0.6.2 → 0.8.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/_agents/docs/04-auth.md +63 -2
- package/dist/auth/defaults.d.ts +15 -0
- package/dist/auth/defaults.js +8 -0
- package/dist/auth/index.d.ts +3 -1
- package/dist/auth/index.js +3 -1
- package/dist/auth/plugins.d.ts +36 -1
- package/dist/auth/plugins.js +10 -3
- package/dist/auth/preset.d.ts +6 -0
- package/dist/auth/preset.js +2 -0
- package/dist/auth/setup.d.ts +185 -0
- package/dist/auth/setup.js +291 -0
- package/dist/auth/sign-in-links.d.ts +35 -0
- package/dist/auth/sign-in-links.js +60 -0
- package/llms.txt +21 -1
- package/package.json +9 -2
package/_agents/docs/04-auth.md
CHANGED
|
@@ -2,6 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
`@cubicecho/server-kit/auth` has the better-auth options and sign-in plugins every server shares: sessions in Postgres, bearer tokens, emailed links, and OIDC with pairing. The app still calls `betterAuth`, so it adds its own plugins and hooks and keeps exact types.
|
|
4
4
|
|
|
5
|
+
- [Setting up a new instance](#setting-up-a-new-instance)
|
|
6
|
+
- [Links for another device, and recovery](#links-for-another-device-and-recovery)
|
|
7
|
+
- [Rate limiting sign-in](#rate-limiting-sign-in)
|
|
8
|
+
|
|
5
9
|
```ts
|
|
6
10
|
import { apiKey } from '@better-auth/api-key';
|
|
7
11
|
import { authPreset, signInPlugins } from '@cubicecho/server-kit/auth';
|
|
@@ -37,9 +41,66 @@ const auth = betterAuth({
|
|
|
37
41
|
- Set every `id` column with `id()`: the preset leaves ids to the database.
|
|
38
42
|
- OIDC is on by default. A server without it says `oidc: false`, and then needs no `sso_providers` table.
|
|
39
43
|
- `deliver: undefined` is an instance that cannot email. `sendsMagicLinks(auth)` says which it is.
|
|
40
|
-
- `paths` moves the app's `login`, `verify` and `
|
|
44
|
+
- `paths` moves the app's `login`, `verify`, `signedIn` and `link` pages.
|
|
41
45
|
- An option after the spread replaces the preset's whole value, so `session: { … }` has to repeat `expiresIn`.
|
|
42
|
-
-
|
|
46
|
+
- `/auth` needs three optional peers: `better-auth`, `@better-auth/sso` and `@cubicecho/better-auth-oidc-pairing`. Install all three in the server, with `oidc: false` too.
|
|
47
|
+
|
|
48
|
+
## Setting up a new instance
|
|
49
|
+
|
|
50
|
+
An instance with no account is set up through a gate, so that whoever finds it first does not own it. A code is always needed unless the operator opts out.
|
|
51
|
+
|
|
52
|
+
| `SETUP_CODE` | `OPEN_SETUP` | Who may set it up |
|
|
53
|
+
|---|---|---|
|
|
54
|
+
| unset | unset | Whoever has the code the server made up, which `setupNotice` puts in the boot log |
|
|
55
|
+
| set | any | Whoever has the operator's code |
|
|
56
|
+
| unset | `true` | Anyone who can reach it, for `SETUP_DEFAULTS.openMinutes` after it starts |
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
import { claimInstance, createSetupGate, isSetUp, setupNotice, setupProblem, signInPlugins, throttle } from '@cubicecho/server-kit/auth';
|
|
60
|
+
|
|
61
|
+
// preflight: refuse to boot on a short code, or an open setup at a public address.
|
|
62
|
+
const problem = setupProblem({ code: setupCode(), open: openSetup(), appUrl });
|
|
63
|
+
|
|
64
|
+
// boot: one gate per process.
|
|
65
|
+
const gate = createSetupGate({ code: setupCode(), open: openSetup(), startedAt });
|
|
66
|
+
const plugins = signInPlugins({
|
|
67
|
+
appUrl,
|
|
68
|
+
deliver,
|
|
69
|
+
setup: gate,
|
|
70
|
+
oidc: { clientName: 'Todo', canPair: async ({ userId }) => (userId === null ? mayPairUnowned(gate) : isAdmin(userId)) },
|
|
71
|
+
});
|
|
72
|
+
if ((await isSetUp(auth)) === false) {
|
|
73
|
+
console.log(`[setup] ${setupNotice(gate)}`);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// the setup mutation
|
|
77
|
+
throttle({ limiter, ip }, 'setup');
|
|
78
|
+
const { token, userId } = await claimInstance(auth, gate, { code, email, name });
|
|
79
|
+
|
|
80
|
+
// pairing a provider before there is an account: run it as the caller, and canPair asks gate.isAdmitted()
|
|
81
|
+
await gate.as(code, () => auth.api.pairOidcProvider({ body: { setupUrl }, headers }));
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
- With `setup`, the first account comes from `claimInstance` or an OIDC provider's callback, and from nothing else. Until then no link is emailed.
|
|
85
|
+
- One claim wins, across processes. Refusals are `FORBIDDEN` or `CONFLICT` with a `SetupRefusal` as `extensions.reason`. `asSetupRefusal` turns better-auth's own error into the same.
|
|
86
|
+
- A server for one person refuses the second account in its own `user.create.before`, which runs after the kit's.
|
|
87
|
+
- `canPair` has to check that there is no account as well: `gate.isAdmitted()` only says the caller has the code.
|
|
88
|
+
- A made-up code is the process's own, so run one process, or set `SETUP_CODE`.
|
|
89
|
+
- The claimed address is unverified. `changeEmail` changes it until a link or a provider verifies it, and does nothing for an address another account has.
|
|
90
|
+
|
|
91
|
+
## Links for another device, and recovery
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
import { createSignInLink, signInLinkUrl, spendSignInLink } from '@cubicecho/server-kit/auth';
|
|
95
|
+
|
|
96
|
+
const { token, expiresAt } = await createSignInLink(auth, userId);
|
|
97
|
+
const url = signInLinkUrl(appUrl, token);
|
|
98
|
+
const signedIn = await spendSignInLink(auth, token); // null: unknown, used or expired
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
- A link works once, for `signInLinkTtlMinutes`, and is stored as a hash. Its token is in the URL's fragment, which no proxy sees: the page at `AUTH_PATHS.link` reads it and spends it over GraphQL.
|
|
102
|
+
- Make one for the caller's own account, from a session and never from an API key. The recovery command is a script in the app that makes one for the owner and prints it.
|
|
103
|
+
- Call `throttle` before spending one.
|
|
43
104
|
|
|
44
105
|
## Rate limiting sign-in
|
|
45
106
|
|
package/dist/auth/defaults.d.ts
CHANGED
|
@@ -4,6 +4,8 @@ export interface AuthSettings {
|
|
|
4
4
|
sessionTtlDays: number;
|
|
5
5
|
/** How long an emailed sign-in link works. Short: it travels by mail. */
|
|
6
6
|
magicLinkTtlMinutes: number;
|
|
7
|
+
/** How long a link for another device, or from the recovery command, works. */
|
|
8
|
+
signInLinkTtlMinutes: number;
|
|
7
9
|
}
|
|
8
10
|
/** What `authPreset` and `signInPlugins` use when the app overrides nothing. */
|
|
9
11
|
export declare const AUTH_DEFAULTS: Readonly<AuthSettings>;
|
|
@@ -15,9 +17,22 @@ export interface AuthPaths {
|
|
|
15
17
|
verify: string;
|
|
16
18
|
/** Spends the one-time token an OIDC sign-in ends in. */
|
|
17
19
|
signedIn: string;
|
|
20
|
+
/** Spends the token of a link for another device, which is in the URL's fragment. */
|
|
21
|
+
link: string;
|
|
18
22
|
}
|
|
19
23
|
/** Where those pages are when the app overrides nothing. */
|
|
20
24
|
export declare const AUTH_PATHS: Readonly<AuthPaths>;
|
|
25
|
+
/** Setting up an instance that has no account. */
|
|
26
|
+
export interface SetupSettings {
|
|
27
|
+
/** How long after the server starts an open setup stays open. */
|
|
28
|
+
openMinutes: number;
|
|
29
|
+
/** The shortest code an operator may choose, in characters. */
|
|
30
|
+
minCodeLength: number;
|
|
31
|
+
/** How long one claim keeps others out, should the process die part way. */
|
|
32
|
+
claimSeconds: number;
|
|
33
|
+
}
|
|
34
|
+
/** What `createSetupGate`, `setupProblem` and `setupPlugin` use when the app overrides nothing. */
|
|
35
|
+
export declare const SETUP_DEFAULTS: Readonly<SetupSettings>;
|
|
21
36
|
/** The sign-in throttle. */
|
|
22
37
|
export interface RateLimitSettings {
|
|
23
38
|
/** Attempts allowed per key inside one window. */
|
package/dist/auth/defaults.js
CHANGED
|
@@ -3,12 +3,20 @@
|
|
|
3
3
|
export const AUTH_DEFAULTS = Object.freeze({
|
|
4
4
|
sessionTtlDays: 30,
|
|
5
5
|
magicLinkTtlMinutes: 15,
|
|
6
|
+
signInLinkTtlMinutes: 15,
|
|
6
7
|
});
|
|
7
8
|
/** Where those pages are when the app overrides nothing. */
|
|
8
9
|
export const AUTH_PATHS = Object.freeze({
|
|
9
10
|
login: '/login',
|
|
10
11
|
verify: '/auth/verify',
|
|
11
12
|
signedIn: '/auth/sso',
|
|
13
|
+
link: '/auth/link',
|
|
14
|
+
});
|
|
15
|
+
/** What `createSetupGate`, `setupProblem` and `setupPlugin` use when the app overrides nothing. */
|
|
16
|
+
export const SETUP_DEFAULTS = Object.freeze({
|
|
17
|
+
openMinutes: 15,
|
|
18
|
+
minCodeLength: 16,
|
|
19
|
+
claimSeconds: 60,
|
|
12
20
|
});
|
|
13
21
|
/** What `createRateLimiter` uses when the app overrides nothing. */
|
|
14
22
|
export const RATE_LIMIT_DEFAULTS = Object.freeze({
|
package/dist/auth/index.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
export { AUTH_DEFAULTS, AUTH_PATHS, type AuthPaths, type AuthSettings, RATE_LIMIT_DEFAULTS, type RateLimitSettings, } from './defaults.ts';
|
|
1
|
+
export { AUTH_DEFAULTS, AUTH_PATHS, type AuthPaths, type AuthSettings, RATE_LIMIT_DEFAULTS, type RateLimitSettings, SETUP_DEFAULTS, type SetupSettings, } from './defaults.ts';
|
|
2
2
|
export { type MagicLink, type OidcOptions, type SignInOptions, sendsMagicLinks, signInPlugins } from './plugins.ts';
|
|
3
3
|
export { type AuthPresetOptions, type AuthTables, authPreset } from './preset.ts';
|
|
4
4
|
export { createRateLimiter, type RateLimiter, type ThrottleContext, throttle } from './rate-limit.ts';
|
|
5
|
+
export { type AuthInstance, asSetupRefusal, type Claim, claimInstance, createSetupGate, isSetUp, type SetupEnvironment, type SetupGate, type SetupGateOptions, SetupRefusal, type SignedIn, setupNotice, setupProblem, setupRefused, } from './setup.ts';
|
|
6
|
+
export { createSignInLink, type SignInLink, signInLinkUrl, spendSignInLink } from './sign-in-links.ts';
|
package/dist/auth/index.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
export { AUTH_DEFAULTS, AUTH_PATHS, RATE_LIMIT_DEFAULTS, } from './defaults.js';
|
|
1
|
+
export { AUTH_DEFAULTS, AUTH_PATHS, RATE_LIMIT_DEFAULTS, SETUP_DEFAULTS, } from './defaults.js';
|
|
2
2
|
export { sendsMagicLinks, signInPlugins } from './plugins.js';
|
|
3
3
|
export { authPreset } from './preset.js';
|
|
4
4
|
export { createRateLimiter, throttle } from './rate-limit.js';
|
|
5
|
+
export { asSetupRefusal, claimInstance, createSetupGate, isSetUp, SetupRefusal, setupNotice, setupProblem, setupRefused, } from './setup.js';
|
|
6
|
+
export { createSignInLink, signInLinkUrl, spendSignInLink } from './sign-in-links.js';
|
package/dist/auth/plugins.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { oidcPairingPlugins } from '@cubicecho/better-auth-oidc-pairing';
|
|
2
2
|
import { type AuthPaths, type AuthSettings } from './defaults.ts';
|
|
3
|
+
import { type SetupGate } from './setup.ts';
|
|
3
4
|
/** What delivering one sign-in link is given. */
|
|
4
5
|
export interface MagicLink {
|
|
5
6
|
email: string;
|
|
@@ -21,6 +22,8 @@ export interface SignInOptions extends Partial<Pick<AuthSettings, 'magicLinkTtlM
|
|
|
21
22
|
* @defaultValue `AUTH_PATHS`
|
|
22
23
|
*/
|
|
23
24
|
paths?: Partial<AuthPaths>;
|
|
25
|
+
/** How an instance with no account is set up. Without it, the first account is made by whoever signs in first. */
|
|
26
|
+
setup?: SetupGate;
|
|
24
27
|
}
|
|
25
28
|
/**
|
|
26
29
|
* The plugins every server has: bearer sessions, and emailed links when there is a way to deliver them.
|
|
@@ -28,7 +31,7 @@ export interface SignInOptions extends Partial<Pick<AuthSettings, 'magicLinkTtlM
|
|
|
28
31
|
* @param options - The app's links.
|
|
29
32
|
* @returns The plugins.
|
|
30
33
|
*/
|
|
31
|
-
declare function linkPlugins({ appUrl, deliver, paths, magicLinkTtlMinutes, }: SignInOptions): ({
|
|
34
|
+
declare function linkPlugins({ appUrl, deliver, paths, setup, magicLinkTtlMinutes, }: SignInOptions): ({
|
|
32
35
|
id: "bearer";
|
|
33
36
|
version: string;
|
|
34
37
|
hooks: {
|
|
@@ -153,6 +156,22 @@ declare function linkPlugins({ appUrl, deliver, paths, magicLinkTtlMinutes, }: S
|
|
|
153
156
|
max: number;
|
|
154
157
|
}[];
|
|
155
158
|
options: import("better-auth/plugins").MagicLinkOptions;
|
|
159
|
+
} | {
|
|
160
|
+
id: "server-kit-setup";
|
|
161
|
+
init: (context: import("./setup.ts").SetupContext) => {
|
|
162
|
+
options: {
|
|
163
|
+
databaseHooks: {
|
|
164
|
+
user: {
|
|
165
|
+
create: {
|
|
166
|
+
before: (_user: unknown, endpoint?: {
|
|
167
|
+
path?: string;
|
|
168
|
+
} | null) => Promise<void>;
|
|
169
|
+
after: () => Promise<void>;
|
|
170
|
+
};
|
|
171
|
+
};
|
|
172
|
+
};
|
|
173
|
+
};
|
|
174
|
+
};
|
|
156
175
|
})[];
|
|
157
176
|
/**
|
|
158
177
|
* Those, with OIDC sign-in and pairing.
|
|
@@ -1387,6 +1406,22 @@ declare function oidcPlugins(options: SignInOptions, oidc: OidcOptions): ({
|
|
|
1387
1406
|
max: number;
|
|
1388
1407
|
}[];
|
|
1389
1408
|
options: import("better-auth/plugins").MagicLinkOptions;
|
|
1409
|
+
} | {
|
|
1410
|
+
id: "server-kit-setup";
|
|
1411
|
+
init: (context: import("./setup.ts").SetupContext) => {
|
|
1412
|
+
options: {
|
|
1413
|
+
databaseHooks: {
|
|
1414
|
+
user: {
|
|
1415
|
+
create: {
|
|
1416
|
+
before: (_user: unknown, endpoint?: {
|
|
1417
|
+
path?: string;
|
|
1418
|
+
} | null) => Promise<void>;
|
|
1419
|
+
after: () => Promise<void>;
|
|
1420
|
+
};
|
|
1421
|
+
};
|
|
1422
|
+
};
|
|
1423
|
+
};
|
|
1424
|
+
};
|
|
1390
1425
|
})[];
|
|
1391
1426
|
/**
|
|
1392
1427
|
* How people sign in: bearer sessions, emailed links, and OIDC with pairing. Never a password.
|
package/dist/auth/plugins.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { oidcPairingPlugins } from '@cubicecho/better-auth-oidc-pairing';
|
|
2
2
|
import { bearer, magicLink } from 'better-auth/plugins';
|
|
3
3
|
import { AUTH_DEFAULTS, AUTH_PATHS } from './defaults.js';
|
|
4
|
+
import { refuseLinkBeforeSetup, setupPlugin } from './setup.js';
|
|
4
5
|
const SECONDS_PER_MINUTE = 60;
|
|
5
6
|
/** better-auth's id for the magic-link plugin. */
|
|
6
7
|
const MAGIC_LINK_PLUGIN_ID = 'magic-link';
|
|
@@ -10,7 +11,7 @@ const MAGIC_LINK_PLUGIN_ID = 'magic-link';
|
|
|
10
11
|
* @param options - The app's links.
|
|
11
12
|
* @returns The plugins.
|
|
12
13
|
*/
|
|
13
|
-
function linkPlugins({ appUrl, deliver, paths, magicLinkTtlMinutes = AUTH_DEFAULTS.magicLinkTtlMinutes, }) {
|
|
14
|
+
function linkPlugins({ appUrl, deliver, paths, setup, magicLinkTtlMinutes = AUTH_DEFAULTS.magicLinkTtlMinutes, }) {
|
|
14
15
|
const { verify } = { ...AUTH_PATHS, ...paths };
|
|
15
16
|
const links = deliver === undefined
|
|
16
17
|
? []
|
|
@@ -19,10 +20,16 @@ function linkPlugins({ appUrl, deliver, paths, magicLinkTtlMinutes = AUTH_DEFAUL
|
|
|
19
20
|
expiresIn: magicLinkTtlMinutes * SECONDS_PER_MINUTE,
|
|
20
21
|
storeToken: 'hashed',
|
|
21
22
|
// Links go to the app, which spends the token over GraphQL. The REST verify route is not mounted.
|
|
22
|
-
sendMagicLink: ({ email, token }) =>
|
|
23
|
+
sendMagicLink: async ({ email, token }, request) => {
|
|
24
|
+
if (setup !== undefined && request !== undefined) {
|
|
25
|
+
await refuseLinkBeforeSetup(request.context);
|
|
26
|
+
}
|
|
27
|
+
await deliver({ email, token, url: `${appUrl}${verify}?token=${encodeURIComponent(token)}` });
|
|
28
|
+
},
|
|
23
29
|
}),
|
|
24
30
|
];
|
|
25
|
-
|
|
31
|
+
const setups = setup === undefined ? [] : [setupPlugin(setup)];
|
|
32
|
+
return [bearer(), ...links, ...setups];
|
|
26
33
|
}
|
|
27
34
|
/**
|
|
28
35
|
* Those, with OIDC sign-in and pairing.
|
package/dist/auth/preset.d.ts
CHANGED
|
@@ -44,6 +44,12 @@ export declare function authPreset({ db, tables, secret, serverUrl, appUrl, path
|
|
|
44
44
|
generateId: 'uuid';
|
|
45
45
|
};
|
|
46
46
|
};
|
|
47
|
+
user: {
|
|
48
|
+
changeEmail: {
|
|
49
|
+
enabled: boolean;
|
|
50
|
+
updateEmailWithoutVerification: boolean;
|
|
51
|
+
};
|
|
52
|
+
};
|
|
47
53
|
session: {
|
|
48
54
|
expiresIn: number;
|
|
49
55
|
};
|
package/dist/auth/preset.js
CHANGED
|
@@ -15,6 +15,8 @@ export function authPreset({ db, tables, secret, serverUrl, appUrl, paths, sessi
|
|
|
15
15
|
trustedOrigins: [new URL(appUrl).origin],
|
|
16
16
|
// On Postgres this leaves the id out of the insert, so the column's uuidv7() fills it.
|
|
17
17
|
advanced: { database: { generateId: 'uuid' } },
|
|
18
|
+
// An address nothing has verified may be changed, so a typo at setup is not the account's for good.
|
|
19
|
+
user: { changeEmail: { enabled: true, updateEmailWithoutVerification: true } },
|
|
18
20
|
session: { expiresIn: sessionTtlDays * SECONDS_PER_DAY },
|
|
19
21
|
onAPIError: { errorURL: `${appUrl}${{ ...AUTH_PATHS, ...paths }.login}` },
|
|
20
22
|
};
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import type { AuthContext } from 'better-auth';
|
|
2
|
+
import { GraphQLError } from 'graphql';
|
|
3
|
+
import { type SetupSettings } from './defaults.ts';
|
|
4
|
+
/** Why setting an instance up was refused: `extensions.reason`, or the code of better-auth's error. */
|
|
5
|
+
export declare const SetupRefusal: {
|
|
6
|
+
/** The code is missing or wrong. */
|
|
7
|
+
readonly WrongCode: 'WRONG_SETUP_CODE';
|
|
8
|
+
/** Setup was open, and its time is up until the next start. */
|
|
9
|
+
readonly WindowClosed: 'SETUP_WINDOW_CLOSED';
|
|
10
|
+
/** Someone else is setting the instance up at this moment. */
|
|
11
|
+
readonly InProgress: 'SETUP_IN_PROGRESS';
|
|
12
|
+
/** The instance has an account already. */
|
|
13
|
+
readonly AlreadyDone: 'ALREADY_SET_UP';
|
|
14
|
+
/** The instance has no account yet, so it has to be set up before anyone signs in this way. */
|
|
15
|
+
readonly Required: 'SETUP_REQUIRED';
|
|
16
|
+
};
|
|
17
|
+
/** One of the reasons in `SetupRefusal`. */
|
|
18
|
+
export type SetupRefusal = (typeof SetupRefusal)[keyof typeof SetupRefusal];
|
|
19
|
+
/** Who may set up an instance that has no account. */
|
|
20
|
+
export interface SetupGateOptions {
|
|
21
|
+
/** `SETUP_CODE`. Empty counts as unset. It wins over `open`, so setting one is always stricter. */
|
|
22
|
+
code?: string | undefined;
|
|
23
|
+
/** `OPEN_SETUP`: anyone who can reach the instance may set it up, for a while after it starts. */
|
|
24
|
+
open: boolean;
|
|
25
|
+
/** When the server started. */
|
|
26
|
+
startedAt: Date;
|
|
27
|
+
}
|
|
28
|
+
/** The door an instance with no account is set up through. */
|
|
29
|
+
export interface SetupGate {
|
|
30
|
+
/** Whether a code is needed. */
|
|
31
|
+
readonly needsCode: boolean;
|
|
32
|
+
/** The code the server made up, for the boot log, or null when there is none or the operator chose it. */
|
|
33
|
+
readonly generatedCode: string | null;
|
|
34
|
+
/** When an open setup closes, or null when a code is needed. */
|
|
35
|
+
readonly endsAt: Date | null;
|
|
36
|
+
/**
|
|
37
|
+
* Why a caller may not set the instance up, or null when they may. It does not ask whether it is already set up.
|
|
38
|
+
*
|
|
39
|
+
* @param code - The code they gave, or null.
|
|
40
|
+
*/
|
|
41
|
+
refusal(code: string | null): SetupRefusal | null;
|
|
42
|
+
/**
|
|
43
|
+
* Runs something as a caller with this code. `isAdmitted` answers for them inside it, however deep.
|
|
44
|
+
*
|
|
45
|
+
* @param code - The code they gave, or null.
|
|
46
|
+
* @param run - What to run.
|
|
47
|
+
*/
|
|
48
|
+
as<Result>(code: string | null, run: () => Result): Result;
|
|
49
|
+
/** Whether the caller `as` is running for may set the instance up. An app's `canPair` asks it. */
|
|
50
|
+
isAdmitted(): boolean;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Builds the door an instance with no account is set up through. Build one per process, at boot.
|
|
54
|
+
*
|
|
55
|
+
* @param options - The operator's choice.
|
|
56
|
+
* @param [overrides] - Settings that replace the defaults.
|
|
57
|
+
* @param [now] - The clock, in milliseconds since the epoch. Tests pass their own.
|
|
58
|
+
* @returns The gate.
|
|
59
|
+
*/
|
|
60
|
+
export declare function createSetupGate({ code, open, startedAt }: SetupGateOptions, overrides?: Partial<SetupSettings>, now?: () => number): SetupGate;
|
|
61
|
+
/** What `setupProblem` looks at. */
|
|
62
|
+
export interface SetupEnvironment extends Pick<SetupGateOptions, 'code' | 'open'> {
|
|
63
|
+
/** Where users reach the app, or null when it is not configured. */
|
|
64
|
+
appUrl: string | null;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* What is wrong with the setup variables, for an app's preflight to refuse to boot on.
|
|
68
|
+
*
|
|
69
|
+
* @param environment - `SETUP_CODE`, `OPEN_SETUP` and `APP_URL`.
|
|
70
|
+
* @param [overrides] - Settings that replace the defaults.
|
|
71
|
+
* @returns A sentence saying how to fix it, without the code, or undefined when nothing is.
|
|
72
|
+
*/
|
|
73
|
+
export declare function setupProblem({ code, open, appUrl }: SetupEnvironment, overrides?: Partial<SetupSettings>): string | undefined;
|
|
74
|
+
/**
|
|
75
|
+
* What to log at boot while an instance has no account.
|
|
76
|
+
*
|
|
77
|
+
* @param gate - The instance's gate.
|
|
78
|
+
* @returns One line, which holds the code when the server made it up.
|
|
79
|
+
*/
|
|
80
|
+
export declare function setupNotice({ generatedCode, endsAt }: Pick<SetupGate, 'generatedCode' | 'endsAt'>): string;
|
|
81
|
+
/** What counts accounts. */
|
|
82
|
+
export interface AccountCounter {
|
|
83
|
+
adapter: {
|
|
84
|
+
count(query: {
|
|
85
|
+
model: string;
|
|
86
|
+
}): Promise<number>;
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
/** The calls setup and sign-in links make on better-auth's own adapter. */
|
|
90
|
+
type InternalAdapter = Pick<AuthContext['internalAdapter'], 'createUser' | 'createSession' | 'findUserById' | 'createVerificationValue' | 'consumeVerificationValue'>;
|
|
91
|
+
/** What holding the first account to one caller needs of better-auth's context. */
|
|
92
|
+
export interface SetupContext extends AccountCounter {
|
|
93
|
+
adapter: AccountCounter['adapter'] & Pick<AuthContext['adapter'], 'deleteMany'>;
|
|
94
|
+
internalAdapter: Pick<AuthContext['internalAdapter'], 'reserveVerificationValue' | 'deleteVerificationByIdentifier'>;
|
|
95
|
+
}
|
|
96
|
+
/** The part of an auth instance that setup and sign-in links use, whatever its plugins. */
|
|
97
|
+
export interface AuthInstance {
|
|
98
|
+
$context: Promise<AccountCounter & {
|
|
99
|
+
internalAdapter: InternalAdapter;
|
|
100
|
+
}>;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Whether an instance has been set up.
|
|
104
|
+
*
|
|
105
|
+
* @param auth - The auth instance.
|
|
106
|
+
* @returns true once it has an account.
|
|
107
|
+
*/
|
|
108
|
+
export declare function isSetUp(auth: AuthInstance): Promise<boolean>;
|
|
109
|
+
/**
|
|
110
|
+
* Refuses to email a link from an instance with no account, so that nobody becomes its owner that way.
|
|
111
|
+
*
|
|
112
|
+
* @param context - better-auth's own context.
|
|
113
|
+
* @throws A `SETUP_REQUIRED` error.
|
|
114
|
+
*/
|
|
115
|
+
export declare function refuseLinkBeforeSetup(context: AccountCounter): Promise<void>;
|
|
116
|
+
/**
|
|
117
|
+
* Holds the making of the first account to one caller, who was let in.
|
|
118
|
+
*
|
|
119
|
+
* @param gate - The instance's gate.
|
|
120
|
+
* @param [overrides] - Settings that replace the defaults.
|
|
121
|
+
* @returns The plugin.
|
|
122
|
+
*
|
|
123
|
+
* @remarks
|
|
124
|
+
* The first account comes from `claimInstance` or from an OIDC provider's callback, and from nothing else. The claim
|
|
125
|
+
* is held as a row with a key of its own, so that two processes cannot both make one.
|
|
126
|
+
*/
|
|
127
|
+
export declare function setupPlugin(gate: SetupGate, overrides?: Partial<SetupSettings>): {
|
|
128
|
+
id: "server-kit-setup";
|
|
129
|
+
init: (context: SetupContext) => {
|
|
130
|
+
options: {
|
|
131
|
+
databaseHooks: {
|
|
132
|
+
user: {
|
|
133
|
+
create: {
|
|
134
|
+
before: (_user: unknown, endpoint?: {
|
|
135
|
+
path?: string;
|
|
136
|
+
} | null) => Promise<void>;
|
|
137
|
+
after: () => Promise<void>;
|
|
138
|
+
};
|
|
139
|
+
};
|
|
140
|
+
};
|
|
141
|
+
};
|
|
142
|
+
};
|
|
143
|
+
};
|
|
144
|
+
/** What a claim is made with. */
|
|
145
|
+
export interface Claim {
|
|
146
|
+
/** The caller's code, or null. */
|
|
147
|
+
code: string | null;
|
|
148
|
+
/** The normalized address. */
|
|
149
|
+
email: string;
|
|
150
|
+
name: string;
|
|
151
|
+
}
|
|
152
|
+
/** A signed-in session. */
|
|
153
|
+
export interface SignedIn {
|
|
154
|
+
/** The bearer token. */
|
|
155
|
+
token: string;
|
|
156
|
+
userId: string;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* The GraphQL error for a refusal.
|
|
160
|
+
*
|
|
161
|
+
* @param reason - Why.
|
|
162
|
+
* @returns The error, with the reason in its extensions.
|
|
163
|
+
*/
|
|
164
|
+
export declare function setupRefused(reason: SetupRefusal): GraphQLError;
|
|
165
|
+
/**
|
|
166
|
+
* Makes an instance's first account and signs it in. Throttle the caller first.
|
|
167
|
+
*
|
|
168
|
+
* @param auth - The auth instance, built with `setupPlugin`.
|
|
169
|
+
* @param gate - The same gate.
|
|
170
|
+
* @param claim - Who is claiming it.
|
|
171
|
+
* @returns The session.
|
|
172
|
+
* @throws FORBIDDEN or CONFLICT, with a `SetupRefusal` as `extensions.reason`.
|
|
173
|
+
*
|
|
174
|
+
* @remarks
|
|
175
|
+
* The address is unverified: nothing has shown it is the caller's. They can change it until a link or a provider does.
|
|
176
|
+
*/
|
|
177
|
+
export declare function claimInstance(auth: AuthInstance, gate: SetupGate, { code, email, name }: Claim): Promise<SignedIn>;
|
|
178
|
+
/**
|
|
179
|
+
* Turns better-auth's error for a refusal into the GraphQL one. Any other error is answered as it is.
|
|
180
|
+
*
|
|
181
|
+
* @param error - What was thrown.
|
|
182
|
+
* @returns What to throw.
|
|
183
|
+
*/
|
|
184
|
+
export declare function asSetupRefusal(error: unknown): unknown;
|
|
185
|
+
export {};
|
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
+
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
3
|
+
import { APIError, isAPIError } from 'better-auth/api';
|
|
4
|
+
import { GraphQLError } from 'graphql';
|
|
5
|
+
import { errorCode } from '../db/errors.js';
|
|
6
|
+
import { isPrivateHost } from '../db/ssl.js';
|
|
7
|
+
import { ErrorCode } from '../graphql/errors.js';
|
|
8
|
+
import { SETUP_DEFAULTS } from './defaults.js';
|
|
9
|
+
const MS_PER_SECOND = 1000;
|
|
10
|
+
/** Postgres's answer when a key is taken. */
|
|
11
|
+
const UNIQUE_VIOLATION = '23505';
|
|
12
|
+
const MS_PER_MINUTE = 60_000;
|
|
13
|
+
/** Bytes in a code the server makes up, which are read out as twice as many letters and digits. */
|
|
14
|
+
const GENERATED_CODE_BYTES = 10;
|
|
15
|
+
/** better-auth's model names. */
|
|
16
|
+
const USER_MODEL = 'user';
|
|
17
|
+
const VERIFICATION_MODEL = 'verification';
|
|
18
|
+
/** Where the one setup in progress is held. */
|
|
19
|
+
const CLAIM_IDENTIFIER = 'server-kit:instance-claim';
|
|
20
|
+
/** Where an OIDC provider sends the browser back. Who it lets in is decided at the provider. */
|
|
21
|
+
const SSO_CALLBACK_PREFIX = '/sso/callback/';
|
|
22
|
+
/** Why setting an instance up was refused: `extensions.reason`, or the code of better-auth's error. */
|
|
23
|
+
export const SetupRefusal = {
|
|
24
|
+
/** The code is missing or wrong. */
|
|
25
|
+
WrongCode: 'WRONG_SETUP_CODE',
|
|
26
|
+
/** Setup was open, and its time is up until the next start. */
|
|
27
|
+
WindowClosed: 'SETUP_WINDOW_CLOSED',
|
|
28
|
+
/** Someone else is setting the instance up at this moment. */
|
|
29
|
+
InProgress: 'SETUP_IN_PROGRESS',
|
|
30
|
+
/** The instance has an account already. */
|
|
31
|
+
AlreadyDone: 'ALREADY_SET_UP',
|
|
32
|
+
/** The instance has no account yet, so it has to be set up before anyone signs in this way. */
|
|
33
|
+
Required: 'SETUP_REQUIRED',
|
|
34
|
+
};
|
|
35
|
+
const MESSAGES = Object.freeze({
|
|
36
|
+
[SetupRefusal.WrongCode]: 'That is not the setup code.',
|
|
37
|
+
[SetupRefusal.WindowClosed]: 'The time to set this instance up has passed. Restart it to open setup again.',
|
|
38
|
+
[SetupRefusal.InProgress]: 'This instance is being set up by someone else. Try again in a minute.',
|
|
39
|
+
[SetupRefusal.AlreadyDone]: 'This instance is already set up. Sign in instead.',
|
|
40
|
+
[SetupRefusal.Required]: 'This instance has not been set up yet.',
|
|
41
|
+
});
|
|
42
|
+
/**
|
|
43
|
+
* Compares two codes in a time that does not depend on where they differ.
|
|
44
|
+
*
|
|
45
|
+
* @param given - The code a caller gave.
|
|
46
|
+
* @param expected - The instance's.
|
|
47
|
+
* @returns true when they are equal.
|
|
48
|
+
*/
|
|
49
|
+
function isSameCode(given, expected) {
|
|
50
|
+
const digest = (value) => createHash('sha256').update(value).digest();
|
|
51
|
+
return timingSafeEqual(digest(given.trim()), digest(expected));
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Builds the door an instance with no account is set up through. Build one per process, at boot.
|
|
55
|
+
*
|
|
56
|
+
* @param options - The operator's choice.
|
|
57
|
+
* @param [overrides] - Settings that replace the defaults.
|
|
58
|
+
* @param [now] - The clock, in milliseconds since the epoch. Tests pass their own.
|
|
59
|
+
* @returns The gate.
|
|
60
|
+
*/
|
|
61
|
+
export function createSetupGate({ code, open, startedAt }, overrides = {}, now = Date.now) {
|
|
62
|
+
const { openMinutes } = { ...SETUP_DEFAULTS, ...overrides };
|
|
63
|
+
const chosen = code?.trim() ?? '';
|
|
64
|
+
const hasChosen = chosen !== '';
|
|
65
|
+
const isOpen = open && hasChosen === false;
|
|
66
|
+
const generatedCode = hasChosen || isOpen ? null : randomBytes(GENERATED_CODE_BYTES).toString('hex');
|
|
67
|
+
const expected = generatedCode ?? chosen;
|
|
68
|
+
const endsAt = isOpen ? new Date(startedAt.getTime() + openMinutes * MS_PER_MINUTE) : null;
|
|
69
|
+
const caller = new AsyncLocalStorage();
|
|
70
|
+
const refusal = (given) => {
|
|
71
|
+
if (endsAt !== null) {
|
|
72
|
+
return now() < endsAt.getTime() ? null : SetupRefusal.WindowClosed;
|
|
73
|
+
}
|
|
74
|
+
const isRight = given !== null && isSameCode(given, expected);
|
|
75
|
+
return isRight ? null : SetupRefusal.WrongCode;
|
|
76
|
+
};
|
|
77
|
+
return {
|
|
78
|
+
needsCode: isOpen === false,
|
|
79
|
+
generatedCode,
|
|
80
|
+
endsAt,
|
|
81
|
+
refusal,
|
|
82
|
+
as: (given, run) => caller.run({ code: given }, run),
|
|
83
|
+
isAdmitted: () => refusal(caller.getStore()?.code ?? null) === null,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* What is wrong with the setup variables, for an app's preflight to refuse to boot on.
|
|
88
|
+
*
|
|
89
|
+
* @param environment - `SETUP_CODE`, `OPEN_SETUP` and `APP_URL`.
|
|
90
|
+
* @param [overrides] - Settings that replace the defaults.
|
|
91
|
+
* @returns A sentence saying how to fix it, without the code, or undefined when nothing is.
|
|
92
|
+
*/
|
|
93
|
+
export function setupProblem({ code, open, appUrl }, overrides = {}) {
|
|
94
|
+
const { minCodeLength } = { ...SETUP_DEFAULTS, ...overrides };
|
|
95
|
+
const chosen = code?.trim() ?? '';
|
|
96
|
+
if (chosen !== '') {
|
|
97
|
+
return chosen.length < minCodeLength
|
|
98
|
+
? `SETUP_CODE is shorter than ${minCodeLength} characters. Generate one with \`openssl rand -hex 16\`.`
|
|
99
|
+
: undefined;
|
|
100
|
+
}
|
|
101
|
+
if (open === false || appUrl === null || URL.canParse(appUrl) === false) {
|
|
102
|
+
return undefined;
|
|
103
|
+
}
|
|
104
|
+
const host = new URL(appUrl).hostname.replace(/^\[|\]$/g, '').toLowerCase();
|
|
105
|
+
return isPrivateHost(host)
|
|
106
|
+
? undefined
|
|
107
|
+
: `OPEN_SETUP lets anyone claim a new instance, and APP_URL (${host}) is public. Set SETUP_CODE instead.`;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* What to log at boot while an instance has no account.
|
|
111
|
+
*
|
|
112
|
+
* @param gate - The instance's gate.
|
|
113
|
+
* @returns One line, which holds the code when the server made it up.
|
|
114
|
+
*/
|
|
115
|
+
export function setupNotice({ generatedCode, endsAt }) {
|
|
116
|
+
if (endsAt !== null) {
|
|
117
|
+
return `OPEN_SETUP is on: anyone who can reach this instance can claim it until ${endsAt.toISOString()}.`;
|
|
118
|
+
}
|
|
119
|
+
return generatedCode === null
|
|
120
|
+
? 'This instance has no account yet. Open the app and set it up with SETUP_CODE.'
|
|
121
|
+
: `This instance has no account yet. Open the app and set it up with this code: ${generatedCode}`;
|
|
122
|
+
}
|
|
123
|
+
/** Set while `claimInstance` makes its account, so the hook can tell it from an ordinary sign-up. */
|
|
124
|
+
const claiming = new AsyncLocalStorage();
|
|
125
|
+
/**
|
|
126
|
+
* Whether an instance has an account.
|
|
127
|
+
*
|
|
128
|
+
* @param context - better-auth's own context.
|
|
129
|
+
* @returns true once the first one exists.
|
|
130
|
+
*/
|
|
131
|
+
async function hasAccount({ adapter }) {
|
|
132
|
+
return (await adapter.count({ model: USER_MODEL })) > 0;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Whether an instance has been set up.
|
|
136
|
+
*
|
|
137
|
+
* @param auth - The auth instance.
|
|
138
|
+
* @returns true once it has an account.
|
|
139
|
+
*/
|
|
140
|
+
export async function isSetUp(auth) {
|
|
141
|
+
return hasAccount(await auth.$context);
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Builds better-auth's error for a refusal.
|
|
145
|
+
*
|
|
146
|
+
* @param reason - Why.
|
|
147
|
+
* @returns The error.
|
|
148
|
+
*/
|
|
149
|
+
function refused(reason) {
|
|
150
|
+
return new APIError('FORBIDDEN', { code: reason, message: MESSAGES[reason] });
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Refuses to email a link from an instance with no account, so that nobody becomes its owner that way.
|
|
154
|
+
*
|
|
155
|
+
* @param context - better-auth's own context.
|
|
156
|
+
* @throws A `SETUP_REQUIRED` error.
|
|
157
|
+
*/
|
|
158
|
+
export async function refuseLinkBeforeSetup(context) {
|
|
159
|
+
if ((await hasAccount(context)) === false) {
|
|
160
|
+
throw refused(SetupRefusal.Required);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Holds the making of the first account to one caller, who was let in.
|
|
165
|
+
*
|
|
166
|
+
* @param gate - The instance's gate.
|
|
167
|
+
* @param [overrides] - Settings that replace the defaults.
|
|
168
|
+
* @returns The plugin.
|
|
169
|
+
*
|
|
170
|
+
* @remarks
|
|
171
|
+
* The first account comes from `claimInstance` or from an OIDC provider's callback, and from nothing else. The claim
|
|
172
|
+
* is held as a row with a key of its own, so that two processes cannot both make one.
|
|
173
|
+
*/
|
|
174
|
+
export function setupPlugin(gate, overrides = {}) {
|
|
175
|
+
const { claimSeconds } = { ...SETUP_DEFAULTS, ...overrides };
|
|
176
|
+
return {
|
|
177
|
+
id: 'server-kit-setup',
|
|
178
|
+
init: (context) => {
|
|
179
|
+
const { adapter, internalAdapter } = context;
|
|
180
|
+
const release = () => internalAdapter.deleteVerificationByIdentifier(CLAIM_IDENTIFIER);
|
|
181
|
+
/** Takes the claim, and answers false when another caller has it. */
|
|
182
|
+
const hold = async (expiresAt) => {
|
|
183
|
+
try {
|
|
184
|
+
const claim = { identifier: CLAIM_IDENTIFIER, value: CLAIM_IDENTIFIER, expiresAt };
|
|
185
|
+
return await internalAdapter.reserveVerificationValue(claim);
|
|
186
|
+
}
|
|
187
|
+
catch (error) {
|
|
188
|
+
// It was let go just after it kept this one out, and better-auth found no row to blame.
|
|
189
|
+
if (errorCode(error) === UNIQUE_VIOLATION) {
|
|
190
|
+
return false;
|
|
191
|
+
}
|
|
192
|
+
throw error;
|
|
193
|
+
}
|
|
194
|
+
};
|
|
195
|
+
const before = async (_user, endpoint) => {
|
|
196
|
+
if (await hasAccount(context)) {
|
|
197
|
+
// Someone else's claim finished since this one looked.
|
|
198
|
+
if (claiming.getStore() === true) {
|
|
199
|
+
throw refused(SetupRefusal.AlreadyDone);
|
|
200
|
+
}
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
const isFromProvider = endpoint?.path?.startsWith(SSO_CALLBACK_PREFIX) === true;
|
|
204
|
+
// No endpoint: the server's own call, as `claimInstance` makes it.
|
|
205
|
+
const isServerCall = (endpoint ?? null) === null;
|
|
206
|
+
const isFromSetup = isServerCall && gate.isAdmitted();
|
|
207
|
+
const isAllowed = isFromProvider || isFromSetup;
|
|
208
|
+
if (isAllowed === false) {
|
|
209
|
+
throw refused(SetupRefusal.Required);
|
|
210
|
+
}
|
|
211
|
+
const at = new Date();
|
|
212
|
+
// A process that died holding the claim.
|
|
213
|
+
await adapter.deleteMany({
|
|
214
|
+
model: VERIFICATION_MODEL,
|
|
215
|
+
where: [
|
|
216
|
+
{ field: 'identifier', value: CLAIM_IDENTIFIER },
|
|
217
|
+
{ field: 'expiresAt', operator: 'lt', value: at },
|
|
218
|
+
],
|
|
219
|
+
});
|
|
220
|
+
const isHeld = await hold(new Date(at.getTime() + claimSeconds * MS_PER_SECOND));
|
|
221
|
+
if (isHeld === false) {
|
|
222
|
+
throw refused(SetupRefusal.InProgress);
|
|
223
|
+
}
|
|
224
|
+
// Someone may have finished between the first look and the claim.
|
|
225
|
+
if (await hasAccount(context)) {
|
|
226
|
+
await release();
|
|
227
|
+
throw refused(SetupRefusal.AlreadyDone);
|
|
228
|
+
}
|
|
229
|
+
};
|
|
230
|
+
return { options: { databaseHooks: { user: { create: { before, after: release } } } } };
|
|
231
|
+
},
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
/** The codes a refusal is answered with. */
|
|
235
|
+
const REFUSAL_CODES = Object.freeze({
|
|
236
|
+
[SetupRefusal.WrongCode]: ErrorCode.Forbidden,
|
|
237
|
+
[SetupRefusal.WindowClosed]: ErrorCode.Forbidden,
|
|
238
|
+
[SetupRefusal.InProgress]: ErrorCode.Conflict,
|
|
239
|
+
[SetupRefusal.AlreadyDone]: ErrorCode.Conflict,
|
|
240
|
+
[SetupRefusal.Required]: ErrorCode.Forbidden,
|
|
241
|
+
});
|
|
242
|
+
/**
|
|
243
|
+
* The GraphQL error for a refusal.
|
|
244
|
+
*
|
|
245
|
+
* @param reason - Why.
|
|
246
|
+
* @returns The error, with the reason in its extensions.
|
|
247
|
+
*/
|
|
248
|
+
export function setupRefused(reason) {
|
|
249
|
+
return new GraphQLError(MESSAGES[reason], { extensions: { code: REFUSAL_CODES[reason], reason } });
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Makes an instance's first account and signs it in. Throttle the caller first.
|
|
253
|
+
*
|
|
254
|
+
* @param auth - The auth instance, built with `setupPlugin`.
|
|
255
|
+
* @param gate - The same gate.
|
|
256
|
+
* @param claim - Who is claiming it.
|
|
257
|
+
* @returns The session.
|
|
258
|
+
* @throws FORBIDDEN or CONFLICT, with a `SetupRefusal` as `extensions.reason`.
|
|
259
|
+
*
|
|
260
|
+
* @remarks
|
|
261
|
+
* The address is unverified: nothing has shown it is the caller's. They can change it until a link or a provider does.
|
|
262
|
+
*/
|
|
263
|
+
export async function claimInstance(auth, gate, { code, email, name }) {
|
|
264
|
+
const { internalAdapter } = await auth.$context;
|
|
265
|
+
if (await isSetUp(auth)) {
|
|
266
|
+
throw setupRefused(SetupRefusal.AlreadyDone);
|
|
267
|
+
}
|
|
268
|
+
const refusal = gate.refusal(code);
|
|
269
|
+
if (refusal !== null) {
|
|
270
|
+
throw setupRefused(refusal);
|
|
271
|
+
}
|
|
272
|
+
try {
|
|
273
|
+
const user = await gate.as(code, () => claiming.run(true, () => internalAdapter.createUser({ email, name, emailVerified: false }, { method: 'setup' })));
|
|
274
|
+
const session = await internalAdapter.createSession(user.id);
|
|
275
|
+
return { token: session.token, userId: user.id };
|
|
276
|
+
}
|
|
277
|
+
catch (error) {
|
|
278
|
+
throw asSetupRefusal(error);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Turns better-auth's error for a refusal into the GraphQL one. Any other error is answered as it is.
|
|
283
|
+
*
|
|
284
|
+
* @param error - What was thrown.
|
|
285
|
+
* @returns What to throw.
|
|
286
|
+
*/
|
|
287
|
+
export function asSetupRefusal(error) {
|
|
288
|
+
const reason = isAPIError(error) ? error.body?.code : undefined;
|
|
289
|
+
const refusal = Object.values(SetupRefusal).find((known) => known === reason);
|
|
290
|
+
return refusal === undefined ? error : setupRefused(refusal);
|
|
291
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { type AuthPaths, type AuthSettings } from './defaults.ts';
|
|
2
|
+
import type { AuthInstance, SignedIn } from './setup.ts';
|
|
3
|
+
/** A link that signs one person in, once. */
|
|
4
|
+
export interface SignInLink {
|
|
5
|
+
/** The secret. Show it once, and never log it. */
|
|
6
|
+
token: string;
|
|
7
|
+
expiresAt: Date;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Makes a link that signs its holder in as a user, once. For another device of their own, made from a session and
|
|
11
|
+
* never from an API key, and for a recovery command run beside the server.
|
|
12
|
+
*
|
|
13
|
+
* @param auth - The auth instance.
|
|
14
|
+
* @param userId - An existing user. The caller has checked that they may sign in as them.
|
|
15
|
+
* @param [overrides] - How long it works.
|
|
16
|
+
* @returns The link.
|
|
17
|
+
*/
|
|
18
|
+
export declare function createSignInLink(auth: AuthInstance, userId: string, overrides?: Partial<Pick<AuthSettings, 'signInLinkTtlMinutes'>>): Promise<SignInLink>;
|
|
19
|
+
/**
|
|
20
|
+
* Signs in with a link, and uses it up. Throttle the caller first.
|
|
21
|
+
*
|
|
22
|
+
* @param auth - The auth instance.
|
|
23
|
+
* @param token - The link's token.
|
|
24
|
+
* @returns The session, or null for a link that is unknown, used or expired, or whose user is gone.
|
|
25
|
+
*/
|
|
26
|
+
export declare function spendSignInLink(auth: AuthInstance, token: string): Promise<SignedIn | null>;
|
|
27
|
+
/**
|
|
28
|
+
* The address a link is opened at.
|
|
29
|
+
*
|
|
30
|
+
* @param appUrl - Where users reach the app.
|
|
31
|
+
* @param token - The link's token.
|
|
32
|
+
* @param [paths] - Pages that are somewhere else in this app.
|
|
33
|
+
* @returns The URL. The token is in its fragment, which no server or proxy on the way is sent.
|
|
34
|
+
*/
|
|
35
|
+
export declare function signInLinkUrl(appUrl: string, token: string, paths?: Partial<AuthPaths>): string;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
2
|
+
import { AUTH_DEFAULTS, AUTH_PATHS } from './defaults.js';
|
|
3
|
+
const MS_PER_MINUTE = 60_000;
|
|
4
|
+
/** Bytes of randomness in a link's token. */
|
|
5
|
+
const TOKEN_BYTES = 32;
|
|
6
|
+
const IDENTIFIER_PREFIX = 'server-kit:sign-in-link:';
|
|
7
|
+
/**
|
|
8
|
+
* Where a link is kept: under its token's hash, so that a copy of the database holds no link that works.
|
|
9
|
+
*
|
|
10
|
+
* @param token - The link's token.
|
|
11
|
+
* @returns The identifier.
|
|
12
|
+
*/
|
|
13
|
+
function identifierOf(token) {
|
|
14
|
+
return IDENTIFIER_PREFIX + createHash('sha256').update(token).digest('hex');
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Makes a link that signs its holder in as a user, once. For another device of their own, made from a session and
|
|
18
|
+
* never from an API key, and for a recovery command run beside the server.
|
|
19
|
+
*
|
|
20
|
+
* @param auth - The auth instance.
|
|
21
|
+
* @param userId - An existing user. The caller has checked that they may sign in as them.
|
|
22
|
+
* @param [overrides] - How long it works.
|
|
23
|
+
* @returns The link.
|
|
24
|
+
*/
|
|
25
|
+
export async function createSignInLink(auth, userId, overrides = {}) {
|
|
26
|
+
const { signInLinkTtlMinutes } = { ...AUTH_DEFAULTS, ...overrides };
|
|
27
|
+
const { internalAdapter } = await auth.$context;
|
|
28
|
+
const token = randomBytes(TOKEN_BYTES).toString('base64url');
|
|
29
|
+
const expiresAt = new Date(Date.now() + signInLinkTtlMinutes * MS_PER_MINUTE);
|
|
30
|
+
await internalAdapter.createVerificationValue({ identifier: identifierOf(token), value: userId, expiresAt });
|
|
31
|
+
return { token, expiresAt };
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Signs in with a link, and uses it up. Throttle the caller first.
|
|
35
|
+
*
|
|
36
|
+
* @param auth - The auth instance.
|
|
37
|
+
* @param token - The link's token.
|
|
38
|
+
* @returns The session, or null for a link that is unknown, used or expired, or whose user is gone.
|
|
39
|
+
*/
|
|
40
|
+
export async function spendSignInLink(auth, token) {
|
|
41
|
+
const { internalAdapter } = await auth.$context;
|
|
42
|
+
const link = await internalAdapter.consumeVerificationValue(identifierOf(token));
|
|
43
|
+
const user = link === null ? null : await internalAdapter.findUserById(link.value);
|
|
44
|
+
if (user === null) {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
const session = await internalAdapter.createSession(user.id);
|
|
48
|
+
return { token: session.token, userId: user.id };
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* The address a link is opened at.
|
|
52
|
+
*
|
|
53
|
+
* @param appUrl - Where users reach the app.
|
|
54
|
+
* @param token - The link's token.
|
|
55
|
+
* @param [paths] - Pages that are somewhere else in this app.
|
|
56
|
+
* @returns The URL. The token is in its fragment, which no server or proxy on the way is sent.
|
|
57
|
+
*/
|
|
58
|
+
export function signInLinkUrl(appUrl, token, paths = {}) {
|
|
59
|
+
return `${appUrl}${{ ...AUTH_PATHS, ...paths }.link}#token=${encodeURIComponent(token)}`;
|
|
60
|
+
}
|
package/llms.txt
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
Agent-facing docs for @cubicecho/server-kit: one task or concept per page, then what each package.json "exports" entry exports. Generated from _agents/docs/ and the doc comments in src/ by @cubicecho/agent-docs; edit those, not this file.
|
|
6
6
|
|
|
7
|
-
Requires Node >=22. Peer dependencies: `@better-auth/sso` >=1.7.28 <1.8.0 (optional), `@cubicecho/graphql-mcp` ^3.1.0 (optional), `@electric-sql/pglite` ^0.5.0 (optional), `better-auth` >=1.7.28 <1.8.0, `drizzle-orm` 1.0.0-rc.5, `express` ^5.0.0, `graphql` ^16.0.0, `graphql-yoga` ^6.0.0, `postgres` ^3.4.0 (optional), `vitest` ^5.0.0 (optional).
|
|
7
|
+
Requires Node >=22. Peer dependencies: `@better-auth/sso` >=1.7.28 <1.8.0 (optional), `@cubicecho/better-auth-oidc-pairing` ^1.1.0 (optional), `@cubicecho/graphql-mcp` ^3.1.0 (optional), `@electric-sql/pglite` ^0.5.0 (optional), `better-auth` >=1.7.28 <1.8.0 (optional), `drizzle-orm` 1.0.0-rc.5, `express` ^5.0.0, `graphql` ^16.0.0, `graphql-yoga` ^6.0.0, `postgres` ^3.4.0 (optional), `vitest` ^5.0.0 (optional).
|
|
8
8
|
|
|
9
9
|
## Docs
|
|
10
10
|
|
|
@@ -25,6 +25,8 @@ Requires Node >=22. Peer dependencies: `@better-auth/sso` >=1.7.28 <1.8.0 (optio
|
|
|
25
25
|
- `AuthSettings` (type): Session and link lifetimes.
|
|
26
26
|
- `RATE_LIMIT_DEFAULTS`: What `createRateLimiter` uses when the app overrides nothing.
|
|
27
27
|
- `RateLimitSettings` (type): The sign-in throttle.
|
|
28
|
+
- `SETUP_DEFAULTS`: What `createSetupGate`, `setupProblem` and `setupPlugin` use when the app overrides nothing.
|
|
29
|
+
- `SetupSettings` (type): Setting up an instance that has no account.
|
|
28
30
|
- `MagicLink` (type): What delivering one sign-in link is given.
|
|
29
31
|
- `OidcOptions` (type): OIDC sign-in and pairing, without the two URLs, which follow from `appUrl`.
|
|
30
32
|
- `SignInOptions` (type): What an app gives `signInPlugins`, besides OIDC.
|
|
@@ -37,6 +39,24 @@ Requires Node >=22. Peer dependencies: `@better-auth/sso` >=1.7.28 <1.8.0 (optio
|
|
|
37
39
|
- `RateLimiter` (type): Sliding-window counter, in process.
|
|
38
40
|
- `ThrottleContext` (type): What throttling needs of a request's context.
|
|
39
41
|
- `throttle`: Counts one sign-in attempt, by the caller's address and by the account when the step names one.
|
|
42
|
+
- `AuthInstance` (type): The part of an auth instance that setup and sign-in links use, whatever its plugins.
|
|
43
|
+
- `asSetupRefusal`: Turns better-auth's error for a refusal into the GraphQL one.
|
|
44
|
+
- `Claim` (type): What a claim is made with.
|
|
45
|
+
- `claimInstance`: Makes an instance's first account and signs it in.
|
|
46
|
+
- `createSetupGate`: Builds the door an instance with no account is set up through.
|
|
47
|
+
- `isSetUp`: Whether an instance has been set up.
|
|
48
|
+
- `SetupEnvironment` (type): What `setupProblem` looks at.
|
|
49
|
+
- `SetupGate` (type): The door an instance with no account is set up through.
|
|
50
|
+
- `SetupGateOptions` (type): Who may set up an instance that has no account.
|
|
51
|
+
- `SetupRefusal`: Why setting an instance up was refused: `extensions.reason`, or the code of better-auth's error.
|
|
52
|
+
- `SignedIn` (type): A signed-in session.
|
|
53
|
+
- `setupNotice`: What to log at boot while an instance has no account.
|
|
54
|
+
- `setupProblem`: What is wrong with the setup variables, for an app's preflight to refuse to boot on.
|
|
55
|
+
- `setupRefused`: The GraphQL error for a refusal.
|
|
56
|
+
- `createSignInLink`: Makes a link that signs its holder in as a user, once.
|
|
57
|
+
- `SignInLink` (type): A link that signs one person in, once.
|
|
58
|
+
- `signInLinkUrl`: The address a link is opened at.
|
|
59
|
+
- `spendSignInLink`: Signs in with a link, and uses it up.
|
|
40
60
|
|
|
41
61
|
## Exports: @cubicecho/server-kit/columns
|
|
42
62
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cubicecho/server-kit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "The server code every cubicecho GraphQL backend shares: database boot, id columns and the checks that keep a schema to the standard.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Benjamin Van Treese",
|
|
@@ -72,6 +72,7 @@
|
|
|
72
72
|
},
|
|
73
73
|
"peerDependencies": {
|
|
74
74
|
"@better-auth/sso": ">=1.7.28 <1.8.0",
|
|
75
|
+
"@cubicecho/better-auth-oidc-pairing": "^1.1.0",
|
|
75
76
|
"@cubicecho/graphql-mcp": "^3.1.0",
|
|
76
77
|
"@electric-sql/pglite": "^0.5.0",
|
|
77
78
|
"better-auth": ">=1.7.28 <1.8.0",
|
|
@@ -86,12 +87,18 @@
|
|
|
86
87
|
"@better-auth/sso": {
|
|
87
88
|
"optional": true
|
|
88
89
|
},
|
|
90
|
+
"@cubicecho/better-auth-oidc-pairing": {
|
|
91
|
+
"optional": true
|
|
92
|
+
},
|
|
89
93
|
"@cubicecho/graphql-mcp": {
|
|
90
94
|
"optional": true
|
|
91
95
|
},
|
|
92
96
|
"@electric-sql/pglite": {
|
|
93
97
|
"optional": true
|
|
94
98
|
},
|
|
99
|
+
"better-auth": {
|
|
100
|
+
"optional": true
|
|
101
|
+
},
|
|
95
102
|
"postgres": {
|
|
96
103
|
"optional": true
|
|
97
104
|
},
|
|
@@ -103,6 +110,7 @@
|
|
|
103
110
|
"@better-auth/sso": "^1.7.28",
|
|
104
111
|
"@biomejs/biome": "^2.6.2",
|
|
105
112
|
"@cubicecho/agent-docs": "^0.2.0",
|
|
113
|
+
"@cubicecho/better-auth-oidc-pairing": "^1.1.0",
|
|
106
114
|
"@cubicecho/graphql-mcp": "^3.2.0",
|
|
107
115
|
"@electric-sql/pglite": "^0.5.17",
|
|
108
116
|
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
@@ -127,7 +135,6 @@
|
|
|
127
135
|
"zod": "^4.6.7"
|
|
128
136
|
},
|
|
129
137
|
"dependencies": {
|
|
130
|
-
"@cubicecho/better-auth-oidc-pairing": "^1.1.0",
|
|
131
138
|
"@escape.tech/graphql-armor-max-aliases": "^2.6.3",
|
|
132
139
|
"@escape.tech/graphql-armor-max-depth": "^2.4.3",
|
|
133
140
|
"graphql-query-complexity": "^2.0.0"
|