@oks-page/auth 0.0.0-stage → 0.1.0-beta.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/LICENSE +21 -0
- package/README.md +6 -2
- package/dist/account-limit.d.ts +32 -0
- package/dist/account-limit.js +62 -0
- package/dist/capabilities.d.ts +13 -0
- package/dist/capabilities.js +31 -0
- package/dist/client-ip.d.ts +5 -0
- package/dist/client-ip.js +55 -0
- package/dist/create-auth.d.ts +123 -0
- package/dist/create-auth.js +441 -0
- package/dist/devices.d.ts +18 -0
- package/dist/devices.js +61 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/passkey-client.d.ts +1 -0
- package/dist/passkey-client.js +3 -0
- package/dist/testing.d.ts +21 -0
- package/dist/testing.js +82 -0
- package/package.json +48 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 OKS-ORG
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @oks-page/auth
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Login, sessions, roles and capabilities.
|
|
4
|
+
|
|
5
|
+
This is a building block of [oks-page](https://github.com/OKS-ORG/oks-page). Most people do not install it directly: start a site with `npm create oks-page@beta my-site` and it comes along.
|
|
6
|
+
|
|
7
|
+
Licence: MIT.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { SqlRunner } from "@oks-page/db";
|
|
2
|
+
export interface AccountLimitConfig {
|
|
3
|
+
/** Wrong tries before the first cool-down. */
|
|
4
|
+
freeTries: number;
|
|
5
|
+
firstCooldownMs: number;
|
|
6
|
+
maxCooldownMs: number;
|
|
7
|
+
/** The count starts again after this long without a try. */
|
|
8
|
+
resetAfterMs: number;
|
|
9
|
+
}
|
|
10
|
+
export declare const DEFAULT_ACCOUNT_LIMIT: AccountLimitConfig;
|
|
11
|
+
export type AttemptResult = {
|
|
12
|
+
allowed: true;
|
|
13
|
+
} | {
|
|
14
|
+
allowed: false;
|
|
15
|
+
retryAfterMs: number;
|
|
16
|
+
};
|
|
17
|
+
export declare const accountKey: (email: string) => string;
|
|
18
|
+
export declare function cooldownMs(count: number, c: AccountLimitConfig): number;
|
|
19
|
+
export declare function createAccountLimiter(db: SqlRunner, config?: AccountLimitConfig, clock?: () => number): {
|
|
20
|
+
/** Count one sign-in attempt for this account, or refuse it. Call before checking the password. */
|
|
21
|
+
attempt(email: string): Promise<AttemptResult>;
|
|
22
|
+
/** A correct password: the account starts clean. */
|
|
23
|
+
succeeded(email: string): Promise<void>;
|
|
24
|
+
/** What an administrator's "unlock" does. Returns whether there was anything to clear. */
|
|
25
|
+
clear(email: string): Promise<boolean>;
|
|
26
|
+
/** Seconds still to wait, for the admin screen; 0 when the account is free. */
|
|
27
|
+
status(email: string): Promise<{
|
|
28
|
+
count: number;
|
|
29
|
+
retryAfterMs: number;
|
|
30
|
+
}>;
|
|
31
|
+
};
|
|
32
|
+
export type AccountLimiter = ReturnType<typeof createAccountLimiter>;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { newId } from "@oks-page/db";
|
|
2
|
+
export const DEFAULT_ACCOUNT_LIMIT = {
|
|
3
|
+
freeTries: 5,
|
|
4
|
+
firstCooldownMs: 60_000,
|
|
5
|
+
maxCooldownMs: 3_600_000,
|
|
6
|
+
resetAfterMs: 15 * 60_000,
|
|
7
|
+
};
|
|
8
|
+
export const accountKey = (email) => `acct|${email.trim().toLowerCase()}`;
|
|
9
|
+
export function cooldownMs(count, c) {
|
|
10
|
+
if (count < c.freeTries)
|
|
11
|
+
return 0;
|
|
12
|
+
return Math.min(c.firstCooldownMs * 2 ** (count - c.freeTries), c.maxCooldownMs);
|
|
13
|
+
}
|
|
14
|
+
export function createAccountLimiter(db, config = DEFAULT_ACCOUNT_LIMIT, clock = Date.now) {
|
|
15
|
+
return {
|
|
16
|
+
/** Count one sign-in attempt for this account, or refuse it. Call before checking the password. */
|
|
17
|
+
async attempt(email) {
|
|
18
|
+
const key = accountKey(email);
|
|
19
|
+
return db.transaction(async (tx) => {
|
|
20
|
+
const forUpdate = tx.dialect === "postgres" ? " for update" : "";
|
|
21
|
+
// Make sure the row exists, so "for update" has a row to hold. A new row is an empty count.
|
|
22
|
+
await tx.all(`insert into "rate_limits" ("id", "key", "count", "last_request_ms") values (?, ?, 0, 0) on conflict ("key") do nothing`, [newId(), key]);
|
|
23
|
+
const row = (await tx.all(`select "count", "last_request_ms" from "rate_limits" where "key" = ?${forUpdate}`, [key]))[0];
|
|
24
|
+
const now = clock();
|
|
25
|
+
let count = Number(row["count"]);
|
|
26
|
+
const last = Number(row["last_request_ms"]);
|
|
27
|
+
const wait = cooldownMs(count, config);
|
|
28
|
+
if (count > 0 && now < last + wait)
|
|
29
|
+
return { allowed: false, retryAfterMs: last + wait - now };
|
|
30
|
+
// The 15 minutes count from the end of the cool-down, so a long cool-down cannot clear itself.
|
|
31
|
+
if (count > 0 && now - (last + wait) > config.resetAfterMs)
|
|
32
|
+
count = 0;
|
|
33
|
+
await tx.all(`update "rate_limits" set "count" = ?, "last_request_ms" = ? where "key" = ?`, [count + 1, now, key]);
|
|
34
|
+
return { allowed: true };
|
|
35
|
+
});
|
|
36
|
+
},
|
|
37
|
+
/** A correct password: the account starts clean. */
|
|
38
|
+
async succeeded(email) {
|
|
39
|
+
await db.all(`delete from "rate_limits" where "key" = ?`, [accountKey(email)]);
|
|
40
|
+
},
|
|
41
|
+
/** What an administrator's "unlock" does. Returns whether there was anything to clear. */
|
|
42
|
+
async clear(email) {
|
|
43
|
+
const rows = await db.all(`delete from "rate_limits" where "key" = ? returning "key"`, [
|
|
44
|
+
accountKey(email),
|
|
45
|
+
]);
|
|
46
|
+
return rows.length > 0;
|
|
47
|
+
},
|
|
48
|
+
/** Seconds still to wait, for the admin screen; 0 when the account is free. */
|
|
49
|
+
async status(email) {
|
|
50
|
+
const row = (await db.all(`select "count", "last_request_ms" from "rate_limits" where "key" = ?`, [
|
|
51
|
+
accountKey(email),
|
|
52
|
+
]))[0];
|
|
53
|
+
if (!row)
|
|
54
|
+
return { count: 0, retryAfterMs: 0 };
|
|
55
|
+
const count = Number(row["count"]);
|
|
56
|
+
return {
|
|
57
|
+
count,
|
|
58
|
+
retryAfterMs: Math.max(0, Number(row["last_request_ms"]) + cooldownMs(count, config) - clock()),
|
|
59
|
+
};
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** The one database call this needs. Every `SqlRunner` from `@oks-page/db` fits. */
|
|
2
|
+
export interface CapabilityRunner {
|
|
3
|
+
all(sql: string, params?: unknown[]): Promise<Record<string, unknown>[]>;
|
|
4
|
+
}
|
|
5
|
+
export interface UserCapabilities {
|
|
6
|
+
userId: string;
|
|
7
|
+
/** True when the person has `capability` for every content type, or for `typeKey` when the role limits it to some
|
|
8
|
+
* types. Someone who is not a member of the site has none. */
|
|
9
|
+
can(capability: string, typeKey?: string): boolean;
|
|
10
|
+
}
|
|
11
|
+
/** The role key that has every capability, including ones added later by plugins (spec 02, section 6). */
|
|
12
|
+
export declare const ADMINISTRATOR_ROLE = "administrator";
|
|
13
|
+
export declare function capabilitiesOf(runner: CapabilityRunner, siteId: string, userId: string): Promise<UserCapabilities>;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// What a person may do on a site (spec 02, section 6): the capabilities of their role there. A plugin acting for that
|
|
2
|
+
// person may do an action only if this allows it too (spec 02, section 8, rule 1; PL-38).
|
|
3
|
+
/** The role key that has every capability, including ones added later by plugins (spec 02, section 6). */
|
|
4
|
+
export const ADMINISTRATOR_ROLE = "administrator";
|
|
5
|
+
export async function capabilitiesOf(runner, siteId, userId) {
|
|
6
|
+
const rows = await runner.all(`select r."key" as role_key, c."capability" as capability, c."scope_type_key" as scope
|
|
7
|
+
from "site_members" m
|
|
8
|
+
join "roles" r on r."id" = m."role_id"
|
|
9
|
+
left join "role_capabilities" c on c."role_id" = r."id"
|
|
10
|
+
where m."site_id" = ? and m."user_id" = ?`, [siteId, userId]);
|
|
11
|
+
const administrator = rows.some((r) => r["role_key"] === ADMINISTRATOR_ROLE);
|
|
12
|
+
// A capability with no scope is for every content type; a scoped one only for the types it names.
|
|
13
|
+
const everywhere = new Set();
|
|
14
|
+
const forTypes = new Map();
|
|
15
|
+
for (const r of rows) {
|
|
16
|
+
if (r["capability"] == null)
|
|
17
|
+
continue;
|
|
18
|
+
const capability = String(r["capability"]);
|
|
19
|
+
const scope = String(r["scope"] ?? "");
|
|
20
|
+
if (scope === "")
|
|
21
|
+
everywhere.add(capability);
|
|
22
|
+
else
|
|
23
|
+
forTypes.set(capability, (forTypes.get(capability) ?? new Set()).add(scope));
|
|
24
|
+
}
|
|
25
|
+
return {
|
|
26
|
+
userId,
|
|
27
|
+
can: (capability, typeKey) => administrator ||
|
|
28
|
+
everywhere.has(capability) ||
|
|
29
|
+
(typeKey !== undefined && (forTypes.get(capability)?.has(typeKey) ?? false)),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export type TrustedProxies = readonly string[];
|
|
2
|
+
/** Turn "::ffff:10.0.0.1" into "10.0.0.1" so one address has one spelling. */
|
|
3
|
+
export declare function normaliseAddress(address: string): string;
|
|
4
|
+
export declare const UNKNOWN_CLIENT = "unknown";
|
|
5
|
+
export declare function clientAddress(forwardedFor: string | null, remoteAddress: string | undefined, trusted?: TrustedProxies): string;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// The real client address, for rate limits (spec 02, section 5, rule 4; AU-39).
|
|
2
|
+
//
|
|
3
|
+
// Forwarding headers can be written by anyone. They are believed only when the connection comes from a
|
|
4
|
+
// proxy the owner listed. Then the address is the first one, counting from the right of `X-Forwarded-For`,
|
|
5
|
+
// that is not a trusted proxy itself. Entries further left are what the client claimed, and are ignored.
|
|
6
|
+
import { BlockList, isIP } from "node:net";
|
|
7
|
+
function blockList(trusted) {
|
|
8
|
+
const list = new BlockList();
|
|
9
|
+
for (const entry of trusted) {
|
|
10
|
+
const [address, prefix] = entry.split("/");
|
|
11
|
+
const family = isIP(address);
|
|
12
|
+
if (!family)
|
|
13
|
+
throw new Error(`Not an IP address or range: "${entry}"`);
|
|
14
|
+
const type = family === 4 ? "ipv4" : "ipv6";
|
|
15
|
+
if (prefix === undefined)
|
|
16
|
+
list.addAddress(address, type);
|
|
17
|
+
else
|
|
18
|
+
list.addSubnet(address, Number(prefix), type);
|
|
19
|
+
}
|
|
20
|
+
return list;
|
|
21
|
+
}
|
|
22
|
+
/** Turn "::ffff:10.0.0.1" into "10.0.0.1" so one address has one spelling. */
|
|
23
|
+
export function normaliseAddress(address) {
|
|
24
|
+
const a = address.trim();
|
|
25
|
+
const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(a);
|
|
26
|
+
return mapped ? mapped[1] : a.toLowerCase();
|
|
27
|
+
}
|
|
28
|
+
export const UNKNOWN_CLIENT = "unknown";
|
|
29
|
+
export function clientAddress(forwardedFor, remoteAddress, trusted = []) {
|
|
30
|
+
const remote = remoteAddress ? normaliseAddress(remoteAddress) : undefined;
|
|
31
|
+
if (!remote)
|
|
32
|
+
return UNKNOWN_CLIENT;
|
|
33
|
+
if (trusted.length === 0)
|
|
34
|
+
return remote;
|
|
35
|
+
const list = blockList(trusted);
|
|
36
|
+
const isTrusted = (a) => {
|
|
37
|
+
const family = isIP(a);
|
|
38
|
+
return family !== 0 && list.check(a, family === 4 ? "ipv4" : "ipv6");
|
|
39
|
+
};
|
|
40
|
+
// The connection must come from a trusted proxy, or the header is just what the sender wrote.
|
|
41
|
+
if (!isTrusted(remote))
|
|
42
|
+
return remote;
|
|
43
|
+
const chain = (forwardedFor ?? "")
|
|
44
|
+
.split(",")
|
|
45
|
+
.map((s) => normaliseAddress(s))
|
|
46
|
+
.filter(Boolean);
|
|
47
|
+
for (let i = chain.length - 1; i >= 0; i--) {
|
|
48
|
+
const a = chain[i];
|
|
49
|
+
if (isIP(a) === 0)
|
|
50
|
+
return remote; // a malformed entry: do not guess
|
|
51
|
+
if (!isTrusted(a))
|
|
52
|
+
return a;
|
|
53
|
+
}
|
|
54
|
+
return remote;
|
|
55
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { type SqlRunner } from "@oks-page/db";
|
|
2
|
+
import { createAccountLimiter, type AccountLimitConfig } from "./account-limit.js";
|
|
3
|
+
import { type TrustedProxies } from "./client-ip.js";
|
|
4
|
+
export interface CreateAuthOptions {
|
|
5
|
+
/** A Drizzle client for the database. */
|
|
6
|
+
db: unknown;
|
|
7
|
+
/** The same database as a runner, for the per-account limit. */
|
|
8
|
+
runner: SqlRunner;
|
|
9
|
+
/** The site's secret key. At least 32 characters. */
|
|
10
|
+
secret: string;
|
|
11
|
+
/** The public address of the site, for example https://example.com. Decides whether cookies are `Secure`. */
|
|
12
|
+
baseUrl: string;
|
|
13
|
+
/** Other addresses that may send sign-in requests from a browser. */
|
|
14
|
+
trustedOrigins?: string[];
|
|
15
|
+
/** Reverse proxies whose forwarding headers may be believed (addresses or ranges such as 10.0.0.0/8). */
|
|
16
|
+
trustedProxies?: TrustedProxies;
|
|
17
|
+
passwordMinLength?: number;
|
|
18
|
+
/** Passkeys need the site's domain. Leave out to switch them off. */
|
|
19
|
+
passkey?: {
|
|
20
|
+
rpID: string;
|
|
21
|
+
rpName: string;
|
|
22
|
+
origin: string;
|
|
23
|
+
};
|
|
24
|
+
accountLimit?: AccountLimitConfig;
|
|
25
|
+
/** Sign-in tries per address in the window (the library's own limit, kept in the database). */
|
|
26
|
+
addressLimit?: {
|
|
27
|
+
window: number;
|
|
28
|
+
max: number;
|
|
29
|
+
};
|
|
30
|
+
/** For tests: the time used by the per-account limit. */
|
|
31
|
+
clock?: () => number;
|
|
32
|
+
/**
|
|
33
|
+
* Sends the password reset link (spec 13). Without it, password reset is off. It is called only for an address that
|
|
34
|
+
* has an account; the answer to the person is the same either way.
|
|
35
|
+
*/
|
|
36
|
+
sendResetPassword?: (data: AccountPerson & {
|
|
37
|
+
token: string;
|
|
38
|
+
}) => Promise<void>;
|
|
39
|
+
/** Told after a password, two-factor or email change, for the security email (spec 13, section 5). For an email
|
|
40
|
+
* change it is told twice, once for each address, with the old and the new one. */
|
|
41
|
+
onAccountChange?: (data: AccountPerson & {
|
|
42
|
+
change: AccountChange;
|
|
43
|
+
previous?: string;
|
|
44
|
+
address?: string;
|
|
45
|
+
}) => Promise<void>;
|
|
46
|
+
/**
|
|
47
|
+
* Sends a link about an email address (spec 13): confirm it, confirm a change from the old address, or confirm the
|
|
48
|
+
* new one. Without it, confirming and changing an address are off.
|
|
49
|
+
*/
|
|
50
|
+
sendAddressLink?: (data: AccountPerson & {
|
|
51
|
+
kind: AddressLinkKind;
|
|
52
|
+
url: string;
|
|
53
|
+
address?: string;
|
|
54
|
+
}) => Promise<void>;
|
|
55
|
+
/** Whether email works now (EM-02). Confirming and changing an address are refused while it does not. */
|
|
56
|
+
emailReady?: () => Promise<boolean>;
|
|
57
|
+
/**
|
|
58
|
+
* Sends a sign-in link (spec 13, section 5), or the reason there is none: it works only for a confirmed address
|
|
59
|
+
* without two-factor (the library would skip two-factor, and for an unconfirmed address it deletes the password).
|
|
60
|
+
* Without it, sign-in links are off.
|
|
61
|
+
*/
|
|
62
|
+
sendSignInLink?: (data: AccountPerson & ({
|
|
63
|
+
url: string;
|
|
64
|
+
} | {
|
|
65
|
+
refused: "two-factor" | "not-confirmed";
|
|
66
|
+
})) => Promise<void>;
|
|
67
|
+
/** Told after a passkey was added or removed, for the audit log (spec 02, "always logged"). */
|
|
68
|
+
onPasskeyChange?: (data: AccountPerson & {
|
|
69
|
+
change: "added" | "removed";
|
|
70
|
+
name: string;
|
|
71
|
+
}) => Promise<void>;
|
|
72
|
+
/** Told when someone signs in from a browser the site does not know for them (after the first one). */
|
|
73
|
+
onNewDevice?: (data: AccountPerson & {
|
|
74
|
+
when: number;
|
|
75
|
+
browser: string;
|
|
76
|
+
address: string;
|
|
77
|
+
}) => Promise<void>;
|
|
78
|
+
}
|
|
79
|
+
/** How long a sign-in link works. */
|
|
80
|
+
export declare const SIGN_IN_LINK_SECONDS: number;
|
|
81
|
+
export type AddressLinkKind = "confirm-email" | "change-email-old" | "change-email-new";
|
|
82
|
+
/** Where the links about an address lead back to, with what happened (the library adds `error=` when it failed). */
|
|
83
|
+
export declare const ADDRESS_RETURN: {
|
|
84
|
+
readonly confirmed: "/admin/account?email=confirmed";
|
|
85
|
+
readonly checkNew: "/admin/account?email=check-new";
|
|
86
|
+
readonly changed: "/admin/account?email=changed";
|
|
87
|
+
};
|
|
88
|
+
export interface AccountPerson {
|
|
89
|
+
userId: string;
|
|
90
|
+
email: string;
|
|
91
|
+
name: string;
|
|
92
|
+
}
|
|
93
|
+
export type AccountChange = "password" | "two-factor-on" | "two-factor-off" | "email";
|
|
94
|
+
/** How long a password reset link works (spec 13, section 7: an expired one is never sent late). */
|
|
95
|
+
export declare const RESET_TOKEN_SECONDS: number;
|
|
96
|
+
/**
|
|
97
|
+
* The parts of the Better Auth object that our code and tests use. Written out, because the library's own type
|
|
98
|
+
* cannot be named from another package (it refers to files inside its dependencies).
|
|
99
|
+
*/
|
|
100
|
+
export interface AuthInstance {
|
|
101
|
+
api: Record<string, (...args: any[]) => Promise<any>>;
|
|
102
|
+
handler: (request: Request) => Promise<Response>;
|
|
103
|
+
$context: Promise<any>;
|
|
104
|
+
}
|
|
105
|
+
export interface RecoverInput {
|
|
106
|
+
/** The site's secret key: proof that the person runs the server. */
|
|
107
|
+
secret: string;
|
|
108
|
+
email: string;
|
|
109
|
+
newPassword: string;
|
|
110
|
+
}
|
|
111
|
+
export interface OksAuth {
|
|
112
|
+
auth: AuthInstance;
|
|
113
|
+
/** What `oks user reset` does (AU-43). Throws when the secret key is wrong. */
|
|
114
|
+
recover(input: RecoverInput): Promise<{
|
|
115
|
+
sessionsRemoved: number;
|
|
116
|
+
auditEntries: number;
|
|
117
|
+
}>;
|
|
118
|
+
handler: (request: Request, connection?: {
|
|
119
|
+
remoteAddress?: string;
|
|
120
|
+
}) => Promise<Response>;
|
|
121
|
+
limiter: ReturnType<typeof createAccountLimiter>;
|
|
122
|
+
}
|
|
123
|
+
export declare function createAuth(options: CreateAuthOptions): OksAuth;
|
|
@@ -0,0 +1,441 @@
|
|
|
1
|
+
// Better Auth on our own tables, on SQLite or PostgreSQL (spec 02; spike S3).
|
|
2
|
+
import { drizzleAdapter } from "@better-auth/drizzle-adapter";
|
|
3
|
+
import { passkey } from "@better-auth/passkey";
|
|
4
|
+
import { newId, pgSchema, sqliteSchema } from "@oks-page/db";
|
|
5
|
+
import { timingSafeEqual } from "node:crypto";
|
|
6
|
+
import { betterAuth } from "better-auth";
|
|
7
|
+
import { APIError, createAuthMiddleware, getSessionFromCtx } from "better-auth/api";
|
|
8
|
+
import { magicLink, twoFactor } from "better-auth/plugins";
|
|
9
|
+
import { accountKey, createAccountLimiter, DEFAULT_ACCOUNT_LIMIT, } from "./account-limit.js";
|
|
10
|
+
import { clientAddress, UNKNOWN_CLIENT } from "./client-ip.js";
|
|
11
|
+
import { checkDevice, DEVICE_COOKIE, DEVICE_DAYS } from "./devices.js";
|
|
12
|
+
/** How long a sign-in link works. */
|
|
13
|
+
export const SIGN_IN_LINK_SECONDS = 15 * 60;
|
|
14
|
+
/** Where the links about an address lead back to, with what happened (the library adds `error=` when it failed). */
|
|
15
|
+
export const ADDRESS_RETURN = {
|
|
16
|
+
confirmed: "/admin/account?email=confirmed",
|
|
17
|
+
checkNew: "/admin/account?email=check-new",
|
|
18
|
+
changed: "/admin/account?email=changed",
|
|
19
|
+
};
|
|
20
|
+
/** How long a password reset link works (spec 13, section 7: an expired one is never sent late). */
|
|
21
|
+
export const RESET_TOKEN_SECONDS = 60 * 60;
|
|
22
|
+
const CLIENT_HEADER = "x-oks-client-ip";
|
|
23
|
+
export function createAuth(options) {
|
|
24
|
+
if (options.secret.length < 32)
|
|
25
|
+
throw new Error("The secret key must be at least 32 characters");
|
|
26
|
+
const schema = options.runner.dialect === "sqlite" ? sqliteSchema : pgSchema;
|
|
27
|
+
const limiter = createAccountLimiter(options.runner, options.accountLimit ?? DEFAULT_ACCOUNT_LIMIT, options.clock);
|
|
28
|
+
const address = options.addressLimit ?? { window: 300, max: 5 };
|
|
29
|
+
const personOf = (user) => ({
|
|
30
|
+
userId: user.id,
|
|
31
|
+
email: user.email,
|
|
32
|
+
name: user.name ?? "",
|
|
33
|
+
});
|
|
34
|
+
/** A security email must never break the change it is about. */
|
|
35
|
+
const notify = async (user, change, extra = {}) => {
|
|
36
|
+
try {
|
|
37
|
+
await options.onAccountChange?.({ ...personOf(user), change, ...extra });
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
// the change is done; the email is only a notice
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
const emailOff = async () => (options.emailReady ? !(await options.emailReady()) : false);
|
|
44
|
+
/** What a link about an address says, read before the library checks it (it is checked there, not here). */
|
|
45
|
+
const tokenPayload = (token) => {
|
|
46
|
+
if (typeof token !== "string")
|
|
47
|
+
return {};
|
|
48
|
+
try {
|
|
49
|
+
const part = token.split(".")[1] ?? "";
|
|
50
|
+
return JSON.parse(Buffer.from(part, "base64url").toString("utf8"));
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
return {};
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* The current password, asked again before something that gives access (spec 02, rule 7; AU-41). It is sent in the body
|
|
58
|
+
* as `password`, taken out before the library reads the body, and checked against the signed-in person's own password.
|
|
59
|
+
*/
|
|
60
|
+
const askPasswordAgain = async (ctx) => {
|
|
61
|
+
const body = (ctx.body ?? {});
|
|
62
|
+
const password = body["password"];
|
|
63
|
+
delete body["password"];
|
|
64
|
+
const session = await getSessionFromCtx(ctx);
|
|
65
|
+
if (!session)
|
|
66
|
+
return;
|
|
67
|
+
const account = (await options.runner.all(`select "password" from "auth_accounts" where "user_id" = ? and "provider_id" = 'credential'`, [session.user.id]))[0];
|
|
68
|
+
const hash = account?.["password"];
|
|
69
|
+
const right = typeof password === "string" &&
|
|
70
|
+
typeof hash === "string" &&
|
|
71
|
+
(await ctx.context.password.verify({ hash, password }));
|
|
72
|
+
if (!right)
|
|
73
|
+
throw new APIError("BAD_REQUEST", { message: "Your current password is not right." });
|
|
74
|
+
};
|
|
75
|
+
/** Names of passkeys about to be removed, by id, for the audit log. */
|
|
76
|
+
const removing = new Map();
|
|
77
|
+
/** Email changes waiting for their last link, by token: who it was and the old address. */
|
|
78
|
+
const changing = new Map();
|
|
79
|
+
const auth = betterAuth({
|
|
80
|
+
database: drizzleAdapter(options.db, {
|
|
81
|
+
provider: options.runner.dialect === "sqlite" ? "sqlite" : "pg",
|
|
82
|
+
schema: {
|
|
83
|
+
user: schema.users,
|
|
84
|
+
session: schema.authSessions,
|
|
85
|
+
account: schema.authAccounts,
|
|
86
|
+
verification: schema.authVerifications,
|
|
87
|
+
twoFactor: schema.twoFactor,
|
|
88
|
+
passkey: schema.passkeys,
|
|
89
|
+
rateLimit: schema.rateLimits,
|
|
90
|
+
},
|
|
91
|
+
}),
|
|
92
|
+
secret: options.secret,
|
|
93
|
+
baseURL: options.baseUrl,
|
|
94
|
+
trustedOrigins: [options.baseUrl, ...(options.trustedOrigins ?? [])],
|
|
95
|
+
logger: { level: "error" },
|
|
96
|
+
emailAndPassword: {
|
|
97
|
+
enabled: true,
|
|
98
|
+
minPasswordLength: options.passwordMinLength ?? 10,
|
|
99
|
+
...(options.sendResetPassword
|
|
100
|
+
? {
|
|
101
|
+
resetPasswordTokenExpiresIn: RESET_TOKEN_SECONDS,
|
|
102
|
+
// A new password signs out every session, as a changed one does (spec 02, section 4).
|
|
103
|
+
revokeSessionsOnPasswordReset: true,
|
|
104
|
+
sendResetPassword: async ({ user, token }) => options.sendResetPassword({ ...personOf(user), token }),
|
|
105
|
+
onPasswordReset: async ({ user }) => notify(user, "password"),
|
|
106
|
+
}
|
|
107
|
+
: {}),
|
|
108
|
+
},
|
|
109
|
+
...(options.sendAddressLink
|
|
110
|
+
? {
|
|
111
|
+
// Confirming an address, and changing it (spec 13, section 5). Signing in never waits for a confirmed address,
|
|
112
|
+
// so nobody is locked out; changing one needs the current one confirmed (see the hook below).
|
|
113
|
+
emailVerification: {
|
|
114
|
+
expiresIn: RESET_TOKEN_SECONDS,
|
|
115
|
+
sendOnSignUp: false,
|
|
116
|
+
autoSignInAfterVerification: false,
|
|
117
|
+
sendVerificationEmail: async ({ user, url }) => {
|
|
118
|
+
// During a change the library passes the new address with the same person.
|
|
119
|
+
const rows = await options.runner.all(`select "email" from "users" where "id" = ?`, [
|
|
120
|
+
user.id,
|
|
121
|
+
]);
|
|
122
|
+
const current = String(rows[0]?.["email"] ?? user.email).toLowerCase();
|
|
123
|
+
const kind = current === user.email.toLowerCase() ? "confirm-email" : "change-email-new";
|
|
124
|
+
await options.sendAddressLink({ ...personOf(user), kind, url });
|
|
125
|
+
},
|
|
126
|
+
},
|
|
127
|
+
user: {
|
|
128
|
+
changeEmail: {
|
|
129
|
+
enabled: true,
|
|
130
|
+
sendChangeEmailConfirmation: async ({ user, newEmail, url, }) => options.sendAddressLink({
|
|
131
|
+
...personOf(user),
|
|
132
|
+
kind: "change-email-old",
|
|
133
|
+
url,
|
|
134
|
+
address: newEmail,
|
|
135
|
+
}),
|
|
136
|
+
},
|
|
137
|
+
},
|
|
138
|
+
}
|
|
139
|
+
: {}),
|
|
140
|
+
advanced: {
|
|
141
|
+
database: { generateId: () => newId() },
|
|
142
|
+
// Only the header our own wrapper writes is read. Anything the browser sends under other names is ignored.
|
|
143
|
+
ipAddress: { ipAddressHeaders: [CLIENT_HEADER] },
|
|
144
|
+
defaultCookieAttributes: { httpOnly: true, sameSite: "lax" },
|
|
145
|
+
// The library skips these checks when it thinks it is running under a test (NODE_ENV=test). They are switched
|
|
146
|
+
// on explicitly, so the product behaves the same everywhere and the tests see what production does (AU-45).
|
|
147
|
+
disableOriginCheck: false,
|
|
148
|
+
disableCSRFCheck: false,
|
|
149
|
+
},
|
|
150
|
+
// On in every mode (the library turns it on only in production), in the database, so it works with several servers.
|
|
151
|
+
rateLimit: {
|
|
152
|
+
enabled: true,
|
|
153
|
+
storage: "database",
|
|
154
|
+
window: 60,
|
|
155
|
+
max: 100,
|
|
156
|
+
customRules: { "/sign-in/email": { window: address.window, max: address.max } },
|
|
157
|
+
},
|
|
158
|
+
plugins: [
|
|
159
|
+
twoFactor(),
|
|
160
|
+
...(options.passkey ? [passkey(options.passkey)] : []),
|
|
161
|
+
...(options.sendSignInLink
|
|
162
|
+
? [
|
|
163
|
+
magicLink({
|
|
164
|
+
expiresIn: SIGN_IN_LINK_SECONDS,
|
|
165
|
+
// A link never makes an account; the token is kept only as a hash.
|
|
166
|
+
disableSignUp: true,
|
|
167
|
+
storeToken: "hashed",
|
|
168
|
+
sendMagicLink: async ({ email, url }) => {
|
|
169
|
+
const rows = await options.runner.all(`select "id", "email", "name", "email_verified", "two_factor_enabled" from "users" where lower("email") = ?`, [email.trim().toLowerCase()]);
|
|
170
|
+
const row = rows[0];
|
|
171
|
+
// No account: nothing is sent, and the page answers the same.
|
|
172
|
+
if (!row)
|
|
173
|
+
return;
|
|
174
|
+
const person = {
|
|
175
|
+
userId: String(row["id"]),
|
|
176
|
+
email: String(row["email"]),
|
|
177
|
+
name: String(row["name"] ?? ""),
|
|
178
|
+
};
|
|
179
|
+
const on = (v) => v === true || Number(v) === 1;
|
|
180
|
+
if (on(row["two_factor_enabled"]))
|
|
181
|
+
return options.sendSignInLink({ ...person, refused: "two-factor" });
|
|
182
|
+
if (!on(row["email_verified"]))
|
|
183
|
+
return options.sendSignInLink({ ...person, refused: "not-confirmed" });
|
|
184
|
+
return options.sendSignInLink({ ...person, url });
|
|
185
|
+
},
|
|
186
|
+
}),
|
|
187
|
+
]
|
|
188
|
+
: []),
|
|
189
|
+
],
|
|
190
|
+
hooks: {
|
|
191
|
+
before: createAuthMiddleware(async (ctx) => {
|
|
192
|
+
if (ctx.path === "/sign-in/email") {
|
|
193
|
+
const email = ctx.body?.email;
|
|
194
|
+
if (typeof email !== "string")
|
|
195
|
+
return;
|
|
196
|
+
const result = await limiter.attempt(email);
|
|
197
|
+
if (!result.allowed) {
|
|
198
|
+
throw new APIError("TOO_MANY_REQUESTS", {
|
|
199
|
+
message: "Too many tries for this account. Wait a little and try again.",
|
|
200
|
+
retryAfterSeconds: Math.ceil(result.retryAfterMs / 1000),
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
// A sign-in link needs email, and always leads to the dashboard (or back to the sign-in page when it failed).
|
|
205
|
+
if (ctx.path === "/sign-in/magic-link") {
|
|
206
|
+
if (await emailOff())
|
|
207
|
+
throw new APIError("BAD_REQUEST", {
|
|
208
|
+
message: "Email is not set up on this site yet, so no link can be sent.",
|
|
209
|
+
});
|
|
210
|
+
const body = (ctx.body ?? {});
|
|
211
|
+
body["callbackURL"] = "/admin";
|
|
212
|
+
body["errorCallbackURL"] = "/admin/login?link=failed";
|
|
213
|
+
delete body["newUserCallbackURL"];
|
|
214
|
+
}
|
|
215
|
+
// Changing the address asks for the current password again (spec 02, rule 7).
|
|
216
|
+
if (ctx.path === "/change-email")
|
|
217
|
+
await askPasswordAgain(ctx);
|
|
218
|
+
// Adding or removing a passkey asks for it too (AU-41): a passkey is a way in, like a password.
|
|
219
|
+
if (ctx.path === "/passkey/verify-registration" || ctx.path === "/passkey/delete-passkey") {
|
|
220
|
+
await askPasswordAgain(ctx);
|
|
221
|
+
if (ctx.path === "/passkey/delete-passkey") {
|
|
222
|
+
const id = ctx.body?.id;
|
|
223
|
+
const session = await getSessionFromCtx(ctx);
|
|
224
|
+
if (typeof id === "string" && session) {
|
|
225
|
+
const row = (await options.runner.all(`select "name" from "passkeys" where "id" = ? and "user_id" = ?`, [id, session.user.id]))[0];
|
|
226
|
+
removing.set(id, String(row?.["name"] ?? ""));
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
// Confirming or changing an address needs email (EM-02), and always comes back to the account page.
|
|
231
|
+
if (ctx.path === "/send-verification-email" || ctx.path === "/change-email") {
|
|
232
|
+
if (await emailOff())
|
|
233
|
+
throw new APIError("BAD_REQUEST", {
|
|
234
|
+
message: "Email is not set up on this site yet, so no link can be sent.",
|
|
235
|
+
});
|
|
236
|
+
const body = (ctx.body ?? {});
|
|
237
|
+
body["callbackURL"] =
|
|
238
|
+
ctx.path === "/change-email" ? ADDRESS_RETURN.changed : ADDRESS_RETURN.confirmed;
|
|
239
|
+
// A new address only for a confirmed current one: the old address must say yes first, so a stolen
|
|
240
|
+
// session cannot move the account to another mailbox.
|
|
241
|
+
if (ctx.path === "/change-email") {
|
|
242
|
+
const session = await getSessionFromCtx(ctx);
|
|
243
|
+
if (session && !session.user.emailVerified)
|
|
244
|
+
throw new APIError("BAD_REQUEST", {
|
|
245
|
+
message: "Confirm your current email address first. Then you can change it.",
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
// The link of an address: back to the account page with what it did; an email change is remembered for its notice.
|
|
250
|
+
if (ctx.path === "/verify-email" && ctx.query && typeof ctx.query === "object") {
|
|
251
|
+
const token = ctx.query["token"];
|
|
252
|
+
const payload = tokenPayload(token);
|
|
253
|
+
ctx.query["callbackURL"] =
|
|
254
|
+
payload.requestType === "change-email-confirmation"
|
|
255
|
+
? ADDRESS_RETURN.checkNew
|
|
256
|
+
: payload.updateTo
|
|
257
|
+
? ADDRESS_RETURN.changed
|
|
258
|
+
: ADDRESS_RETURN.confirmed;
|
|
259
|
+
if (payload.requestType === "change-email-verification" &&
|
|
260
|
+
payload.email &&
|
|
261
|
+
payload.updateTo) {
|
|
262
|
+
const rows = await options.runner.all(`select "id" from "users" where lower("email") = ?`, [payload.email.toLowerCase()]);
|
|
263
|
+
if (rows[0])
|
|
264
|
+
changing.set(String(token), {
|
|
265
|
+
userId: String(rows[0]["id"]),
|
|
266
|
+
previous: payload.email,
|
|
267
|
+
address: payload.updateTo,
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
// A password change signs out every other session (spec 02, section 4).
|
|
272
|
+
if (ctx.path === "/change-password" && ctx.body && typeof ctx.body === "object") {
|
|
273
|
+
ctx.body["revokeOtherSessions"] = true;
|
|
274
|
+
}
|
|
275
|
+
}),
|
|
276
|
+
after: createAuthMiddleware(async (ctx) => {
|
|
277
|
+
// A sign-in from a browser the site does not know for this person: remember it, and send the alert. Every
|
|
278
|
+
// way of signing in counts once its session exists (password, the code after it, passkey, sign-in link).
|
|
279
|
+
const fresh = ctx.context.newSession;
|
|
280
|
+
const answer = ctx.context.returned;
|
|
281
|
+
if (fresh?.user &&
|
|
282
|
+
ctx.path !== "/sign-up/email" &&
|
|
283
|
+
ctx.path !== "/verify-email" &&
|
|
284
|
+
!(answer && typeof answer === "object" && "twoFactorRedirect" in answer)) {
|
|
285
|
+
try {
|
|
286
|
+
const device = await checkDevice(options.runner, fresh.user.id, ctx.getCookie(DEVICE_COOKIE), fresh.session?.userAgent ?? ctx.headers?.get("user-agent"), options.clock);
|
|
287
|
+
ctx.setCookie(DEVICE_COOKIE, device.value, {
|
|
288
|
+
httpOnly: true,
|
|
289
|
+
sameSite: "lax",
|
|
290
|
+
secure: options.baseUrl.startsWith("https://"),
|
|
291
|
+
path: "/",
|
|
292
|
+
maxAge: DEVICE_DAYS * 24 * 60 * 60,
|
|
293
|
+
});
|
|
294
|
+
if (device.alert)
|
|
295
|
+
await options.onNewDevice?.({
|
|
296
|
+
...personOf(fresh.user),
|
|
297
|
+
when: (options.clock ?? Date.now)(),
|
|
298
|
+
browser: device.description,
|
|
299
|
+
address: fresh.session?.ipAddress ?? ctx.headers?.get(CLIENT_HEADER) ?? "",
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
catch {
|
|
303
|
+
// The sign-in is done; the alert is only a notice.
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
// An email change is done when the person now has the new address (the library answers with a redirect
|
|
307
|
+
// either way, so the database decides). The notice goes to the old address and to the new one.
|
|
308
|
+
if (ctx.path === "/verify-email") {
|
|
309
|
+
const token = String(ctx.query?.["token"] ?? "");
|
|
310
|
+
const change = changing.get(token);
|
|
311
|
+
changing.delete(token);
|
|
312
|
+
if (!change)
|
|
313
|
+
return;
|
|
314
|
+
const rows = await options.runner.all(`select "id", "email", "name" from "users" where "id" = ?`, [change.userId]);
|
|
315
|
+
const user = rows[0];
|
|
316
|
+
if (!user || String(user["email"]).toLowerCase() !== change.address.toLowerCase())
|
|
317
|
+
return;
|
|
318
|
+
const person = {
|
|
319
|
+
id: change.userId,
|
|
320
|
+
email: change.previous,
|
|
321
|
+
name: String(user["name"] ?? ""),
|
|
322
|
+
};
|
|
323
|
+
const extra = { previous: change.previous, address: change.address };
|
|
324
|
+
await notify(person, "email", extra);
|
|
325
|
+
await notify({ ...person, email: change.address }, "email", extra);
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
const returned = ctx.context.returned;
|
|
329
|
+
const failed = returned instanceof APIError ||
|
|
330
|
+
(typeof returned?.status === "number" && returned.status >= 400);
|
|
331
|
+
if (failed)
|
|
332
|
+
return;
|
|
333
|
+
if (ctx.path === "/sign-in/email") {
|
|
334
|
+
const email = ctx.body?.email;
|
|
335
|
+
if (typeof email === "string")
|
|
336
|
+
await limiter.succeeded(email);
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
// The security emails: a changed password, two-factor turned off, or turned on (its first code checked).
|
|
340
|
+
const user = ctx.context.session?.user;
|
|
341
|
+
if (!user)
|
|
342
|
+
return;
|
|
343
|
+
// A passkey added or removed: for the audit log. It never undoes the change.
|
|
344
|
+
if (ctx.path === "/passkey/verify-registration" || ctx.path === "/passkey/delete-passkey") {
|
|
345
|
+
try {
|
|
346
|
+
let name = "";
|
|
347
|
+
if (ctx.path === "/passkey/delete-passkey") {
|
|
348
|
+
const id = String(ctx.body?.id ?? "");
|
|
349
|
+
name = removing.get(id) ?? "";
|
|
350
|
+
removing.delete(id);
|
|
351
|
+
}
|
|
352
|
+
else {
|
|
353
|
+
const row = (await options.runner.all(`select "name" from "passkeys" where "user_id" = ? order by "created_at" desc limit 1`, [user.id]))[0];
|
|
354
|
+
name = String(row?.["name"] ?? "");
|
|
355
|
+
}
|
|
356
|
+
await options.onPasskeyChange?.({
|
|
357
|
+
...personOf(user),
|
|
358
|
+
change: ctx.path === "/passkey/delete-passkey" ? "removed" : "added",
|
|
359
|
+
name,
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
catch {
|
|
363
|
+
// the change is done; the log entry is only a record
|
|
364
|
+
}
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
if (ctx.path === "/change-password")
|
|
368
|
+
await notify(user, "password");
|
|
369
|
+
else if (ctx.path === "/two-factor/disable")
|
|
370
|
+
await notify(user, "two-factor-off");
|
|
371
|
+
else if (ctx.path === "/two-factor/verify-totp" && !user.twoFactorEnabled) {
|
|
372
|
+
const now = await options.runner.all(`select "two_factor_enabled" from "users" where "id" = ?`, [user.id]);
|
|
373
|
+
const on = now[0]?.["two_factor_enabled"];
|
|
374
|
+
if (on === true || on === 1)
|
|
375
|
+
await notify(user, "two-factor-on");
|
|
376
|
+
}
|
|
377
|
+
}),
|
|
378
|
+
},
|
|
379
|
+
});
|
|
380
|
+
/**
|
|
381
|
+
* The function for the HTTP route. It decides the client address itself (from the connection and the trusted
|
|
382
|
+
* proxies) and removes whatever the sender wrote in the headers the library might read, so a made-up
|
|
383
|
+
* `X-Forwarded-For` cannot hide an attacker or frame someone else (AU-39).
|
|
384
|
+
*/
|
|
385
|
+
function handler(request, connection = {}) {
|
|
386
|
+
const headers = new Headers(request.headers);
|
|
387
|
+
const ip = clientAddress(headers.get("x-forwarded-for"), connection.remoteAddress, options.trustedProxies);
|
|
388
|
+
for (const name of [
|
|
389
|
+
"x-forwarded-for",
|
|
390
|
+
"x-real-ip",
|
|
391
|
+
"cf-connecting-ip",
|
|
392
|
+
"x-client-ip",
|
|
393
|
+
"forwarded",
|
|
394
|
+
CLIENT_HEADER,
|
|
395
|
+
])
|
|
396
|
+
headers.delete(name);
|
|
397
|
+
headers.set(CLIENT_HEADER, ip || UNKNOWN_CLIENT);
|
|
398
|
+
return auth.handler(new Request(request, { headers }));
|
|
399
|
+
}
|
|
400
|
+
async function recover(input) {
|
|
401
|
+
const given = Buffer.from(input.secret);
|
|
402
|
+
const real = Buffer.from(options.secret);
|
|
403
|
+
if (given.length !== real.length || !timingSafeEqual(given, real))
|
|
404
|
+
throw new Error("The secret key is wrong. Nothing was changed.");
|
|
405
|
+
const minLength = options.passwordMinLength ?? 10;
|
|
406
|
+
if (input.newPassword.length < minLength)
|
|
407
|
+
throw new Error(`The new password must have at least ${minLength} characters.`);
|
|
408
|
+
const context = await auth.$context;
|
|
409
|
+
const hash = await context.password.hash(input.newPassword);
|
|
410
|
+
const now = new Date();
|
|
411
|
+
return options.runner.transaction(async (tx) => {
|
|
412
|
+
const user = (await tx.all(`select "id" from "users" where lower("email") = ?`, [
|
|
413
|
+
input.email.trim().toLowerCase(),
|
|
414
|
+
]))[0];
|
|
415
|
+
if (!user)
|
|
416
|
+
throw new Error("There is no account with that email address.");
|
|
417
|
+
const userId = String(user["id"]);
|
|
418
|
+
const updated = await tx.all(`update "auth_accounts" set "password" = ?, "updated_at" = ? where "user_id" = ? and "provider_id" = 'credential' returning "id"`, [hash, now, userId]);
|
|
419
|
+
if (updated.length === 0) {
|
|
420
|
+
await tx.all(`insert into "auth_accounts" ("id", "user_id", "account_id", "provider_id", "password", "created_at", "updated_at") values (?, ?, ?, 'credential', ?, ?, ?)`, [newId(), userId, userId, hash, now, now]);
|
|
421
|
+
}
|
|
422
|
+
const sessions = await tx.all(`delete from "auth_sessions" where "user_id" = ? returning "id"`, [userId]);
|
|
423
|
+
await tx.all(`delete from "rate_limits" where "key" = ?`, [accountKey(input.email)]);
|
|
424
|
+
// One audit entry in every site the person belongs to.
|
|
425
|
+
const sites = await tx.all(`select "site_id" from "site_members" where "user_id" = ?`, [
|
|
426
|
+
userId,
|
|
427
|
+
]);
|
|
428
|
+
for (const site of sites) {
|
|
429
|
+
await tx.all(`insert into "audit_log" ("id", "site_id", "actor_type", "actor_id", "action", "target_type", "target_id", "detail", "created_at") values (?, ?, 'system', 'oks user reset', 'user.password_reset', 'user', ?, ?, ?)`, [
|
|
430
|
+
newId(),
|
|
431
|
+
site["site_id"],
|
|
432
|
+
userId,
|
|
433
|
+
JSON.stringify({ sessionsRemoved: sessions.length }),
|
|
434
|
+
now,
|
|
435
|
+
]);
|
|
436
|
+
}
|
|
437
|
+
return { sessionsRemoved: sessions.length, auditEntries: sites.length };
|
|
438
|
+
});
|
|
439
|
+
}
|
|
440
|
+
return { auth: auth, recover, handler, limiter };
|
|
441
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { SqlRunner } from "@oks-page/db";
|
|
2
|
+
export declare const DEVICE_COOKIE = "oks_device";
|
|
3
|
+
/** How long a browser stays known after its last sign-in. */
|
|
4
|
+
export declare const DEVICE_DAYS = 400;
|
|
5
|
+
/** "Firefox on Windows", from the browser's own description; "a browser" when it says nothing useful. */
|
|
6
|
+
export declare function describeBrowser(userAgent: string | null | undefined): string;
|
|
7
|
+
export interface DeviceCheck {
|
|
8
|
+
/** The value to keep in the cookie (the same one, or a new one). */
|
|
9
|
+
value: string;
|
|
10
|
+
/** True when this browser was not known for this person, and the person had signed in from another one before. */
|
|
11
|
+
alert: boolean;
|
|
12
|
+
description: string;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Notes a sign-in from this browser. The first browser a person ever signs in from is remembered without an alert;
|
|
16
|
+
* after that, a browser the site does not know gets one. Browsers not seen for 400 days are forgotten.
|
|
17
|
+
*/
|
|
18
|
+
export declare function checkDevice(runner: SqlRunner, userId: string, cookieValue: string | null | undefined, userAgent: string | null | undefined, now?: () => number): Promise<DeviceCheck>;
|
package/dist/devices.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
export const DEVICE_COOKIE = "oks_device";
|
|
3
|
+
/** How long a browser stays known after its last sign-in. */
|
|
4
|
+
export const DEVICE_DAYS = 400;
|
|
5
|
+
const hash = (value) => createHash("sha256").update(value).digest("hex");
|
|
6
|
+
/** "Firefox on Windows", from the browser's own description; "a browser" when it says nothing useful. */
|
|
7
|
+
export function describeBrowser(userAgent) {
|
|
8
|
+
const ua = userAgent ?? "";
|
|
9
|
+
const browser = /Edg\//.test(ua)
|
|
10
|
+
? "Edge"
|
|
11
|
+
: /OPR\/|Opera/.test(ua)
|
|
12
|
+
? "Opera"
|
|
13
|
+
: /Firefox\//.test(ua)
|
|
14
|
+
? "Firefox"
|
|
15
|
+
: /Chrome\/|CriOS\//.test(ua)
|
|
16
|
+
? "Chrome"
|
|
17
|
+
: /Safari\//.test(ua)
|
|
18
|
+
? "Safari"
|
|
19
|
+
: "";
|
|
20
|
+
const system = /Android/.test(ua)
|
|
21
|
+
? "Android"
|
|
22
|
+
: /iPhone|iPad|iPod/.test(ua)
|
|
23
|
+
? "iOS"
|
|
24
|
+
: /Windows/.test(ua)
|
|
25
|
+
? "Windows"
|
|
26
|
+
: /Mac OS X|Macintosh/.test(ua)
|
|
27
|
+
? "macOS"
|
|
28
|
+
: /Linux/.test(ua)
|
|
29
|
+
? "Linux"
|
|
30
|
+
: "";
|
|
31
|
+
if (browser && system)
|
|
32
|
+
return `${browser} on ${system}`;
|
|
33
|
+
return browser || (system ? `a browser on ${system}` : "a browser");
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Notes a sign-in from this browser. The first browser a person ever signs in from is remembered without an alert;
|
|
37
|
+
* after that, a browser the site does not know gets one. Browsers not seen for 400 days are forgotten.
|
|
38
|
+
*/
|
|
39
|
+
export async function checkDevice(runner, userId, cookieValue, userAgent, now = Date.now) {
|
|
40
|
+
const at = new Date(now());
|
|
41
|
+
await runner.all(`delete from "known_devices" where "user_id" = ? and "last_seen_at" < ?`, [
|
|
42
|
+
userId,
|
|
43
|
+
new Date(now() - DEVICE_DAYS * 24 * 60 * 60 * 1000),
|
|
44
|
+
]);
|
|
45
|
+
const description = describeBrowser(userAgent);
|
|
46
|
+
const valid = typeof cookieValue === "string" && /^[A-Za-z0-9_-]{43}$/.test(cookieValue);
|
|
47
|
+
if (valid) {
|
|
48
|
+
const known = await runner.all(`select 1 from "known_devices" where "user_id" = ? and "device_hash" = ?`, [userId, hash(cookieValue)]);
|
|
49
|
+
if (known.length > 0) {
|
|
50
|
+
await runner.all(`update "known_devices" set "last_seen_at" = ?, "description" = ? where "user_id" = ? and "device_hash" = ?`, [at, description, userId, hash(cookieValue)]);
|
|
51
|
+
return { value: cookieValue, alert: false, description };
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
// A browser this person has not used: keep a value for it (the one it brought, so another person on the same
|
|
55
|
+
// browser keeps it too, or a new one).
|
|
56
|
+
const value = valid ? cookieValue : randomBytes(32).toString("base64url");
|
|
57
|
+
const before = await runner.all(`select count(*) as "n" from "known_devices" where "user_id" = ?`, [userId]);
|
|
58
|
+
await runner.all(`insert into "known_devices" ("user_id", "device_hash", "description", "created_at", "last_seen_at")
|
|
59
|
+
values (?, ?, ?, ?, ?)`, [userId, hash(value), description, at, at]);
|
|
60
|
+
return { value, alert: Number(before[0]?.["n"] ?? 0) > 0, description };
|
|
61
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { browserSupportsWebAuthn, startAuthentication, startRegistration, } from "@simplewebauthn/browser";
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// The browser side of passkeys, for the sign-in and account screens (spec 02). Browser-safe: nothing from the server
|
|
2
|
+
// parts of this package is imported here, so a screen can import it without pulling them into the page.
|
|
3
|
+
export { browserSupportsWebAuthn, startAuthentication, startRegistration, } from "@simplewebauthn/browser";
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { TestDb } from "@oks-page/db/testing";
|
|
2
|
+
import { type CreateAuthOptions, type OksAuth } from "./create-auth.js";
|
|
3
|
+
export declare const SECRET: string;
|
|
4
|
+
export declare const BASE_URL = "http://localhost:3000";
|
|
5
|
+
export declare function authFor(db: TestDb, extra?: Partial<CreateAuthOptions>): OksAuth;
|
|
6
|
+
export declare const post: (a: OksAuth, path: string, body: unknown, headers?: Record<string, string>, remoteAddress?: string) => Promise<Response>;
|
|
7
|
+
/** Turn Set-Cookie headers into a Cookie header. */
|
|
8
|
+
export declare const cookieOf: (res: Response) => string;
|
|
9
|
+
import { type Server } from "node:http";
|
|
10
|
+
export interface TestServer {
|
|
11
|
+
url: string;
|
|
12
|
+
port: number;
|
|
13
|
+
close(): Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
/** Start a server on a free port. `page` is the HTML of "/"; everything under /api/auth goes to the handler. */
|
|
16
|
+
export declare function startServer(getHandler: () => OksAuth["handler"], page: () => string): Promise<{
|
|
17
|
+
server: Server;
|
|
18
|
+
port: number;
|
|
19
|
+
}>;
|
|
20
|
+
/** A Chromium or Chrome to drive, or null. In CI one must exist. */
|
|
21
|
+
export declare function findBrowser(): string | null;
|
package/dist/testing.js
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// Test helpers shared by the auth tests.
|
|
2
|
+
import { pgSchema, sqliteSchema } from "@oks-page/db";
|
|
3
|
+
import { createAuth } from "./create-auth.js";
|
|
4
|
+
export const SECRET = "s".repeat(40);
|
|
5
|
+
export const BASE_URL = "http://localhost:3000";
|
|
6
|
+
export function authFor(db, extra = {}) {
|
|
7
|
+
return createAuth({
|
|
8
|
+
db: db.drizzle(db.kind === "sqlite" ? sqliteSchema : pgSchema),
|
|
9
|
+
runner: db.runner,
|
|
10
|
+
secret: SECRET,
|
|
11
|
+
baseUrl: BASE_URL,
|
|
12
|
+
...extra,
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
export const post = (a, path, body, headers = {}, remoteAddress = "203.0.113.1") => a.handler(new Request(`${BASE_URL}/api/auth${path}`, {
|
|
16
|
+
method: "POST",
|
|
17
|
+
headers: { "content-type": "application/json", origin: BASE_URL, ...headers },
|
|
18
|
+
body: JSON.stringify(body),
|
|
19
|
+
}), { remoteAddress });
|
|
20
|
+
/** Turn Set-Cookie headers into a Cookie header. */
|
|
21
|
+
export const cookieOf = (res) => res.headers
|
|
22
|
+
.getSetCookie()
|
|
23
|
+
.map((c) => c.split(";")[0])
|
|
24
|
+
.join("; ");
|
|
25
|
+
// ---- a real HTTP server around the handler, for tests that drive a browser ----
|
|
26
|
+
import { createServer } from "node:http";
|
|
27
|
+
import { existsSync } from "node:fs";
|
|
28
|
+
async function toRequest(req, base) {
|
|
29
|
+
const chunks = [];
|
|
30
|
+
for await (const c of req)
|
|
31
|
+
chunks.push(c);
|
|
32
|
+
const body = chunks.length ? Buffer.concat(chunks) : undefined;
|
|
33
|
+
const headers = new Headers();
|
|
34
|
+
for (const [k, v] of Object.entries(req.headers))
|
|
35
|
+
if (v !== undefined)
|
|
36
|
+
headers.set(k, Array.isArray(v) ? v.join(", ") : v);
|
|
37
|
+
const init = { method: req.method ?? "GET", headers };
|
|
38
|
+
if (body && req.method !== "GET" && req.method !== "HEAD")
|
|
39
|
+
init.body = body;
|
|
40
|
+
return new Request(new URL(req.url ?? "/", base), init);
|
|
41
|
+
}
|
|
42
|
+
async function send(res, response) {
|
|
43
|
+
const headers = {};
|
|
44
|
+
response.headers.forEach((v, k) => {
|
|
45
|
+
if (k !== "set-cookie")
|
|
46
|
+
headers[k] = v;
|
|
47
|
+
});
|
|
48
|
+
const cookies = response.headers.getSetCookie();
|
|
49
|
+
if (cookies.length)
|
|
50
|
+
headers["set-cookie"] = cookies;
|
|
51
|
+
res.writeHead(response.status, headers).end(Buffer.from(await response.arrayBuffer()));
|
|
52
|
+
}
|
|
53
|
+
/** Start a server on a free port. `page` is the HTML of "/"; everything under /api/auth goes to the handler. */
|
|
54
|
+
export async function startServer(getHandler, page) {
|
|
55
|
+
let base = "";
|
|
56
|
+
const server = createServer(async (req, res) => {
|
|
57
|
+
try {
|
|
58
|
+
if (req.url?.startsWith("/api/auth"))
|
|
59
|
+
return void (await send(res, await getHandler()(await toRequest(req, base), req.socket.remoteAddress ? { remoteAddress: req.socket.remoteAddress } : {})));
|
|
60
|
+
res.writeHead(200, { "content-type": "text/html" }).end(page());
|
|
61
|
+
}
|
|
62
|
+
catch (e) {
|
|
63
|
+
res.writeHead(500).end(String(e));
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
|
|
67
|
+
const port = server.address().port;
|
|
68
|
+
base = `http://localhost:${port}`;
|
|
69
|
+
return { server, port };
|
|
70
|
+
}
|
|
71
|
+
/** A Chromium or Chrome to drive, or null. In CI one must exist. */
|
|
72
|
+
export function findBrowser() {
|
|
73
|
+
const candidates = [
|
|
74
|
+
process.env["CHROMIUM_PATH"],
|
|
75
|
+
"/opt/pw-browsers/chromium",
|
|
76
|
+
"/usr/bin/google-chrome",
|
|
77
|
+
"/usr/bin/google-chrome-stable",
|
|
78
|
+
"/usr/bin/chromium",
|
|
79
|
+
"/usr/bin/chromium-browser",
|
|
80
|
+
];
|
|
81
|
+
return candidates.find((p) => Boolean(p) && existsSync(p)) ?? null;
|
|
82
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,51 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@oks-page/auth",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0-beta.0",
|
|
4
|
+
"description": "Login, sessions, roles and capabilities",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"default": "./dist/index.js"
|
|
12
|
+
},
|
|
13
|
+
"./passkey-client": {
|
|
14
|
+
"types": "./dist/passkey-client.d.ts",
|
|
15
|
+
"default": "./dist/passkey-client.js"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"dependencies": {
|
|
19
|
+
"@better-auth/drizzle-adapter": "1.7.12",
|
|
20
|
+
"@better-auth/passkey": "1.7.12",
|
|
21
|
+
"@simplewebauthn/browser": "^14.0.0",
|
|
22
|
+
"better-auth": "1.7.12",
|
|
23
|
+
"drizzle-orm": "0.45.4"
|
|
24
|
+
},
|
|
25
|
+
"devDependencies": {
|
|
26
|
+
"esbuild": "^0.28.2",
|
|
27
|
+
"otplib": "^13.5.0",
|
|
28
|
+
"playwright-core": "^1.64.1",
|
|
29
|
+
"ulidx": "^2.4.1",
|
|
30
|
+
"@oks-page/db": "0.1.0-beta.0"
|
|
31
|
+
},
|
|
32
|
+
"license": "MIT",
|
|
33
|
+
"repository": {
|
|
34
|
+
"type": "git",
|
|
35
|
+
"url": "git+https://github.com/OKS-ORG/oks-page.git",
|
|
36
|
+
"directory": "packages/auth"
|
|
37
|
+
},
|
|
38
|
+
"homepage": "https://github.com/OKS-ORG/oks-page#readme",
|
|
39
|
+
"bugs": {
|
|
40
|
+
"url": "https://github.com/OKS-ORG/oks-page/issues"
|
|
41
|
+
},
|
|
42
|
+
"files": [
|
|
43
|
+
"dist"
|
|
44
|
+
],
|
|
45
|
+
"engines": {
|
|
46
|
+
"node": ">=22"
|
|
47
|
+
},
|
|
48
|
+
"publishConfig": {
|
|
49
|
+
"access": "public"
|
|
50
|
+
}
|
|
6
51
|
}
|