@soroi/auth 0.0.0-stage → 0.1.1
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.md +154 -0
- package/LICENSE +21 -0
- package/README.md +26 -2
- package/dist/account.d.ts +52 -0
- package/dist/account.js +177 -0
- package/dist/adapters/next.d.ts +6 -0
- package/dist/adapters/next.js +35 -0
- package/dist/adapters/tanstack.d.ts +12 -0
- package/dist/adapters/tanstack.js +40 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +76 -0
- package/dist/core.d.ts +122 -0
- package/dist/core.js +351 -0
- package/dist/crypto.d.ts +12 -0
- package/dist/crypto.js +69 -0
- package/dist/db.d.ts +29 -0
- package/dist/db.js +55 -0
- package/dist/email.d.ts +9 -0
- package/dist/email.js +64 -0
- package/dist/errors.d.ts +24 -0
- package/dist/errors.js +88 -0
- package/dist/index.d.ts +202 -0
- package/dist/index.js +255 -0
- package/dist/methods.d.ts +16 -0
- package/dist/methods.js +21 -0
- package/dist/migrations.d.ts +5 -0
- package/dist/migrations.js +154 -0
- package/dist/modules/oauth-server.d.ts +110 -0
- package/dist/modules/oauth-server.js +568 -0
- package/dist/modules/tokens.d.ts +31 -0
- package/dist/modules/tokens.js +107 -0
- package/dist/modules/two-factor.d.ts +41 -0
- package/dist/modules/two-factor.js +169 -0
- package/dist/modules/workspaces.d.ts +140 -0
- package/dist/modules/workspaces.js +297 -0
- package/dist/oauth/flow.d.ts +5 -0
- package/dist/oauth/flow.js +161 -0
- package/dist/oauth/providers.d.ts +29 -0
- package/dist/oauth/providers.js +124 -0
- package/dist/password-hash.d.ts +8 -0
- package/dist/password-hash.js +68 -0
- package/dist/password.d.ts +49 -0
- package/dist/password.js +181 -0
- package/dist/routes.d.ts +5 -0
- package/dist/routes.js +77 -0
- package/dist/sessions.d.ts +51 -0
- package/dist/sessions.js +184 -0
- package/dist/testing.d.ts +15 -0
- package/dist/testing.js +32 -0
- package/dist/types.d.ts +184 -0
- package/dist/types.js +1 -0
- package/package.json +75 -4
package/dist/email.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/** Sends through Resend's HTTP API. */
|
|
2
|
+
export function resend(apiKey) {
|
|
3
|
+
return async (message) => {
|
|
4
|
+
if (!apiKey)
|
|
5
|
+
throw new Error("@soroi/auth: RESEND_API_KEY is not set");
|
|
6
|
+
const response = await fetch("https://api.resend.com/emails", {
|
|
7
|
+
method: "POST",
|
|
8
|
+
headers: { authorization: `Bearer ${apiKey}`, "content-type": "application/json" },
|
|
9
|
+
body: JSON.stringify(message),
|
|
10
|
+
});
|
|
11
|
+
if (!response.ok)
|
|
12
|
+
throw new Error(`@soroi/auth: Resend answered ${response.status}: ${await response.text()}`);
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
const CONSOLE = Symbol("consoleEmail");
|
|
16
|
+
/** Prints e-mails, links included, to the console. The default outside production. `createAuth` refuses it in production. */
|
|
17
|
+
export function consoleEmail() {
|
|
18
|
+
const send = async (message) => {
|
|
19
|
+
console.info(`\n[@soroi/auth] e-mail to ${message.to}: ${message.subject}\n${message.text}\n`);
|
|
20
|
+
};
|
|
21
|
+
return Object.assign(send, { [CONSOLE]: true });
|
|
22
|
+
}
|
|
23
|
+
export const isConsoleEmail = (send) => CONSOLE in send;
|
|
24
|
+
const escape = (value) => value.replace(/[&<>"']/g, (char) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[char]);
|
|
25
|
+
function layout(title, lines, button) {
|
|
26
|
+
const html = [
|
|
27
|
+
`<div style="font-family:system-ui,sans-serif;max-width:480px;margin:0 auto;padding:24px;color:#111">`,
|
|
28
|
+
`<h1 style="font-size:20px;margin:0 0 16px">${escape(title)}</h1>`,
|
|
29
|
+
...lines.map((line) => `<p style="line-height:1.5;margin:0 0 12px">${escape(line)}</p>`),
|
|
30
|
+
button
|
|
31
|
+
? `<p style="margin:24px 0"><a href="${escape(button.url)}" style="background:#111;color:#fff;padding:10px 16px;border-radius:6px;text-decoration:none">${escape(button.label)}</a></p><p style="font-size:12px;color:#666;word-break:break-all">${escape(button.url)}</p>`
|
|
32
|
+
: "",
|
|
33
|
+
`</div>`,
|
|
34
|
+
].join("");
|
|
35
|
+
const text = [title, "", ...lines, ...(button ? ["", `${button.label}: ${button.url}`] : [])].join("\n");
|
|
36
|
+
return { subject: title, html, text };
|
|
37
|
+
}
|
|
38
|
+
export const defaultTemplates = {
|
|
39
|
+
verifyEmail: ({ appName, url }) => layout(`Confirm your e-mail for ${appName}`, ["Open the link to confirm your e-mail and sign in.", "The link works for 24 hours."], {
|
|
40
|
+
label: "Confirm e-mail",
|
|
41
|
+
url,
|
|
42
|
+
}),
|
|
43
|
+
resetPassword: ({ appName, url }) => layout(`Reset your ${appName} password`, ["Open the link to choose a new password. The link works for 1 hour.", "If you did not ask for this, ignore this e-mail."], {
|
|
44
|
+
label: "Choose a new password",
|
|
45
|
+
url,
|
|
46
|
+
}),
|
|
47
|
+
changeEmail: ({ appName, url }) => layout(`Confirm your new e-mail for ${appName}`, ["Open the link to use this address for your account. The link works for 24 hours."], {
|
|
48
|
+
label: "Confirm new e-mail",
|
|
49
|
+
url,
|
|
50
|
+
}),
|
|
51
|
+
emailChanged: ({ appName, newEmail }) => layout(`Your ${appName} e-mail changed`, [`Your account now uses ${newEmail}.`, "If you did not do this, contact support at once."]),
|
|
52
|
+
passwordChanged: ({ appName }) => layout(`Your ${appName} password changed`, ["If you did not do this, reset your password at once."]),
|
|
53
|
+
accountExists: ({ appName, url }) => layout(`You already have a ${appName} account`, ["Someone tried to sign up with this e-mail. You can sign in instead."], {
|
|
54
|
+
label: "Sign in",
|
|
55
|
+
url,
|
|
56
|
+
}),
|
|
57
|
+
accountLinked: ({ appName, provider }) => layout(`A ${provider} account was connected to ${appName}`, [`You can now sign in to ${appName} with this ${provider} account.`, "If you did not do this, reset your password and remove it in your settings at once."]),
|
|
58
|
+
tokenCreated: ({ appName, tokenName }) => layout(`A new ${appName} API token was created`, [`An API token named "${tokenName}" can now act as your account.`, "If you did not do this, revoke it in your settings at once."]),
|
|
59
|
+
// User-written text (workspace and inviter names) stays out of the subject line.
|
|
60
|
+
invite: ({ appName, url, workspace, invitedBy }) => layout(`You are invited to a workspace on ${appName}`, [`${invitedBy ?? "Someone"} invited you to the workspace ${workspace}. The invite works for 7 days.`], {
|
|
61
|
+
label: "Accept invite",
|
|
62
|
+
url,
|
|
63
|
+
}),
|
|
64
|
+
};
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export declare const authErrors: readonly ["invalid_input", "invalid_email", "weak_password", "password_too_long", "invalid_credentials", "email_not_verified", "email_taken", "signup_closed", "access_denied", "rate_limited", "forbidden_origin", "not_signed_in", "reauth_required", "invalid_token", "link_expired", "oauth_failed", "oauth_denied", "oauth_email_unverified", "account_linked_elsewhere", "last_sign_in_method", "method_disabled", "invalid_code", "two_factor_not_enabled", "two_factor_already_enabled", "challenge_expired", "not_found", "forbidden", "already_member", "invite_email_mismatch", "owner_cannot_leave", "transfer_ownership_first", "email_unavailable"];
|
|
2
|
+
export type AuthError = (typeof authErrors)[number];
|
|
3
|
+
export type Ok<T extends object = {}> = {
|
|
4
|
+
ok: true;
|
|
5
|
+
} & T;
|
|
6
|
+
export type Fail<E extends AuthError = AuthError> = {
|
|
7
|
+
ok: false;
|
|
8
|
+
error: E;
|
|
9
|
+
};
|
|
10
|
+
export type Result<T extends object, E extends AuthError> = Ok<T> | Fail<E>;
|
|
11
|
+
/** Thrown by `require*` helpers and caught by the result-returning functions. */
|
|
12
|
+
export declare class AuthException extends Error {
|
|
13
|
+
readonly code: AuthError;
|
|
14
|
+
constructor(code: AuthError);
|
|
15
|
+
}
|
|
16
|
+
/** A mistake in the app's auth config. Not shown to end users. */
|
|
17
|
+
export declare class AuthConfigError extends Error {
|
|
18
|
+
constructor(message: string);
|
|
19
|
+
}
|
|
20
|
+
export declare const fail: <E extends AuthError>(error: E) => Fail<E>;
|
|
21
|
+
export declare const isAuthError: (value: unknown) => value is AuthError;
|
|
22
|
+
export declare const messages: {
|
|
23
|
+
en: Record<AuthError, string>;
|
|
24
|
+
};
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
export const authErrors = [
|
|
2
|
+
"invalid_input",
|
|
3
|
+
"invalid_email",
|
|
4
|
+
"weak_password",
|
|
5
|
+
"password_too_long",
|
|
6
|
+
"invalid_credentials",
|
|
7
|
+
"email_not_verified",
|
|
8
|
+
"email_taken",
|
|
9
|
+
"signup_closed",
|
|
10
|
+
"access_denied",
|
|
11
|
+
"rate_limited",
|
|
12
|
+
"forbidden_origin",
|
|
13
|
+
"not_signed_in",
|
|
14
|
+
"reauth_required",
|
|
15
|
+
"invalid_token",
|
|
16
|
+
"link_expired",
|
|
17
|
+
"oauth_failed",
|
|
18
|
+
"oauth_denied",
|
|
19
|
+
"oauth_email_unverified",
|
|
20
|
+
"account_linked_elsewhere",
|
|
21
|
+
"last_sign_in_method",
|
|
22
|
+
"method_disabled",
|
|
23
|
+
"invalid_code",
|
|
24
|
+
"two_factor_not_enabled",
|
|
25
|
+
"two_factor_already_enabled",
|
|
26
|
+
"challenge_expired",
|
|
27
|
+
"not_found",
|
|
28
|
+
"forbidden",
|
|
29
|
+
"already_member",
|
|
30
|
+
"invite_email_mismatch",
|
|
31
|
+
"owner_cannot_leave",
|
|
32
|
+
"transfer_ownership_first",
|
|
33
|
+
"email_unavailable",
|
|
34
|
+
];
|
|
35
|
+
/** Thrown by `require*` helpers and caught by the result-returning functions. */
|
|
36
|
+
export class AuthException extends Error {
|
|
37
|
+
code;
|
|
38
|
+
constructor(code) {
|
|
39
|
+
super(code);
|
|
40
|
+
this.code = code;
|
|
41
|
+
this.name = "AuthException";
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/** A mistake in the app's auth config. Not shown to end users. */
|
|
45
|
+
export class AuthConfigError extends Error {
|
|
46
|
+
constructor(message) {
|
|
47
|
+
super(`@soroi/auth: ${message}`);
|
|
48
|
+
this.name = "AuthConfigError";
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
export const fail = (error) => ({ ok: false, error });
|
|
52
|
+
export const isAuthError = (value) => typeof value === "string" && authErrors.includes(value);
|
|
53
|
+
export const messages = {
|
|
54
|
+
en: {
|
|
55
|
+
invalid_input: "Check the form and try again.",
|
|
56
|
+
invalid_email: "Enter a valid e-mail address.",
|
|
57
|
+
weak_password: "The password is too short.",
|
|
58
|
+
password_too_long: "The password is too long.",
|
|
59
|
+
invalid_credentials: "Wrong e-mail or password.",
|
|
60
|
+
email_not_verified: "Confirm your e-mail first. We sent you a new link.",
|
|
61
|
+
email_taken: "An account with this e-mail already exists.",
|
|
62
|
+
signup_closed: "Sign-up is closed.",
|
|
63
|
+
access_denied: "This account has no access.",
|
|
64
|
+
rate_limited: "Too many attempts. Try again in a few minutes.",
|
|
65
|
+
forbidden_origin: "The request came from another site.",
|
|
66
|
+
not_signed_in: "Sign in to continue.",
|
|
67
|
+
reauth_required: "Confirm it is you: enter your password or sign in again.",
|
|
68
|
+
invalid_token: "The link is not valid.",
|
|
69
|
+
link_expired: "The link has expired. Ask for a new one.",
|
|
70
|
+
oauth_failed: "The sign-in did not work. Try again.",
|
|
71
|
+
oauth_denied: "The sign-in was cancelled.",
|
|
72
|
+
oauth_email_unverified: "Your e-mail at this provider is not verified.",
|
|
73
|
+
account_linked_elsewhere: "This account is already linked to another user.",
|
|
74
|
+
last_sign_in_method: "Add another sign-in method first.",
|
|
75
|
+
method_disabled: "This sign-in method is not enabled.",
|
|
76
|
+
invalid_code: "The code is not correct.",
|
|
77
|
+
two_factor_not_enabled: "Two-factor sign-in is not on.",
|
|
78
|
+
two_factor_already_enabled: "Two-factor sign-in is already on.",
|
|
79
|
+
challenge_expired: "The sign-in expired. Sign in again.",
|
|
80
|
+
not_found: "Not found.",
|
|
81
|
+
forbidden: "You do not have permission to do this.",
|
|
82
|
+
already_member: "This person is already a member.",
|
|
83
|
+
invite_email_mismatch: "This invite is for another e-mail address.",
|
|
84
|
+
owner_cannot_leave: "Transfer the ownership before you leave.",
|
|
85
|
+
transfer_ownership_first: "Transfer or delete your workspaces first.",
|
|
86
|
+
email_unavailable: "E-mail is not set up here yet, so this does not work. Ask the owner.",
|
|
87
|
+
},
|
|
88
|
+
};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import * as account from "./account.js";
|
|
2
|
+
import { type Core, type RequestContext } from "./core.js";
|
|
3
|
+
import { type AuthError, type Fail } from "./errors.js";
|
|
4
|
+
import * as twoFactor from "./modules/two-factor.js";
|
|
5
|
+
import * as tokens from "./modules/tokens.js";
|
|
6
|
+
import * as workspaces from "./modules/workspaces.js";
|
|
7
|
+
import * as password from "./password.js";
|
|
8
|
+
import * as sessions from "./sessions.js";
|
|
9
|
+
import type { AuthConfig, Session, User } from "./types.js";
|
|
10
|
+
export { allowlist, github, google, password } from "./methods.js";
|
|
11
|
+
export { bunSql, pg, postgresJs, type Db, type Row } from "./db.js";
|
|
12
|
+
export { consoleEmail, defaultTemplates, resend } from "./email.js";
|
|
13
|
+
export { RECENT_MS } from "./sessions.js";
|
|
14
|
+
export { AuthConfigError, AuthException, authErrors, isAuthError, messages, type AuthError, type Fail, type Ok, type Result } from "./errors.js";
|
|
15
|
+
export type * from "./types.js";
|
|
16
|
+
export { createOAuthServer, oauthServerTables, redirectUriProblem, type OAuthServer, type OAuthServerConfig, type PendingConsent, type RedirectTarget, } from "./modules/oauth-server.js";
|
|
17
|
+
export type { ApiToken } from "./modules/tokens.js";
|
|
18
|
+
export type { Invite, Member, Membership, Workspace } from "./modules/workspaces.js";
|
|
19
|
+
/** Marks objects made by `createAuth`. Used by `@soroi/auth/testing` and the CLI. */
|
|
20
|
+
export declare const CORE: unique symbol;
|
|
21
|
+
type Fn = (core: Core, ctx: RequestContext, input: any) => Promise<any>;
|
|
22
|
+
type Change<F extends Fn> = undefined extends Parameters<F>[2] ? (input?: Parameters<F>[2]) => Promise<Awaited<ReturnType<F>> | Fail<AuthError>> : (input: Parameters<F>[2]) => Promise<Awaited<ReturnType<F>> | Fail<AuthError>>;
|
|
23
|
+
type Read<F extends (core: Core, ctx: RequestContext, input?: any) => Promise<any>> = (input?: Parameters<F>[2]) => ReturnType<F>;
|
|
24
|
+
type RoleOf<C> = C extends {
|
|
25
|
+
workspaces: {
|
|
26
|
+
roles: infer R extends readonly string[];
|
|
27
|
+
};
|
|
28
|
+
} ? R[number] : string;
|
|
29
|
+
type WorkspacesApi<Role extends string> = {
|
|
30
|
+
/** The session's active workspace, or null. Throws `not_signed_in`. */
|
|
31
|
+
current(): Promise<{
|
|
32
|
+
workspace: workspaces.Workspace;
|
|
33
|
+
role: Role;
|
|
34
|
+
} | null>;
|
|
35
|
+
list(): Promise<{
|
|
36
|
+
workspace: workspaces.Workspace;
|
|
37
|
+
role: Role;
|
|
38
|
+
}[]>;
|
|
39
|
+
/** Redirects to the sign-in page when signed out. Throws `AuthException("forbidden")` below `role`. */
|
|
40
|
+
requireMember(options?: {
|
|
41
|
+
role?: Role;
|
|
42
|
+
workspaceId?: string;
|
|
43
|
+
next?: string;
|
|
44
|
+
}): Promise<{
|
|
45
|
+
user: User;
|
|
46
|
+
session: Session;
|
|
47
|
+
workspace: workspaces.Workspace;
|
|
48
|
+
role: Role;
|
|
49
|
+
}>;
|
|
50
|
+
create: Change<typeof workspaces.create>;
|
|
51
|
+
switch: Change<typeof workspaces.switchTo>;
|
|
52
|
+
rename: Change<typeof workspaces.rename>;
|
|
53
|
+
delete: Change<typeof workspaces.remove>;
|
|
54
|
+
members(input?: {
|
|
55
|
+
workspaceId?: string;
|
|
56
|
+
}): Promise<(Omit<workspaces.Member, "role"> & {
|
|
57
|
+
role: Role;
|
|
58
|
+
})[]>;
|
|
59
|
+
invite(input: {
|
|
60
|
+
email: string;
|
|
61
|
+
role: Role;
|
|
62
|
+
workspaceId?: string;
|
|
63
|
+
}): Promise<{
|
|
64
|
+
ok: true;
|
|
65
|
+
} | Fail<AuthError>>;
|
|
66
|
+
invites(input?: {
|
|
67
|
+
workspaceId?: string;
|
|
68
|
+
}): Promise<(Omit<workspaces.Invite, "role"> & {
|
|
69
|
+
role: Role;
|
|
70
|
+
})[]>;
|
|
71
|
+
revokeInvite: Change<typeof workspaces.revokeInvite>;
|
|
72
|
+
/** Works signed out, for the invite page. Does not use the invite up. */
|
|
73
|
+
inviteInfo(input: {
|
|
74
|
+
token: string;
|
|
75
|
+
}): ReturnType<typeof workspaces.inviteInfo>;
|
|
76
|
+
acceptInvite: Change<typeof workspaces.acceptInvite>;
|
|
77
|
+
setRole(input: {
|
|
78
|
+
userId: string;
|
|
79
|
+
role: Role;
|
|
80
|
+
workspaceId?: string;
|
|
81
|
+
}): Promise<{
|
|
82
|
+
ok: true;
|
|
83
|
+
} | Fail<AuthError>>;
|
|
84
|
+
removeMember: Change<typeof workspaces.removeMember>;
|
|
85
|
+
leave: Change<typeof workspaces.leave>;
|
|
86
|
+
transferOwnership: Change<typeof workspaces.transferOwnership>;
|
|
87
|
+
};
|
|
88
|
+
type BaseApi = {
|
|
89
|
+
/** The signed-in user, or null. Also accepts API tokens when `tokens` is on. */
|
|
90
|
+
user(): Promise<User | null>;
|
|
91
|
+
/** `reauthAt` is the last sign-in or re-authentication of a browser session. Compare it with `RECENT_MS`. */
|
|
92
|
+
session(): Promise<{
|
|
93
|
+
user: User;
|
|
94
|
+
session: Session;
|
|
95
|
+
scopes?: string[];
|
|
96
|
+
reauthAt?: Date;
|
|
97
|
+
} | null>;
|
|
98
|
+
/**
|
|
99
|
+
* Redirects to `pages.signIn?next=<current page>` when signed out (throws `not_signed_in` without an adapter).
|
|
100
|
+
* Pass `next` where the framework cannot tell the page, e.g. in Next.js server components.
|
|
101
|
+
*/
|
|
102
|
+
requireUser(options?: {
|
|
103
|
+
next?: string;
|
|
104
|
+
}): Promise<User>;
|
|
105
|
+
signOut(): Promise<{
|
|
106
|
+
ok: true;
|
|
107
|
+
} | Fail<AuthError>>;
|
|
108
|
+
password: {
|
|
109
|
+
signUp: Change<typeof password.signUp>;
|
|
110
|
+
signIn: Change<typeof password.signIn>;
|
|
111
|
+
requestReset: Change<typeof password.requestReset>;
|
|
112
|
+
reset: Change<typeof password.resetPassword>;
|
|
113
|
+
resendVerification: Change<typeof password.resendVerification>;
|
|
114
|
+
};
|
|
115
|
+
account: {
|
|
116
|
+
/** Confirms the password, or a code with two-factor on; sensitive changes then work for 15 minutes. Others sign in again. */
|
|
117
|
+
reauthenticate: Change<typeof account.reauthenticate>;
|
|
118
|
+
changePassword: Change<typeof account.changePassword>;
|
|
119
|
+
changeEmail: Change<typeof account.changeEmail>;
|
|
120
|
+
linked: Read<typeof account.linkedAccounts>;
|
|
121
|
+
unlink: Change<typeof account.unlink>;
|
|
122
|
+
delete: Change<typeof account.deleteAccount>;
|
|
123
|
+
};
|
|
124
|
+
sessions: {
|
|
125
|
+
list(): ReturnType<typeof sessions.listSessions>;
|
|
126
|
+
revoke(input: {
|
|
127
|
+
id: string;
|
|
128
|
+
}): Promise<{
|
|
129
|
+
ok: true;
|
|
130
|
+
} | Fail<AuthError>>;
|
|
131
|
+
revokeOthers(): Promise<{
|
|
132
|
+
ok: true;
|
|
133
|
+
} | Fail<AuthError>>;
|
|
134
|
+
};
|
|
135
|
+
};
|
|
136
|
+
type ModuleApis<C> = (C extends {
|
|
137
|
+
twoFactor: true | object;
|
|
138
|
+
} ? {
|
|
139
|
+
twoFactor: {
|
|
140
|
+
status: Read<typeof twoFactor.status>;
|
|
141
|
+
setup: Change<typeof twoFactor.setup>;
|
|
142
|
+
enable: Change<typeof twoFactor.enable>;
|
|
143
|
+
disable: Change<typeof twoFactor.disable>;
|
|
144
|
+
regenerateRecoveryCodes: Change<typeof twoFactor.regenerateRecoveryCodes>;
|
|
145
|
+
/** The second sign-in step. */
|
|
146
|
+
verify: Change<typeof twoFactor.verify>;
|
|
147
|
+
};
|
|
148
|
+
} : {}) & (C extends {
|
|
149
|
+
workspaces: object;
|
|
150
|
+
} ? {
|
|
151
|
+
workspaces: WorkspacesApi<RoleOf<C>>;
|
|
152
|
+
} : {}) & (C extends {
|
|
153
|
+
tokens: true | object;
|
|
154
|
+
} ? {
|
|
155
|
+
tokens: {
|
|
156
|
+
create: Change<typeof tokens.create>;
|
|
157
|
+
list(): ReturnType<typeof tokens.list>;
|
|
158
|
+
revoke: Change<typeof tokens.revoke>;
|
|
159
|
+
};
|
|
160
|
+
} : {});
|
|
161
|
+
export type RequestApi<C extends AuthConfig = AuthConfig> = BaseApi & ModuleApis<C>;
|
|
162
|
+
export type DoctorCheck = {
|
|
163
|
+
level: "ok" | "warn" | "error";
|
|
164
|
+
message: string;
|
|
165
|
+
};
|
|
166
|
+
export type Auth<C extends AuthConfig = AuthConfig> = RequestApi<C> & {
|
|
167
|
+
/** Handles `<basePath>/*`. Mount it on a catch-all route. */
|
|
168
|
+
handler(request: Request): Promise<Response>;
|
|
169
|
+
/** `{ GET, POST }` for TanStack Start server routes and similar. */
|
|
170
|
+
routes: {
|
|
171
|
+
GET: (ctx: {
|
|
172
|
+
request: Request;
|
|
173
|
+
}) => Promise<Response>;
|
|
174
|
+
POST: (ctx: {
|
|
175
|
+
request: Request;
|
|
176
|
+
}) => Promise<Response>;
|
|
177
|
+
};
|
|
178
|
+
/** The same API bound to one request, for frameworks without an adapter. Cookies land in `headers`. */
|
|
179
|
+
withRequest(request: Request): RequestApi<C> & {
|
|
180
|
+
headers: Headers;
|
|
181
|
+
};
|
|
182
|
+
/** Server-side user management, for scripts and admin tools. No request needed. */
|
|
183
|
+
users: {
|
|
184
|
+
create(input: {
|
|
185
|
+
email: string;
|
|
186
|
+
password?: string;
|
|
187
|
+
name?: string;
|
|
188
|
+
emailVerified?: boolean;
|
|
189
|
+
}): Promise<User>;
|
|
190
|
+
get(id: string): Promise<User | null>;
|
|
191
|
+
byEmail(email: string): Promise<User | null>;
|
|
192
|
+
/** Also ends every session, API token and pending e-mail change of the user. */
|
|
193
|
+
setPassword(id: string, password: string): Promise<void>;
|
|
194
|
+
delete(id: string): Promise<void>;
|
|
195
|
+
};
|
|
196
|
+
migrate(): Promise<number[]>;
|
|
197
|
+
doctor(): Promise<DoctorCheck[]>;
|
|
198
|
+
/** Waits for e-mails and other work sent to the background. For tests and graceful shutdown. */
|
|
199
|
+
settled(): Promise<void>;
|
|
200
|
+
readonly [CORE]: Core;
|
|
201
|
+
};
|
|
202
|
+
export declare function createAuth<const C extends AuthConfig>(config: C): Auth<C>;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
import * as account from "./account.js";
|
|
2
|
+
import { assertSameOrigin, createContext, createCore, link, normalizeEmail, pageUrl, safeNext, signInLink, serializeCookie, validEmail, } from "./core.js";
|
|
3
|
+
import {} from "./db.js";
|
|
4
|
+
import { AuthConfigError, AuthException, fail } from "./errors.js";
|
|
5
|
+
import { appliedMigration, latestMigration, migrate } from "./migrations.js";
|
|
6
|
+
import * as twoFactor from "./modules/two-factor.js";
|
|
7
|
+
import * as tokens from "./modules/tokens.js";
|
|
8
|
+
import * as workspaces from "./modules/workspaces.js";
|
|
9
|
+
import { redirectUri } from "./oauth/flow.js";
|
|
10
|
+
import * as password from "./password.js";
|
|
11
|
+
import { assertHashRuntime, hashPassword, hashRuntime } from "./password-hash.js";
|
|
12
|
+
import { devLoginAllowed, handle } from "./routes.js";
|
|
13
|
+
import * as sessions from "./sessions.js";
|
|
14
|
+
export { allowlist, github, google, password } from "./methods.js";
|
|
15
|
+
export { bunSql, pg, postgresJs } from "./db.js";
|
|
16
|
+
export { consoleEmail, defaultTemplates, resend } from "./email.js";
|
|
17
|
+
export { RECENT_MS } from "./sessions.js";
|
|
18
|
+
export { AuthConfigError, AuthException, authErrors, isAuthError, messages } from "./errors.js";
|
|
19
|
+
export { createOAuthServer, oauthServerTables, redirectUriProblem, } from "./modules/oauth-server.js";
|
|
20
|
+
/** Marks objects made by `createAuth`. Used by `@soroi/auth/testing` and the CLI. */
|
|
21
|
+
export const CORE = Symbol.for("@soroi/auth/core");
|
|
22
|
+
/** Runs one call on the request context, then waits for the cookie writes the call made. */
|
|
23
|
+
async function withCtx(getCtx, fn) {
|
|
24
|
+
const ctx = await getCtx();
|
|
25
|
+
try {
|
|
26
|
+
return await fn(ctx);
|
|
27
|
+
}
|
|
28
|
+
finally {
|
|
29
|
+
await ctx.flush();
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/** Checks the origin and turns thrown `AuthException`s into `{ ok: false, error }` results. */
|
|
33
|
+
const change = (core, getCtx, fn) => async (input) => {
|
|
34
|
+
try {
|
|
35
|
+
return await withCtx(getCtx, async (ctx) => {
|
|
36
|
+
assertSameOrigin(core, ctx);
|
|
37
|
+
return fn(core, ctx, input);
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
if (error instanceof AuthException)
|
|
42
|
+
return fail(error.code);
|
|
43
|
+
throw error;
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
const read = (core, getCtx, fn) => (input) => withCtx(getCtx, (ctx) => fn(core, ctx, input));
|
|
47
|
+
function publicSession(current) {
|
|
48
|
+
if (!current)
|
|
49
|
+
return null;
|
|
50
|
+
return { user: current.user, session: current.session, ...(current.tokenScopes ? { scopes: current.tokenScopes } : {}), ...(current.reauthAt ? { reauthAt: current.reauthAt } : {}) };
|
|
51
|
+
}
|
|
52
|
+
function buildApi(core, getCtx, redirect) {
|
|
53
|
+
const signInRedirect = (ctx, given) => {
|
|
54
|
+
const next = given ? safeNext(core, given, "") || null : pageUrl(core, ctx);
|
|
55
|
+
return redirect(signInLink(core, next ? { next } : {}));
|
|
56
|
+
};
|
|
57
|
+
const api = {
|
|
58
|
+
user: () => withCtx(getCtx, async (ctx) => (await sessions.readSession(core, ctx))?.user ?? null),
|
|
59
|
+
session: () => withCtx(getCtx, async (ctx) => publicSession(await sessions.readSession(core, ctx))),
|
|
60
|
+
requireUser: (options) => withCtx(getCtx, async (ctx) => (await sessions.readSession(core, ctx))?.user ?? signInRedirect(ctx, options?.next)),
|
|
61
|
+
signOut: change(core, getCtx, async (c, ctx) => {
|
|
62
|
+
await sessions.signOut(c, ctx);
|
|
63
|
+
return { ok: true };
|
|
64
|
+
}),
|
|
65
|
+
password: {
|
|
66
|
+
signUp: change(core, getCtx, password.signUp),
|
|
67
|
+
signIn: change(core, getCtx, password.signIn),
|
|
68
|
+
requestReset: change(core, getCtx, password.requestReset),
|
|
69
|
+
reset: change(core, getCtx, password.resetPassword),
|
|
70
|
+
resendVerification: change(core, getCtx, password.resendVerification),
|
|
71
|
+
},
|
|
72
|
+
account: {
|
|
73
|
+
reauthenticate: change(core, getCtx, account.reauthenticate),
|
|
74
|
+
changePassword: change(core, getCtx, account.changePassword),
|
|
75
|
+
changeEmail: change(core, getCtx, account.changeEmail),
|
|
76
|
+
linked: read(core, getCtx, account.linkedAccounts),
|
|
77
|
+
unlink: change(core, getCtx, account.unlink),
|
|
78
|
+
delete: change(core, getCtx, account.deleteAccount),
|
|
79
|
+
},
|
|
80
|
+
sessions: {
|
|
81
|
+
list: read(core, getCtx, (c, ctx) => sessions.listSessions(c, ctx)),
|
|
82
|
+
revoke: change(core, getCtx, async (c, ctx, input) => {
|
|
83
|
+
const { user } = await sessions.requireSession(c, ctx, { browser: true });
|
|
84
|
+
await c.db.query(`delete from ${c.s}.sessions where user_id = $1::uuid and id = $2`, [user.id, String(input?.id ?? "")]);
|
|
85
|
+
return { ok: true };
|
|
86
|
+
}),
|
|
87
|
+
revokeOthers: change(core, getCtx, async (c, ctx) => {
|
|
88
|
+
const { user, session } = await sessions.requireSession(c, ctx, { browser: true });
|
|
89
|
+
await sessions.deleteUserSessions(c, c.db, user.id, session.id);
|
|
90
|
+
return { ok: true };
|
|
91
|
+
}),
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
if (core.modules.twoFactor) {
|
|
95
|
+
api.twoFactor = {
|
|
96
|
+
status: read(core, getCtx, twoFactor.status),
|
|
97
|
+
setup: change(core, getCtx, twoFactor.setup),
|
|
98
|
+
enable: change(core, getCtx, twoFactor.enable),
|
|
99
|
+
disable: change(core, getCtx, twoFactor.disable),
|
|
100
|
+
regenerateRecoveryCodes: change(core, getCtx, twoFactor.regenerateRecoveryCodes),
|
|
101
|
+
verify: change(core, getCtx, twoFactor.verify),
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
if (core.modules.workspaces) {
|
|
105
|
+
api.workspaces = {
|
|
106
|
+
current: read(core, getCtx, workspaces.current),
|
|
107
|
+
list: read(core, getCtx, workspaces.list),
|
|
108
|
+
requireMember: (options) => withCtx(getCtx, async (ctx) => {
|
|
109
|
+
if (!(await sessions.readSession(core, ctx)))
|
|
110
|
+
return signInRedirect(ctx, options?.next);
|
|
111
|
+
return workspaces.requireMember(core, ctx, options);
|
|
112
|
+
}),
|
|
113
|
+
create: change(core, getCtx, workspaces.create),
|
|
114
|
+
switch: change(core, getCtx, workspaces.switchTo),
|
|
115
|
+
rename: change(core, getCtx, workspaces.rename),
|
|
116
|
+
delete: change(core, getCtx, workspaces.remove),
|
|
117
|
+
members: read(core, getCtx, workspaces.members),
|
|
118
|
+
invite: change(core, getCtx, workspaces.invite),
|
|
119
|
+
invites: read(core, getCtx, workspaces.invites),
|
|
120
|
+
revokeInvite: change(core, getCtx, workspaces.revokeInvite),
|
|
121
|
+
inviteInfo: (input) => workspaces.inviteInfo(core, input),
|
|
122
|
+
acceptInvite: change(core, getCtx, workspaces.acceptInvite),
|
|
123
|
+
setRole: change(core, getCtx, workspaces.setRole),
|
|
124
|
+
removeMember: change(core, getCtx, workspaces.removeMember),
|
|
125
|
+
leave: change(core, getCtx, workspaces.leave),
|
|
126
|
+
transferOwnership: change(core, getCtx, workspaces.transferOwnership),
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
if (core.modules.tokens) {
|
|
130
|
+
api.tokens = {
|
|
131
|
+
create: change(core, getCtx, tokens.create),
|
|
132
|
+
list: read(core, getCtx, (c, ctx) => tokens.list(c, ctx)),
|
|
133
|
+
revoke: change(core, getCtx, tokens.revoke),
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
return api;
|
|
137
|
+
}
|
|
138
|
+
async function doctor(core) {
|
|
139
|
+
const checks = [];
|
|
140
|
+
const add = (level, message) => checks.push({ level, message });
|
|
141
|
+
const production = process.env.NODE_ENV === "production";
|
|
142
|
+
const local = ["localhost", "127.0.0.1"].includes(core.url.hostname) || /\.(localhost|test)$/.test(core.url.hostname);
|
|
143
|
+
add("ok", `url ${core.origin}, routes under ${core.basePath}/*`);
|
|
144
|
+
if (!core.secure && !local)
|
|
145
|
+
add("error", "`url` must use https on a public host. Cookies are not Secure otherwise.");
|
|
146
|
+
if (core.password) {
|
|
147
|
+
add(hashRuntime ? "ok" : "error", hashRuntime ? `argon2id from ${hashRuntime === "bun" ? "Bun" : "Node"}` : `password hashing needs Bun or Node 24.7+, this is Node ${process.versions.node}`);
|
|
148
|
+
}
|
|
149
|
+
for (const method of core.config.methods) {
|
|
150
|
+
if (method.kind !== "oauth")
|
|
151
|
+
continue;
|
|
152
|
+
if (!core.oauth.has(method.id)) {
|
|
153
|
+
add("warn", `${method.id}: client ID or secret is missing, so the method is off`);
|
|
154
|
+
}
|
|
155
|
+
else {
|
|
156
|
+
add("ok", `${method.id}: add this redirect URI in the provider console: ${redirectUri(core, method.id)}`);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
if (core.password && !core.password.verifyEmail && (core.oauth.size > 0 || typeof core.config.access === "function")) {
|
|
160
|
+
add("warn", "verifyEmail is off. Anyone can sign up as any e-mail, so an allowlist by domain is not safe, and an OAuth login by the real owner takes over such accounts.");
|
|
161
|
+
}
|
|
162
|
+
if (!core.emailEnabled) {
|
|
163
|
+
add(core.config.email === false ? "ok" : "warn", "e-mail is off: sign-up with verification, password reset, e-mail change and invites answer email_unavailable.");
|
|
164
|
+
}
|
|
165
|
+
else if (!core.config.email) {
|
|
166
|
+
add("warn", "no `email` set. E-mails print to the console outside production, and are off in production.");
|
|
167
|
+
}
|
|
168
|
+
if (core.config.devLogin) {
|
|
169
|
+
add(devLoginAllowed(core) ? "warn" : "ok", devLoginAllowed(core) ? `dev login is on: ${core.basePath}/dev signs in as ${core.config.devLogin}` : "dev login is set but off here (production or public host)");
|
|
170
|
+
}
|
|
171
|
+
try {
|
|
172
|
+
const applied = await appliedMigration(core.db, core.s);
|
|
173
|
+
add(applied >= latestMigration ? "ok" : "warn", `database reachable, migration ${applied}/${latestMigration}${core.config.migrate === "manual" && applied < latestMigration ? " — run `soroi-auth migrate`" : ""}`);
|
|
174
|
+
}
|
|
175
|
+
catch (error) {
|
|
176
|
+
add("error", `database: ${error.message}`);
|
|
177
|
+
}
|
|
178
|
+
return checks;
|
|
179
|
+
}
|
|
180
|
+
export function createAuth(config) {
|
|
181
|
+
const core = createCore(config);
|
|
182
|
+
if (core.password)
|
|
183
|
+
assertHashRuntime();
|
|
184
|
+
if (core.modules.tokens)
|
|
185
|
+
core.bearer = tokens.bearer;
|
|
186
|
+
const adapter = config.framework;
|
|
187
|
+
const contexts = new WeakMap();
|
|
188
|
+
const adapterContext = async () => {
|
|
189
|
+
if (!adapter) {
|
|
190
|
+
throw new AuthConfigError("no `framework` set. Use `framework: tanstackStart()` or `framework: nextjs()`, or call `auth.withRequest(request)`.");
|
|
191
|
+
}
|
|
192
|
+
const request = await adapter.getRequest();
|
|
193
|
+
let ctx = contexts.get(request);
|
|
194
|
+
if (!ctx) {
|
|
195
|
+
ctx = createContext(core, request, (name, value, options) => adapter.setCookie(name, value, options), adapter.getIP);
|
|
196
|
+
contexts.set(request, ctx);
|
|
197
|
+
}
|
|
198
|
+
return ctx;
|
|
199
|
+
};
|
|
200
|
+
const adapterRedirect = (to) => {
|
|
201
|
+
if (adapter)
|
|
202
|
+
adapter.redirect(to);
|
|
203
|
+
throw new AuthException("not_signed_in");
|
|
204
|
+
};
|
|
205
|
+
const handler = (request) => handle(core, request);
|
|
206
|
+
const users = {
|
|
207
|
+
async create(input) {
|
|
208
|
+
const email = normalizeEmail(input.email);
|
|
209
|
+
if (!validEmail(email))
|
|
210
|
+
throw new AuthException("invalid_email");
|
|
211
|
+
const passwordHash = input.password ? await hashPassword(password.checkPassword(core, input.password)) : null;
|
|
212
|
+
return sessions.insertUser(core, { email, name: input.name ?? null, passwordHash, verified: input.emailVerified ?? true });
|
|
213
|
+
},
|
|
214
|
+
get: async (id) => strip(await sessions.getUser(core, core.db, "id", id)),
|
|
215
|
+
byEmail: async (email) => strip(await sessions.getUser(core, core.db, "email", normalizeEmail(email))),
|
|
216
|
+
async setPassword(id, value) {
|
|
217
|
+
const hash = await hashPassword(password.checkPassword(core, value));
|
|
218
|
+
await core.db.transaction(async (tx) => {
|
|
219
|
+
await tx.query(`update ${core.s}.users set password_hash = $2, updated_at = now() where id = $1::uuid`, [id, hash]);
|
|
220
|
+
await sessions.revokeAccess(core, tx, id);
|
|
221
|
+
});
|
|
222
|
+
},
|
|
223
|
+
async delete(id) {
|
|
224
|
+
await core.db.transaction(async (tx) => {
|
|
225
|
+
await sessions.revokeAccess(core, tx, id);
|
|
226
|
+
await tx.query(`delete from ${core.s}.users where id = $1::uuid`, [id]);
|
|
227
|
+
});
|
|
228
|
+
},
|
|
229
|
+
};
|
|
230
|
+
const auth = {
|
|
231
|
+
...buildApi(core, adapterContext, adapterRedirect),
|
|
232
|
+
handler,
|
|
233
|
+
routes: { GET: ({ request }) => handler(request), POST: ({ request }) => handler(request) },
|
|
234
|
+
withRequest(request) {
|
|
235
|
+
const headers = new Headers();
|
|
236
|
+
const ctx = createContext(core, request, (name, value, options) => headers.append("set-cookie", serializeCookie(name, value, options)));
|
|
237
|
+
const api = buildApi(core, async () => ctx, () => {
|
|
238
|
+
throw new AuthException("not_signed_in");
|
|
239
|
+
});
|
|
240
|
+
return { ...api, headers };
|
|
241
|
+
},
|
|
242
|
+
users,
|
|
243
|
+
migrate: () => migrate(core.db, core.s),
|
|
244
|
+
doctor: () => doctor(core),
|
|
245
|
+
settled: () => core.settled(),
|
|
246
|
+
[CORE]: core,
|
|
247
|
+
};
|
|
248
|
+
return auth;
|
|
249
|
+
}
|
|
250
|
+
function strip(user) {
|
|
251
|
+
if (!user)
|
|
252
|
+
return null;
|
|
253
|
+
const { passwordHash: _, ...rest } = user;
|
|
254
|
+
return rest;
|
|
255
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { Access, OAuthMethod, PasswordMethod } from "./types.js";
|
|
2
|
+
/** Google sign-in. Redirect URI: `<url>/auth/google/callback`. */
|
|
3
|
+
export declare function google(clientId: string | undefined, clientSecret: string | undefined, options?: {
|
|
4
|
+
scopes?: string[];
|
|
5
|
+
prompt?: string;
|
|
6
|
+
}): OAuthMethod;
|
|
7
|
+
/** GitHub sign-in. Callback URL: `<url>/auth/github/callback`. */
|
|
8
|
+
export declare function github(clientId: string | undefined, clientSecret: string | undefined, options?: {
|
|
9
|
+
scopes?: string[];
|
|
10
|
+
}): OAuthMethod;
|
|
11
|
+
export declare function password(options?: Partial<Omit<PasswordMethod, "kind">>): PasswordMethod;
|
|
12
|
+
/**
|
|
13
|
+
* Allows only the listed e-mails. An entry that starts with "@" allows a whole domain.
|
|
14
|
+
* Accepts an array or a comma-separated string, e.g. `allowlist(env.ADMIN_EMAILS)`.
|
|
15
|
+
*/
|
|
16
|
+
export declare function allowlist(entries: string | readonly string[] | undefined): Access;
|