@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.
Files changed (52) hide show
  1. package/AGENTS.md +154 -0
  2. package/LICENSE +21 -0
  3. package/README.md +26 -2
  4. package/dist/account.d.ts +52 -0
  5. package/dist/account.js +177 -0
  6. package/dist/adapters/next.d.ts +6 -0
  7. package/dist/adapters/next.js +35 -0
  8. package/dist/adapters/tanstack.d.ts +12 -0
  9. package/dist/adapters/tanstack.js +40 -0
  10. package/dist/cli.d.ts +2 -0
  11. package/dist/cli.js +76 -0
  12. package/dist/core.d.ts +122 -0
  13. package/dist/core.js +351 -0
  14. package/dist/crypto.d.ts +12 -0
  15. package/dist/crypto.js +69 -0
  16. package/dist/db.d.ts +29 -0
  17. package/dist/db.js +55 -0
  18. package/dist/email.d.ts +9 -0
  19. package/dist/email.js +64 -0
  20. package/dist/errors.d.ts +24 -0
  21. package/dist/errors.js +88 -0
  22. package/dist/index.d.ts +202 -0
  23. package/dist/index.js +255 -0
  24. package/dist/methods.d.ts +16 -0
  25. package/dist/methods.js +21 -0
  26. package/dist/migrations.d.ts +5 -0
  27. package/dist/migrations.js +154 -0
  28. package/dist/modules/oauth-server.d.ts +110 -0
  29. package/dist/modules/oauth-server.js +568 -0
  30. package/dist/modules/tokens.d.ts +31 -0
  31. package/dist/modules/tokens.js +107 -0
  32. package/dist/modules/two-factor.d.ts +41 -0
  33. package/dist/modules/two-factor.js +169 -0
  34. package/dist/modules/workspaces.d.ts +140 -0
  35. package/dist/modules/workspaces.js +297 -0
  36. package/dist/oauth/flow.d.ts +5 -0
  37. package/dist/oauth/flow.js +161 -0
  38. package/dist/oauth/providers.d.ts +29 -0
  39. package/dist/oauth/providers.js +124 -0
  40. package/dist/password-hash.d.ts +8 -0
  41. package/dist/password-hash.js +68 -0
  42. package/dist/password.d.ts +49 -0
  43. package/dist/password.js +181 -0
  44. package/dist/routes.d.ts +5 -0
  45. package/dist/routes.js +77 -0
  46. package/dist/sessions.d.ts +51 -0
  47. package/dist/sessions.js +184 -0
  48. package/dist/testing.d.ts +15 -0
  49. package/dist/testing.js +32 -0
  50. package/dist/types.d.ts +184 -0
  51. package/dist/types.js +1 -0
  52. package/package.json +75 -4
package/dist/core.d.ts ADDED
@@ -0,0 +1,122 @@
1
+ import { type Db } from "./db.js";
2
+ import type { AuthConfig, CookieOptions, OAuthMethod, OAuthProviderId, Pages, PasswordMethod, Session, Templates, User } from "./types.js";
3
+ export type SessionWithUser = {
4
+ user: User;
5
+ session: Session;
6
+ tokenScopes?: string[];
7
+ reauthAt?: Date;
8
+ };
9
+ export type RequestContext = {
10
+ request: Request;
11
+ url: URL;
12
+ ip: string | null;
13
+ userAgent: string | null;
14
+ cookie(name: string): string | undefined;
15
+ /** Resolves to false when the framework could not set the cookie here. */
16
+ setCookie(name: string, value: string, maxAge: number): Promise<boolean>;
17
+ clearCookie(name: string): void;
18
+ /** Waits for cookie writes that the framework does asynchronously (Next.js). */
19
+ flush(): Promise<void>;
20
+ cache: {
21
+ session?: Promise<SessionWithUser | null>;
22
+ };
23
+ };
24
+ export type Core = {
25
+ config: AuthConfig;
26
+ db: Db;
27
+ s: string;
28
+ url: URL;
29
+ origin: string;
30
+ appName: string;
31
+ basePath: string;
32
+ pages: Pages;
33
+ secure: boolean;
34
+ sessionDays: number;
35
+ rateLimit: boolean;
36
+ /** False when no e-mail can go out. The flows that need one are off then. */
37
+ emailEnabled: boolean;
38
+ password: PasswordMethod | undefined;
39
+ oauth: Map<OAuthProviderId, OAuthMethod>;
40
+ keys: {
41
+ state: Buffer;
42
+ totp: Buffer;
43
+ recovery: Buffer;
44
+ browser: Buffer;
45
+ };
46
+ cookies: {
47
+ session: string;
48
+ oauth: string;
49
+ challenge: string;
50
+ pending: string;
51
+ };
52
+ cookieDomain: string | undefined;
53
+ trustedOrigins: Set<string>;
54
+ roles: readonly string[];
55
+ /** Lowest role that may invite, rename and manage members. */
56
+ manageRole: string;
57
+ tokenPrefix: string;
58
+ twoFactorIssuer: string;
59
+ modules: {
60
+ twoFactor: boolean;
61
+ workspaces: boolean;
62
+ tokens: boolean;
63
+ };
64
+ /** Set by the tokens module: resolves `Authorization: Bearer` API tokens. */
65
+ bearer?: (core: Core, ctx: RequestContext) => Promise<SessionWithUser | null>;
66
+ sendEmail<K extends keyof Templates>(template: K, to: string, data: Parameters<Templates[K]>[0]): Promise<void>;
67
+ /** Runs work after the response, so its duration does not show in response times. Errors are logged. */
68
+ background(work: () => Promise<unknown>): void;
69
+ /** Resolves when all background work has finished. Used by tests and graceful shutdown. */
70
+ settled(): Promise<void>;
71
+ ready(): Promise<void>;
72
+ };
73
+ export declare function createCore(config: AuthConfig): Core;
74
+ export declare function cookieOptions(core: Core, maxAge: number): CookieOptions;
75
+ export declare function serializeCookie(name: string, value: string, options: CookieOptions): string;
76
+ export declare function createContext(core: Core, request: Request, sink: (name: string, value: string, options: CookieOptions) => void | boolean | Promise<void | boolean>, socketIp?: () => string | null): RequestContext;
77
+ /**
78
+ * Blocks state-changing calls from other sites, and state-changing calls over GET:
79
+ * SameSite=Lax cookies still go with cross-site GET links. Requests without an Origin header (server to server) pass.
80
+ */
81
+ export declare function assertSameOrigin(core: Core, ctx: RequestContext): void;
82
+ /** Fixed-window counter. Returns false when the key is over its limit. */
83
+ export declare function hit(core: Core, key: string, limit: number, windowSeconds: number): Promise<boolean>;
84
+ /** True when the key already reached its limit. Does not count. */
85
+ export declare function over(core: Core, key: string, limit: number, windowSeconds: number): Promise<boolean>;
86
+ export declare function limit(core: Core, key: string, max: number, windowSeconds: number): Promise<void>;
87
+ /** Per-IP limit. Skipped when the IP is unknown, so one shared "null" bucket cannot lock out every user. */
88
+ export declare function limitIp(core: Core, ctx: RequestContext, key: string, max: number, windowSeconds: number): Promise<void>;
89
+ /** For flows that only work through a link in an e-mail. */
90
+ export declare function requireEmail(core: Core): void;
91
+ export declare function canSignUp(core: Core, email: string): Promise<boolean>;
92
+ export declare function canSignIn(core: Core, email: string): Promise<boolean>;
93
+ export declare const normalizeEmail: (email: string) => string;
94
+ export declare const validEmail: (email: string) => boolean;
95
+ export type EmailTokenKind = "verify_email" | "reset_password" | "change_email";
96
+ export declare function issueEmailToken(core: Core, db: Db, kind: EmailTokenKind, userId: string, email: string, ttlSeconds: number, options?: {
97
+ replace?: boolean;
98
+ browser?: string | null;
99
+ }): Promise<string>;
100
+ export type EmailToken = {
101
+ userId: string;
102
+ kind: EmailTokenKind;
103
+ email: string;
104
+ browser: string | null;
105
+ };
106
+ /** Deletes the token as it reads it, so each link works once. */
107
+ export declare function consumeEmailToken(core: Core, db: Db, kinds: EmailTokenKind[], token: string): Promise<EmailToken | "invalid_token" | "link_expired">;
108
+ /** Reads a token without using it up. */
109
+ export declare function peekEmailToken(core: Core, token: string): Promise<{
110
+ userId: string;
111
+ kind: EmailTokenKind;
112
+ } | null>;
113
+ /** Accepts only paths on this site and URLs on `trustedOrigins`, so `?next=` cannot send users to other domains. */
114
+ export declare function safeNext(core: Core, next: string | null | undefined, fallback: string): string;
115
+ /**
116
+ * The page the user is on. For a server function call (TanStack Start sends `x-tsr-serverFn`)
117
+ * the request URL is the RPC endpoint, so the page comes from a same-origin Referer instead.
118
+ */
119
+ export declare function pageUrl(core: Core, ctx: RequestContext): string | null;
120
+ /** The sign-in page link. A sign-in page on another origin (a central login service) gets a full `next` URL back here. */
121
+ export declare function signInLink(core: Core, params?: Record<string, string>): string;
122
+ export declare function link(core: Core, path: string, params?: Record<string, string>): string;
package/dist/core.js ADDED
@@ -0,0 +1,351 @@
1
+ import { deriveKey, randomToken, sha256 } from "./crypto.js";
2
+ import { quoteSchema, resolveDb } from "./db.js";
3
+ import { consoleEmail, defaultTemplates, isConsoleEmail } from "./email.js";
4
+ import { AuthConfigError, AuthException } from "./errors.js";
5
+ import { migrate } from "./migrations.js";
6
+ const production = () => process.env.NODE_ENV === "production";
7
+ export function createCore(config) {
8
+ if (!config.secret || config.secret.length < 32) {
9
+ throw new AuthConfigError("`secret` must be at least 32 characters. Generate one with `openssl rand -base64 32`.");
10
+ }
11
+ let url;
12
+ try {
13
+ url = new URL(config.url);
14
+ }
15
+ catch {
16
+ throw new AuthConfigError(`\`url\` "${config.url}" is not a valid URL.`);
17
+ }
18
+ const s = quoteSchema(config.schema ?? "auth");
19
+ const basePath = (config.basePath ?? "/auth").replace(/\/+$/, "");
20
+ const secure = url.protocol === "https:";
21
+ const signIn = config.pages?.signIn ?? "/login";
22
+ const afterSignIn = config.pages?.afterSignIn ?? "/";
23
+ const pages = {
24
+ signIn,
25
+ afterSignIn,
26
+ afterSignOut: config.pages?.afterSignOut ?? "/",
27
+ error: config.pages?.error ?? signIn,
28
+ verified: config.pages?.verified ?? afterSignIn,
29
+ resetPassword: config.pages?.resetPassword ?? "/reset-password",
30
+ twoFactor: config.pages?.twoFactor ?? "/login/two-factor",
31
+ acceptInvite: config.pages?.acceptInvite ?? "/invite",
32
+ };
33
+ const password = config.methods.find((m) => m.kind === "password");
34
+ const oauth = new Map();
35
+ for (const method of config.methods) {
36
+ if (method.kind === "oauth" && method.clientId && method.clientSecret)
37
+ oauth.set(method.id, method);
38
+ }
39
+ const cookieDomain = config.cookie?.domain?.replace(/^\./, "") || undefined;
40
+ if (cookieDomain && url.hostname !== cookieDomain && !url.hostname.endsWith(`.${cookieDomain}`)) {
41
+ throw new AuthConfigError(`\`cookie.domain\` "${cookieDomain}" does not contain the host of \`url\` (${url.hostname}).`);
42
+ }
43
+ // `__Host-` cookies are bound to this exact host and cannot be set by subdomains.
44
+ // A shared cookie needs a Domain attribute, which `__Host-` forbids, so it uses `__Secure-`.
45
+ const prefix = secure ? (cookieDomain ? "__Secure-" : "__Host-") : "";
46
+ const name = config.cookie?.name ?? "auth";
47
+ const appName = config.appName ?? url.hostname;
48
+ const roles = config.workspaces?.roles ?? ["owner", "admin", "member"];
49
+ const tokenConfig = typeof config.tokens === "object" ? config.tokens : {};
50
+ const twoFactorConfig = typeof config.twoFactor === "object" ? config.twoFactor : {};
51
+ const email = config.email || undefined;
52
+ if (email && production() && isConsoleEmail(email.send)) {
53
+ throw new AuthConfigError("`consoleEmail()` prints sign-in links to the log, so it does not work in production. Use `resend()` or `email: false`.");
54
+ }
55
+ const templates = { ...defaultTemplates, ...email?.templates };
56
+ const send = email?.send ?? (production() || config.email === false ? undefined : consoleEmail());
57
+ const rawDb = resolveDb(config.db);
58
+ let migrated = config.migrate === "manual" ? Promise.resolve() : null;
59
+ const ready = () => (migrated ??= migrate(rawDb, s).then(() => undefined));
60
+ const db = {
61
+ query: async (text, params) => {
62
+ await ready();
63
+ return rawDb.query(text, params);
64
+ },
65
+ transaction: async (fn) => {
66
+ await ready();
67
+ return rawDb.transaction(fn);
68
+ },
69
+ };
70
+ const pending = new Set();
71
+ return {
72
+ config,
73
+ db,
74
+ s,
75
+ url,
76
+ origin: url.origin,
77
+ appName,
78
+ basePath,
79
+ pages,
80
+ secure,
81
+ // Browsers cap cookie lifetimes at 400 days.
82
+ sessionDays: Math.min(config.session?.days ?? 365, 400),
83
+ rateLimit: config.rateLimit ?? true,
84
+ emailEnabled: !!send,
85
+ password,
86
+ oauth,
87
+ keys: {
88
+ state: deriveKey(config.secret, "oauth-state"),
89
+ totp: deriveKey(config.secret, "totp"),
90
+ recovery: deriveKey(config.secret, "recovery-codes"),
91
+ browser: deriveKey(config.secret, "pending-browser"),
92
+ },
93
+ cookies: {
94
+ session: `${prefix}${name}_session`,
95
+ oauth: `${prefix}${name}_oauth`,
96
+ challenge: `${prefix}${name}_challenge`,
97
+ pending: `${prefix}${name}_pending`,
98
+ },
99
+ cookieDomain,
100
+ trustedOrigins: new Set([url.origin, ...(config.trustedOrigins ?? []).map((o) => new URL(o).origin)]),
101
+ roles,
102
+ manageRole: config.workspaces?.manage ?? (roles.length > 2 ? roles[1] : roles[0]),
103
+ tokenPrefix: tokenConfig.prefix ?? "sk",
104
+ twoFactorIssuer: twoFactorConfig.issuer ?? appName,
105
+ modules: { twoFactor: !!config.twoFactor, workspaces: !!config.workspaces, tokens: !!config.tokens },
106
+ ready,
107
+ async sendEmail(template, to, data) {
108
+ if (!send)
109
+ return;
110
+ const content = templates[template](data);
111
+ await send({ from: email?.from ?? `${appName} <no-reply@${url.hostname}>`, to, ...content });
112
+ },
113
+ background(work) {
114
+ const promise = Promise.resolve()
115
+ .then(work)
116
+ .catch((error) => console.error("[@soroi/auth] background task failed:", error))
117
+ .finally(() => pending.delete(promise));
118
+ pending.add(promise);
119
+ },
120
+ async settled() {
121
+ while (pending.size)
122
+ await Promise.all([...pending]);
123
+ },
124
+ };
125
+ }
126
+ export function cookieOptions(core, maxAge) {
127
+ return { httpOnly: true, secure: core.secure, sameSite: "lax", path: "/", maxAge, domain: core.cookieDomain };
128
+ }
129
+ export function serializeCookie(name, value, options) {
130
+ return [
131
+ `${name}=${encodeURIComponent(value)}`,
132
+ `Path=${options.path}`,
133
+ options.domain ? `Domain=${options.domain}` : "",
134
+ `Max-Age=${options.maxAge}`,
135
+ options.httpOnly ? "HttpOnly" : "",
136
+ options.secure ? "Secure" : "",
137
+ `SameSite=${options.sameSite === "strict" ? "Strict" : "Lax"}`,
138
+ ]
139
+ .filter(Boolean)
140
+ .join("; ");
141
+ }
142
+ function parseCookies(header) {
143
+ const map = new Map();
144
+ for (const part of (header ?? "").split(";")) {
145
+ const index = part.indexOf("=");
146
+ if (index < 1)
147
+ continue;
148
+ const key = part.slice(0, index).trim();
149
+ if (map.has(key))
150
+ continue;
151
+ try {
152
+ map.set(key, decodeURIComponent(part.slice(index + 1).trim()));
153
+ }
154
+ catch {
155
+ // A malformed cookie is ignored like a missing one.
156
+ }
157
+ }
158
+ return map;
159
+ }
160
+ function forwardedIp(request) {
161
+ // The last entry is the one the nearest proxy added. Earlier entries come from the client and can be forged.
162
+ const forwarded = request.headers.get("x-forwarded-for");
163
+ if (forwarded)
164
+ return forwarded.split(",").at(-1).trim() || null;
165
+ return request.headers.get("x-real-ip");
166
+ }
167
+ let warnedNoIp = false;
168
+ export function createContext(core, request, sink, socketIp) {
169
+ const jar = parseCookies(request.headers.get("cookie"));
170
+ const writes = [];
171
+ const write = (result) => {
172
+ const done = Promise.resolve(result).then((value) => value !== false);
173
+ writes.push(done);
174
+ return done;
175
+ };
176
+ const ip = core.config.ip ? core.config.ip(request) : (forwardedIp(request) ?? socketIp?.() ?? null);
177
+ if (!ip && !warnedNoIp && production()) {
178
+ warnedNoIp = true;
179
+ console.warn("[@soroi/auth] no client IP on a request, so per-IP rate limits are off. Set `ip` in the config.");
180
+ }
181
+ return {
182
+ request,
183
+ url: new URL(request.url),
184
+ ip,
185
+ userAgent: request.headers.get("user-agent"),
186
+ cookie: (name) => jar.get(name) || undefined,
187
+ setCookie(name, value, maxAge) {
188
+ jar.set(name, value);
189
+ return write(sink(name, value, cookieOptions(core, maxAge)));
190
+ },
191
+ clearCookie(name) {
192
+ jar.delete(name);
193
+ void write(sink(name, "", cookieOptions(core, 0)));
194
+ },
195
+ async flush() {
196
+ while (writes.length)
197
+ await Promise.all(writes.splice(0));
198
+ },
199
+ cache: {},
200
+ };
201
+ }
202
+ /**
203
+ * Blocks state-changing calls from other sites, and state-changing calls over GET:
204
+ * SameSite=Lax cookies still go with cross-site GET links. Requests without an Origin header (server to server) pass.
205
+ */
206
+ export function assertSameOrigin(core, ctx) {
207
+ const method = ctx.request.method.toUpperCase();
208
+ if (method === "GET" || method === "HEAD")
209
+ throw new AuthException("forbidden_origin");
210
+ if (ctx.request.headers.get("sec-fetch-site") === "cross-site")
211
+ throw new AuthException("forbidden_origin");
212
+ const origin = ctx.request.headers.get("origin");
213
+ if (origin === "null" || (origin && !core.trustedOrigins.has(origin)))
214
+ throw new AuthException("forbidden_origin");
215
+ }
216
+ /** Fixed-window counter. Returns false when the key is over its limit. */
217
+ export async function hit(core, key, limit, windowSeconds) {
218
+ if (!core.rateLimit)
219
+ return true;
220
+ const [row] = await core.db.query(`insert into ${core.s}.rate_limits as r (key, window_start, count) values ($1, now(), 1)
221
+ on conflict (key) do update set
222
+ count = case when r.window_start < now() - make_interval(secs => $2::int) then 1 else r.count + 1 end,
223
+ window_start = case when r.window_start < now() - make_interval(secs => $2::int) then now() else r.window_start end
224
+ returning count`, [sha256(key), windowSeconds]);
225
+ if (Math.random() < 0.01) {
226
+ await core.db.query(`delete from ${core.s}.rate_limits where window_start < now() - interval '1 day'`);
227
+ }
228
+ return Number(row?.count ?? 0) <= limit;
229
+ }
230
+ /** True when the key already reached its limit. Does not count. */
231
+ export async function over(core, key, limit, windowSeconds) {
232
+ if (!core.rateLimit)
233
+ return false;
234
+ const [row] = await core.db.query(`select count from ${core.s}.rate_limits where key = $1 and window_start >= now() - make_interval(secs => $2::int)`, [sha256(key), windowSeconds]);
235
+ return Number(row?.count ?? 0) >= limit;
236
+ }
237
+ export async function limit(core, key, max, windowSeconds) {
238
+ if (!(await hit(core, key, max, windowSeconds)))
239
+ throw new AuthException("rate_limited");
240
+ }
241
+ /** Per-IP limit. Skipped when the IP is unknown, so one shared "null" bucket cannot lock out every user. */
242
+ export async function limitIp(core, ctx, key, max, windowSeconds) {
243
+ if (ctx.ip)
244
+ await limit(core, `${key}:ip:${ctx.ip}`, max, windowSeconds);
245
+ }
246
+ /** For flows that only work through a link in an e-mail. */
247
+ export function requireEmail(core) {
248
+ if (!core.emailEnabled)
249
+ throw new AuthException("email_unavailable");
250
+ }
251
+ export async function canSignUp(core, email) {
252
+ const access = core.config.access ?? "open";
253
+ if (access === "open")
254
+ return true;
255
+ if (access === "closed")
256
+ return false;
257
+ return access(email);
258
+ }
259
+ export async function canSignIn(core, email) {
260
+ const access = core.config.access ?? "open";
261
+ if (typeof access === "string")
262
+ return true;
263
+ return access(email);
264
+ }
265
+ export const normalizeEmail = (email) => email.trim().toLowerCase();
266
+ export const validEmail = (email) => email.length <= 254 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
267
+ export async function issueEmailToken(core, db, kind, userId, email, ttlSeconds, options = {}) {
268
+ const token = randomToken();
269
+ if (options.replace ?? true) {
270
+ await db.query(`delete from ${core.s}.email_tokens where user_id = $1::uuid and kind = $2`, [userId, kind]);
271
+ }
272
+ await db.query(`insert into ${core.s}.email_tokens (id, kind, user_id, email, browser, expires_at)
273
+ values ($1, $2, $3::uuid, $4, $5, now() + make_interval(secs => $6::int))`, [sha256(token), kind, userId, email, options.browser ?? null, ttlSeconds]);
274
+ return token;
275
+ }
276
+ /** Deletes the token as it reads it, so each link works once. */
277
+ export async function consumeEmailToken(core, db, kinds, token) {
278
+ if (!token || token.length > 200)
279
+ return "invalid_token";
280
+ const [row] = await db.query(`delete from ${core.s}.email_tokens where id = $1 and kind in ($2, $3)
281
+ returning user_id::text, kind, email, browser, expires_at < now() as expired`, [sha256(token), kinds[0], kinds[1] ?? kinds[0]]);
282
+ if (!row)
283
+ return "invalid_token";
284
+ if (row.expired)
285
+ return "link_expired";
286
+ return { userId: row.user_id, kind: row.kind, email: row.email, browser: row.browser };
287
+ }
288
+ /** Reads a token without using it up. */
289
+ export async function peekEmailToken(core, token) {
290
+ if (!token || token.length > 200)
291
+ return null;
292
+ const [row] = await core.db.query(`select user_id::text, kind from ${core.s}.email_tokens where id = $1`, [sha256(token)]);
293
+ return row ? { userId: row.user_id, kind: row.kind } : null;
294
+ }
295
+ function relativePath(next) {
296
+ // Browsers drop tabs and newlines and read "\" as "/", so "/\t/evil.com" would become "//evil.com".
297
+ if (/[\u0000-\u001f\\]/.test(next))
298
+ return null;
299
+ if (!next.startsWith("/") || next.startsWith("//"))
300
+ return null;
301
+ // TanStack Start's server function endpoint is not a page.
302
+ if (next.startsWith("/_serverFn"))
303
+ return null;
304
+ return next;
305
+ }
306
+ /** Accepts only paths on this site and URLs on `trustedOrigins`, so `?next=` cannot send users to other domains. */
307
+ export function safeNext(core, next, fallback) {
308
+ if (!next || next.length > 2000)
309
+ return fallback;
310
+ const direct = relativePath(next);
311
+ if (direct)
312
+ return direct;
313
+ try {
314
+ const parsed = new URL(next);
315
+ // "https://app//evil.com/x" has the right origin but the path "//evil.com/x".
316
+ const path = relativePath(`${parsed.pathname}${parsed.search}${parsed.hash}`);
317
+ if (parsed.origin === core.origin)
318
+ return path ?? fallback;
319
+ // Another app of the same suite, e.g. the login service sending the user back to the app they came from.
320
+ if (path && core.trustedOrigins.has(parsed.origin))
321
+ return `${parsed.origin}${path}`;
322
+ }
323
+ catch {
324
+ // Not a URL.
325
+ }
326
+ return fallback;
327
+ }
328
+ /**
329
+ * The page the user is on. For a server function call (TanStack Start sends `x-tsr-serverFn`)
330
+ * the request URL is the RPC endpoint, so the page comes from a same-origin Referer instead.
331
+ */
332
+ export function pageUrl(core, ctx) {
333
+ // TanStack Start server functions and Next.js server actions both run at a URL that is not the page.
334
+ const isServerFn = ctx.request.headers.has("x-tsr-serverfn") || ctx.request.headers.has("next-action") || ctx.url.pathname.startsWith("/_serverFn");
335
+ if (!isServerFn)
336
+ return safeNext(core, `${ctx.url.pathname}${ctx.url.search}`, "") || null;
337
+ const referer = ctx.request.headers.get("referer");
338
+ return referer ? safeNext(core, referer, "") || null : null;
339
+ }
340
+ /** The sign-in page link. A sign-in page on another origin (a central login service) gets a full `next` URL back here. */
341
+ export function signInLink(core, params = {}) {
342
+ const external = new URL(core.pages.signIn, core.url).origin !== core.origin;
343
+ const next = params.next && external && params.next.startsWith("/") ? `${core.origin}${params.next}` : params.next;
344
+ return link(core, core.pages.signIn, next ? { ...params, next } : params);
345
+ }
346
+ export function link(core, path, params = {}) {
347
+ const target = new URL(path, core.url);
348
+ for (const [key, value] of Object.entries(params))
349
+ target.searchParams.set(key, value);
350
+ return target.toString();
351
+ }
@@ -0,0 +1,12 @@
1
+ export declare const randomToken: (bytes?: number) => string;
2
+ export declare const sha256: (value: string) => string;
3
+ export declare const sha256Base64Url: (value: string) => string;
4
+ export declare function safeEqual(a: string, b: string): boolean;
5
+ /** One key per purpose, so a leak of one derived key does not expose the others. */
6
+ export declare function deriveKey(secret: string, purpose: string): Buffer;
7
+ export declare const hmac: (key: Buffer, data: string) => string;
8
+ /** AES-256-GCM. Output: base64url(iv | tag | ciphertext). */
9
+ export declare function seal(key: Buffer, plaintext: string): string;
10
+ export declare function unseal(key: Buffer, sealed: string): string | null;
11
+ export declare function base32Encode(bytes: Uint8Array): string;
12
+ export declare function base32Decode(input: string): Buffer;
package/dist/crypto.js ADDED
@@ -0,0 +1,69 @@
1
+ import { createCipheriv, createDecipheriv, createHash, createHmac, hkdfSync, randomBytes, timingSafeEqual, } from "node:crypto";
2
+ export const randomToken = (bytes = 32) => randomBytes(bytes).toString("base64url");
3
+ export const sha256 = (value) => createHash("sha256").update(value).digest("hex");
4
+ export const sha256Base64Url = (value) => createHash("sha256").update(value).digest("base64url");
5
+ export function safeEqual(a, b) {
6
+ const left = Buffer.from(a);
7
+ const right = Buffer.from(b);
8
+ return left.length === right.length && timingSafeEqual(left, right);
9
+ }
10
+ /** One key per purpose, so a leak of one derived key does not expose the others. */
11
+ export function deriveKey(secret, purpose) {
12
+ return Buffer.from(hkdfSync("sha256", secret, "", `soroi-auth:${purpose}`, 32));
13
+ }
14
+ export const hmac = (key, data) => createHmac("sha256", key).update(data).digest("base64url");
15
+ /** AES-256-GCM. Output: base64url(iv | tag | ciphertext). */
16
+ export function seal(key, plaintext) {
17
+ const iv = randomBytes(12);
18
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
19
+ const body = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
20
+ return Buffer.concat([iv, cipher.getAuthTag(), body]).toString("base64url");
21
+ }
22
+ export function unseal(key, sealed) {
23
+ try {
24
+ const raw = Buffer.from(sealed, "base64url");
25
+ if (raw.length < 29)
26
+ return null;
27
+ const decipher = createDecipheriv("aes-256-gcm", key, raw.subarray(0, 12));
28
+ decipher.setAuthTag(raw.subarray(12, 28));
29
+ return Buffer.concat([decipher.update(raw.subarray(28)), decipher.final()]).toString("utf8");
30
+ }
31
+ catch {
32
+ return null;
33
+ }
34
+ }
35
+ const BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
36
+ export function base32Encode(bytes) {
37
+ let bits = 0;
38
+ let value = 0;
39
+ let out = "";
40
+ for (const byte of bytes) {
41
+ value = (value << 8) | byte;
42
+ bits += 8;
43
+ while (bits >= 5) {
44
+ out += BASE32[(value >>> (bits - 5)) & 31];
45
+ bits -= 5;
46
+ }
47
+ }
48
+ if (bits > 0)
49
+ out += BASE32[(value << (5 - bits)) & 31];
50
+ return out;
51
+ }
52
+ export function base32Decode(input) {
53
+ const clean = input.toUpperCase().replace(/=+$/, "").replace(/\s/g, "");
54
+ let bits = 0;
55
+ let value = 0;
56
+ const out = [];
57
+ for (const char of clean) {
58
+ const index = BASE32.indexOf(char);
59
+ if (index === -1)
60
+ throw new Error("invalid base32");
61
+ value = (value << 5) | index;
62
+ bits += 5;
63
+ if (bits >= 8) {
64
+ out.push((value >>> (bits - 8)) & 255);
65
+ bits -= 8;
66
+ }
67
+ }
68
+ return Buffer.from(out);
69
+ }
package/dist/db.d.ts ADDED
@@ -0,0 +1,29 @@
1
+ export type Row = Record<string, unknown>;
2
+ /** The only thing the package needs from the app's database driver. Placeholders are `$1`, `$2`, … */
3
+ export interface Db {
4
+ query<T extends Row = Row>(sql: string, params?: unknown[]): Promise<T[]>;
5
+ transaction<T>(fn: (tx: Db) => Promise<T>): Promise<T>;
6
+ }
7
+ type BunSqlLike = {
8
+ unsafe(sql: string, params?: unknown[]): Promise<unknown>;
9
+ begin<T>(fn: (tx: BunSqlLike) => Promise<T>): Promise<T>;
10
+ };
11
+ /** Bun's built-in Postgres client: `bunSql(new Bun.SQL(url))` or `bunSql(Bun.sql)`. */
12
+ export declare function bunSql(sql: BunSqlLike): Db;
13
+ /** postgres.js: `postgresJs(postgres(url))`. */
14
+ export declare const postgresJs: (sql: BunSqlLike) => Db;
15
+ type PgQueryable = {
16
+ query(text: string, values?: unknown[]): Promise<{
17
+ rows: unknown[];
18
+ }>;
19
+ };
20
+ type PgPoolLike = PgQueryable & {
21
+ connect(): Promise<PgQueryable & {
22
+ release(): void;
23
+ }>;
24
+ };
25
+ /** node-postgres: `pg(new Pool({ connectionString }))`. Drizzle apps can pass `db.$client`. */
26
+ export declare function pg(pool: PgPoolLike | PgQueryable): Db;
27
+ export declare function resolveDb(db: Db | string): Db;
28
+ export declare function quoteSchema(schema: string): string;
29
+ export {};
package/dist/db.js ADDED
@@ -0,0 +1,55 @@
1
+ import { AuthConfigError } from "./errors.js";
2
+ const asRows = (value) => Array.from(value);
3
+ function flat(db) {
4
+ const self = { query: db.query, transaction: (fn) => fn(self) };
5
+ return self;
6
+ }
7
+ /** Bun's built-in Postgres client: `bunSql(new Bun.SQL(url))` or `bunSql(Bun.sql)`. */
8
+ export function bunSql(sql) {
9
+ return {
10
+ query: async (text, params = []) => asRows(await sql.unsafe(text, params)),
11
+ transaction: (fn) => sql.begin((tx) => fn(flat({ query: async (text, params = []) => asRows(await tx.unsafe(text, params)) }))),
12
+ };
13
+ }
14
+ /** postgres.js: `postgresJs(postgres(url))`. */
15
+ export const postgresJs = (sql) => bunSql(sql);
16
+ /** node-postgres: `pg(new Pool({ connectionString }))`. Drizzle apps can pass `db.$client`. */
17
+ export function pg(pool) {
18
+ const query = async (client, text, params = []) => (await client.query(text, params)).rows;
19
+ return {
20
+ query: (text, params) => query(pool, text, params),
21
+ async transaction(fn) {
22
+ const hasPool = "connect" in pool;
23
+ const client = hasPool ? await pool.connect() : pool;
24
+ try {
25
+ await client.query("begin");
26
+ const result = await fn(flat({ query: (text, params) => query(client, text, params) }));
27
+ await client.query("commit");
28
+ return result;
29
+ }
30
+ catch (error) {
31
+ await client.query("rollback");
32
+ throw error;
33
+ }
34
+ finally {
35
+ if (hasPool)
36
+ client.release();
37
+ }
38
+ },
39
+ };
40
+ }
41
+ export function resolveDb(db) {
42
+ if (typeof db !== "string")
43
+ return db;
44
+ const bun = globalThis.Bun;
45
+ if (!bun) {
46
+ throw new AuthConfigError("a database URL works only on Bun. On Node, pass your driver: `db: pg(pool)` or `db: postgresJs(sql)`.");
47
+ }
48
+ return bunSql(new bun.SQL(db));
49
+ }
50
+ export function quoteSchema(schema) {
51
+ if (!/^[a-z_][a-z0-9_]{0,62}$/.test(schema)) {
52
+ throw new AuthConfigError(`schema "${schema}" must be lower case letters, digits and _.`);
53
+ }
54
+ return `"${schema}"`;
55
+ }
@@ -0,0 +1,9 @@
1
+ import type { EmailConfig, EmailMessage, TemplateData, Templates } from "./types.js";
2
+ /** Sends through Resend's HTTP API. */
3
+ export declare function resend(apiKey: string | undefined): EmailConfig["send"];
4
+ declare const CONSOLE: unique symbol;
5
+ /** Prints e-mails, links included, to the console. The default outside production. `createAuth` refuses it in production. */
6
+ export declare function consoleEmail(): EmailConfig["send"];
7
+ export declare const isConsoleEmail: (send: EmailConfig["send"]) => send is ((message: EmailMessage) => Promise<void>) & Record<typeof CONSOLE, unknown>;
8
+ export declare const defaultTemplates: Templates;
9
+ export type { TemplateData };