@tylix/auth 1.4.0 → 2.0.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/README.md +284 -14
- package/package.json +95 -9
- package/src/client/client.d.ts +14 -0
- package/src/client/client.js +83 -0
- package/src/cookies/authCookies.d.ts +8 -6
- package/src/cookies/authCookies.js +43 -28
- package/src/core/crypto.js +143 -0
- package/src/core/keys.js +83 -0
- package/src/core/seal.js +43 -0
- package/src/generators/AuthGenerator.d.ts +9 -3
- package/src/generators/AuthGenerator.js +16 -4
- package/src/generators/templates/auth-controller-ts.tyx +401 -98
- package/src/generators/templates/auth-controller.tyx +384 -96
- package/src/generators/templates/auth-session-migration-ts.tyx +34 -0
- package/src/generators/templates/auth-session-migration.tyx +32 -0
- package/src/generators/templates/auth-session-model-ts.tyx +53 -0
- package/src/generators/templates/auth-session-model.tyx +34 -0
- package/src/generators/templates/auth-validator-ts.tyx +17 -0
- package/src/generators/templates/auth-validator.tyx +17 -0
- package/src/generators/templates/oauth-account-migration-ts.tyx +29 -0
- package/src/generators/templates/oauth-account-migration.tyx +27 -0
- package/src/generators/templates/oauth-account-model-ts.tyx +65 -0
- package/src/generators/templates/oauth-account-model.tyx +45 -0
- package/src/generators/templates/password-reset-model-ts.tyx +26 -4
- package/src/generators/templates/password-reset-model.tyx +26 -4
- package/src/generators/templates/reset-password-view.html +30 -3
- package/src/generators/templates/verify-email-view.html +30 -3
- package/src/http/cookies.js +91 -0
- package/src/http/origin.js +68 -0
- package/src/http/request.js +179 -0
- package/src/index.d.ts +9 -1
- package/src/index.js +5 -0
- package/src/integrations/h3.d.ts +6 -0
- package/src/integrations/h3.js +70 -0
- package/src/integrations/hono.d.ts +6 -0
- package/src/integrations/hono.js +36 -0
- package/src/integrations/next.d.ts +16 -0
- package/src/integrations/next.js +36 -0
- package/src/integrations/node.d.ts +7 -0
- package/src/integrations/node.js +87 -0
- package/src/integrations/routes.js +92 -0
- package/src/integrations/sveltekit.d.ts +5 -0
- package/src/integrations/sveltekit.js +52 -0
- package/src/integrations/web.js +69 -0
- package/src/mfa/totp.js +150 -0
- package/src/oauth/oauth.js +142 -0
- package/src/oauth/providers.js +112 -0
- package/src/password/hashPassword.d.ts +5 -1
- package/src/password/hashPassword.js +96 -30
- package/src/password/index.d.ts +2 -0
- package/src/password/index.js +2 -0
- package/src/password/policy.js +108 -0
- package/src/rateLimiter/loginRateLimiter.js +16 -6
- package/src/ratelimit/limiter.js +129 -0
- package/src/session/adapters/keyValue.js +87 -0
- package/src/session/adapters/memory.js +38 -0
- package/src/session/adapters/model.js +97 -0
- package/src/session/adapters/prisma.js +67 -0
- package/src/session/adapters/sql.js +128 -0
- package/src/session/createAuth.js +420 -0
- package/src/token/jwt.js +144 -0
- package/src/token/signToken.js +41 -22
- package/src/tylix/accessTokens.js +61 -0
- package/src/web.d.ts +359 -0
- package/src/web.js +47 -0
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generated by Tylix
|
|
3
|
+
*
|
|
4
|
+
* Generator: AuthGenerator
|
|
5
|
+
* Version: 0.2.0
|
|
6
|
+
* Feature: AuthSession
|
|
7
|
+
*
|
|
8
|
+
* Do not edit this section.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
export const up = async (schema) => {
|
|
12
|
+
await schema.createTable("auth_sessions", (table) => {
|
|
13
|
+
table.increments("id");
|
|
14
|
+
table.string("sid").unique();
|
|
15
|
+
table.integer("user_id");
|
|
16
|
+
table.string("token_hash");
|
|
17
|
+
table.string("prev_token_hash");
|
|
18
|
+
table.datetime("rotated_at");
|
|
19
|
+
table.datetime("last_used_at");
|
|
20
|
+
table.datetime("expires_at");
|
|
21
|
+
table.datetime("idle_expires_at");
|
|
22
|
+
table.integer("persistent");
|
|
23
|
+
table.string("ip");
|
|
24
|
+
table.text("user_agent");
|
|
25
|
+
table.text("data");
|
|
26
|
+
table.timestamps();
|
|
27
|
+
});
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
export const down = async (schema) => {
|
|
31
|
+
await schema.dropTable("auth_sessions");
|
|
32
|
+
};
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generated by Tylix
|
|
3
|
+
*
|
|
4
|
+
* Generator: AuthGenerator
|
|
5
|
+
* Version: 0.2.0
|
|
6
|
+
* Feature: AuthSession
|
|
7
|
+
*
|
|
8
|
+
* Do not edit this section.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { Model } from "@tylix/orm";
|
|
12
|
+
|
|
13
|
+
export interface AuthSessionAttributes {
|
|
14
|
+
id: number;
|
|
15
|
+
sid: string;
|
|
16
|
+
user_id: number;
|
|
17
|
+
token_hash: string;
|
|
18
|
+
prev_token_hash: string | null;
|
|
19
|
+
rotated_at: string | null;
|
|
20
|
+
last_used_at: string;
|
|
21
|
+
expires_at: string;
|
|
22
|
+
idle_expires_at: string | null;
|
|
23
|
+
persistent: number;
|
|
24
|
+
ip: string | null;
|
|
25
|
+
user_agent: string | null;
|
|
26
|
+
data: string | null;
|
|
27
|
+
created_at: string;
|
|
28
|
+
updated_at: string;
|
|
29
|
+
[key: string]: unknown;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// One row per signed-in browser or device. Managed by @tylix/auth
|
|
33
|
+
// (createAuth + modelAdapter): rows are created at login, their refresh
|
|
34
|
+
// token hash rotates on every refresh, and logout / "sign out everywhere"
|
|
35
|
+
// / password resets delete them. Only HMACs of tokens are stored.
|
|
36
|
+
export class AuthSession extends Model {
|
|
37
|
+
static table = "auth_sessions";
|
|
38
|
+
|
|
39
|
+
static fillable: string[] = [
|
|
40
|
+
"sid",
|
|
41
|
+
"user_id",
|
|
42
|
+
"token_hash",
|
|
43
|
+
"prev_token_hash",
|
|
44
|
+
"rotated_at",
|
|
45
|
+
"last_used_at",
|
|
46
|
+
"expires_at",
|
|
47
|
+
"idle_expires_at",
|
|
48
|
+
"persistent",
|
|
49
|
+
"ip",
|
|
50
|
+
"user_agent",
|
|
51
|
+
"data",
|
|
52
|
+
];
|
|
53
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generated by Tylix
|
|
3
|
+
*
|
|
4
|
+
* Generator: AuthGenerator
|
|
5
|
+
* Version: 0.2.0
|
|
6
|
+
* Feature: AuthSession
|
|
7
|
+
*
|
|
8
|
+
* Do not edit this section.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { Model } from "@tylix/orm";
|
|
12
|
+
|
|
13
|
+
// One row per signed-in browser or device. Managed by @tylix/auth
|
|
14
|
+
// (createAuth + modelAdapter): rows are created at login, their refresh
|
|
15
|
+
// token hash rotates on every refresh, and logout / "sign out everywhere"
|
|
16
|
+
// / password resets delete them. Only HMACs of tokens are stored.
|
|
17
|
+
export class AuthSession extends Model {
|
|
18
|
+
static table = "auth_sessions";
|
|
19
|
+
|
|
20
|
+
static fillable = [
|
|
21
|
+
"sid",
|
|
22
|
+
"user_id",
|
|
23
|
+
"token_hash",
|
|
24
|
+
"prev_token_hash",
|
|
25
|
+
"rotated_at",
|
|
26
|
+
"last_used_at",
|
|
27
|
+
"expires_at",
|
|
28
|
+
"idle_expires_at",
|
|
29
|
+
"persistent",
|
|
30
|
+
"ip",
|
|
31
|
+
"user_agent",
|
|
32
|
+
"data",
|
|
33
|
+
];
|
|
34
|
+
}
|
|
@@ -55,6 +55,15 @@ export const forgotPasswordSchema = {
|
|
|
55
55
|
email,
|
|
56
56
|
};
|
|
57
57
|
|
|
58
|
+
export const changePasswordSchema = {
|
|
59
|
+
currentPassword: [withMessage(required, "Enter your current password."), isString],
|
|
60
|
+
password: newPassword,
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
export const resendVerificationSchema = {
|
|
64
|
+
email,
|
|
65
|
+
};
|
|
66
|
+
|
|
58
67
|
export const resetPasswordSchema = {
|
|
59
68
|
email,
|
|
60
69
|
token: [withMessage(required, "This reset link is incomplete."), isString],
|
|
@@ -76,3 +85,11 @@ export function validateForgotPassword(data: unknown) {
|
|
|
76
85
|
export function validateResetPassword(data: unknown) {
|
|
77
86
|
return validate(data, resetPasswordSchema);
|
|
78
87
|
}
|
|
88
|
+
|
|
89
|
+
export function validateChangePassword(data: unknown) {
|
|
90
|
+
return validate(data, changePasswordSchema);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function validateResendVerification(data: unknown) {
|
|
94
|
+
return validate(data, resendVerificationSchema);
|
|
95
|
+
}
|
|
@@ -55,6 +55,15 @@ export const forgotPasswordSchema = {
|
|
|
55
55
|
email,
|
|
56
56
|
};
|
|
57
57
|
|
|
58
|
+
export const changePasswordSchema = {
|
|
59
|
+
currentPassword: [withMessage(required, "Enter your current password."), isString],
|
|
60
|
+
password: newPassword,
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
export const resendVerificationSchema = {
|
|
64
|
+
email,
|
|
65
|
+
};
|
|
66
|
+
|
|
58
67
|
export const resetPasswordSchema = {
|
|
59
68
|
email,
|
|
60
69
|
token: [withMessage(required, "This reset link is incomplete."), isString],
|
|
@@ -76,3 +85,11 @@ export function validateForgotPassword(data) {
|
|
|
76
85
|
export function validateResetPassword(data) {
|
|
77
86
|
return validate(data, resetPasswordSchema);
|
|
78
87
|
}
|
|
88
|
+
|
|
89
|
+
export function validateChangePassword(data) {
|
|
90
|
+
return validate(data, changePasswordSchema);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function validateResendVerification(data) {
|
|
94
|
+
return validate(data, resendVerificationSchema);
|
|
95
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generated by Tylix
|
|
3
|
+
*
|
|
4
|
+
* Generator: AuthGenerator
|
|
5
|
+
* Version: 0.3.0
|
|
6
|
+
* Feature: OAuthAccount
|
|
7
|
+
*
|
|
8
|
+
* Do not edit this section.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { Schema, CreateTableBuilder } from "@tylix/shared";
|
|
12
|
+
|
|
13
|
+
export const up = async (schema: Schema) => {
|
|
14
|
+
await schema.createTable("oauth_accounts", (table: CreateTableBuilder) => {
|
|
15
|
+
table.increments("id");
|
|
16
|
+
// "<provider>:<provider user id>", e.g. "github:583231". One column
|
|
17
|
+
// so the unique index works on every database driver.
|
|
18
|
+
table.string("provider_key").unique();
|
|
19
|
+
table.string("provider");
|
|
20
|
+
table.string("provider_user_id");
|
|
21
|
+
table.integer("user_id");
|
|
22
|
+
table.string("email");
|
|
23
|
+
table.timestamps();
|
|
24
|
+
});
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
export const down = async (schema: Schema) => {
|
|
28
|
+
await schema.dropTable("oauth_accounts");
|
|
29
|
+
};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generated by Tylix
|
|
3
|
+
*
|
|
4
|
+
* Generator: AuthGenerator
|
|
5
|
+
* Version: 0.3.0
|
|
6
|
+
* Feature: OAuthAccount
|
|
7
|
+
*
|
|
8
|
+
* Do not edit this section.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
export const up = async (schema) => {
|
|
12
|
+
await schema.createTable("oauth_accounts", (table) => {
|
|
13
|
+
table.increments("id");
|
|
14
|
+
// "<provider>:<provider user id>", e.g. "github:583231". One column
|
|
15
|
+
// so the unique index works on every database driver.
|
|
16
|
+
table.string("provider_key").unique();
|
|
17
|
+
table.string("provider");
|
|
18
|
+
table.string("provider_user_id");
|
|
19
|
+
table.integer("user_id");
|
|
20
|
+
table.string("email");
|
|
21
|
+
table.timestamps();
|
|
22
|
+
});
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export const down = async (schema) => {
|
|
26
|
+
await schema.dropTable("oauth_accounts");
|
|
27
|
+
};
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generated by Tylix
|
|
3
|
+
*
|
|
4
|
+
* Generator: AuthGenerator
|
|
5
|
+
* Version: 0.3.0
|
|
6
|
+
* Feature: OAuthAccount
|
|
7
|
+
*
|
|
8
|
+
* Do not edit this section.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { Model } from "@tylix/orm";
|
|
12
|
+
|
|
13
|
+
export interface OAuthAccountAttributes {
|
|
14
|
+
id: number;
|
|
15
|
+
provider_key: string;
|
|
16
|
+
provider: string;
|
|
17
|
+
provider_user_id: string;
|
|
18
|
+
user_id: number;
|
|
19
|
+
email: string | null;
|
|
20
|
+
created_at: string;
|
|
21
|
+
updated_at: string;
|
|
22
|
+
[key: string]: unknown;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface OAuthProfile {
|
|
26
|
+
provider: string;
|
|
27
|
+
id: string;
|
|
28
|
+
email: string | null;
|
|
29
|
+
emailVerified: boolean;
|
|
30
|
+
name?: string | null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// One row per social login linked to a user ("Continue with Google /
|
|
34
|
+
// GitHub"). A user can have several; the provider's account id, not the
|
|
35
|
+
// email, is what identifies a returning user.
|
|
36
|
+
export class OAuthAccount extends Model {
|
|
37
|
+
static table = "oauth_accounts";
|
|
38
|
+
|
|
39
|
+
static fillable: string[] = [
|
|
40
|
+
"provider_key",
|
|
41
|
+
"provider",
|
|
42
|
+
"provider_user_id",
|
|
43
|
+
"user_id",
|
|
44
|
+
"email",
|
|
45
|
+
];
|
|
46
|
+
|
|
47
|
+
static keyFor(provider: string, providerUserId: string | number): string {
|
|
48
|
+
return `${provider}:${providerUserId}`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
static async findFor(provider: string, providerUserId: string | number): Promise<OAuthAccountAttributes | null> {
|
|
52
|
+
return (await this.query().where("provider_key", this.keyFor(provider, providerUserId)).first()) as OAuthAccountAttributes | null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// profile is what @tylix/auth's oauth.callback() returns.
|
|
56
|
+
static async link(userId: number, profile: OAuthProfile) {
|
|
57
|
+
return this.create({
|
|
58
|
+
provider_key: this.keyFor(profile.provider, profile.id),
|
|
59
|
+
provider: profile.provider,
|
|
60
|
+
provider_user_id: String(profile.id),
|
|
61
|
+
user_id: userId,
|
|
62
|
+
email: profile.email ?? null,
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generated by Tylix
|
|
3
|
+
*
|
|
4
|
+
* Generator: AuthGenerator
|
|
5
|
+
* Version: 0.3.0
|
|
6
|
+
* Feature: OAuthAccount
|
|
7
|
+
*
|
|
8
|
+
* Do not edit this section.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { Model } from "@tylix/orm";
|
|
12
|
+
|
|
13
|
+
// One row per social login linked to a user ("Continue with Google /
|
|
14
|
+
// GitHub"). A user can have several; the provider's account id, not the
|
|
15
|
+
// email, is what identifies a returning user.
|
|
16
|
+
export class OAuthAccount extends Model {
|
|
17
|
+
static table = "oauth_accounts";
|
|
18
|
+
|
|
19
|
+
static fillable = [
|
|
20
|
+
"provider_key",
|
|
21
|
+
"provider",
|
|
22
|
+
"provider_user_id",
|
|
23
|
+
"user_id",
|
|
24
|
+
"email",
|
|
25
|
+
];
|
|
26
|
+
|
|
27
|
+
static keyFor(provider, providerUserId) {
|
|
28
|
+
return `${provider}:${providerUserId}`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
static async findFor(provider, providerUserId) {
|
|
32
|
+
return this.query().where("provider_key", this.keyFor(provider, providerUserId)).first();
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// profile is what @tylix/auth's oauth.callback() returns.
|
|
36
|
+
static async link(userId, profile) {
|
|
37
|
+
return this.create({
|
|
38
|
+
provider_key: this.keyFor(profile.provider, profile.id),
|
|
39
|
+
provider: profile.provider,
|
|
40
|
+
provider_user_id: String(profile.id),
|
|
41
|
+
user_id: userId,
|
|
42
|
+
email: profile.email ?? null,
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -2,6 +2,7 @@ import { Model } from "@tylix/orm";
|
|
|
2
2
|
import { createHash, randomBytes } from "node:crypto";
|
|
3
3
|
|
|
4
4
|
const RESET_TOKEN_TTL_SECONDS = 60 * 60;
|
|
5
|
+
const RAW_TOKEN = /^[0-9a-f]{64}$/;
|
|
5
6
|
|
|
6
7
|
export interface PasswordResetAttributes {
|
|
7
8
|
id: number;
|
|
@@ -19,11 +20,15 @@ export class PasswordReset extends Model {
|
|
|
19
20
|
|
|
20
21
|
static fillable: string[] = ["email", "token_hash", "expires_at", "used_at"];
|
|
21
22
|
|
|
23
|
+
// Only a hash is stored, so a database leak hands out no reset links.
|
|
22
24
|
static hash(rawToken: string): string {
|
|
23
25
|
return createHash("sha256").update(rawToken).digest("hex");
|
|
24
26
|
}
|
|
25
27
|
|
|
26
28
|
static async issue(email: string) {
|
|
29
|
+
// Only the newest link works: older unused ones are retired first.
|
|
30
|
+
await this.invalidateFor(email);
|
|
31
|
+
|
|
27
32
|
const rawToken = randomBytes(32).toString("hex");
|
|
28
33
|
const expiresAt = new Date(Date.now() + RESET_TOKEN_TTL_SECONDS * 1000);
|
|
29
34
|
|
|
@@ -37,19 +42,36 @@ export class PasswordReset extends Model {
|
|
|
37
42
|
return { rawToken, expiresAt };
|
|
38
43
|
}
|
|
39
44
|
|
|
45
|
+
// One indexed lookup by hash (token_hash is unique), never a table scan.
|
|
40
46
|
static async findValid(rawToken: string, email: string): Promise<PasswordResetAttributes | null> {
|
|
41
|
-
|
|
42
|
-
const
|
|
43
|
-
const record = all.find((r) => r.token_hash === tokenHash && r.email === email);
|
|
47
|
+
if (typeof rawToken !== "string" || !RAW_TOKEN.test(rawToken)) return null;
|
|
48
|
+
const record = (await this.query().where("token_hash", this.hash(rawToken)).first()) as PasswordResetAttributes | null;
|
|
44
49
|
|
|
45
50
|
if (!record) return null;
|
|
51
|
+
if (record.email !== email) return null;
|
|
46
52
|
if (record.used_at) return null;
|
|
47
53
|
if (new Date(record.expires_at).getTime() < Date.now()) return null;
|
|
48
54
|
|
|
49
55
|
return record;
|
|
50
56
|
}
|
|
51
57
|
|
|
58
|
+
// Claims the token. Single use even when two requests race: only one
|
|
59
|
+
// UPDATE can still match the original hash. Resolves true for the winner.
|
|
60
|
+
static async consume(record: PasswordResetAttributes): Promise<boolean> {
|
|
61
|
+
const changed = await this.updateWhere(
|
|
62
|
+
{ id: record.id, token_hash: record.token_hash },
|
|
63
|
+
{ token_hash: `used:${record.token_hash}`, used_at: new Date().toISOString() },
|
|
64
|
+
);
|
|
65
|
+
return changed === 1;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
static async invalidateFor(email: string): Promise<void> {
|
|
69
|
+
const open = (await this.query().where("email", email).whereNull("used_at").get()) as PasswordResetAttributes[];
|
|
70
|
+
for (const record of open) await this.consume(record);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Kept for controllers generated before consume() existed.
|
|
52
74
|
static async markUsed(id: number) {
|
|
53
75
|
return this.update(id, { used_at: new Date().toISOString() });
|
|
54
76
|
}
|
|
55
|
-
}
|
|
77
|
+
}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Generated by Tylix
|
|
3
3
|
*
|
|
4
4
|
* Generator: AuthGenerator
|
|
5
|
-
* Version: 0.
|
|
5
|
+
* Version: 0.2.0
|
|
6
6
|
* Feature: PasswordReset
|
|
7
7
|
*
|
|
8
8
|
* Do not edit this section.
|
|
@@ -12,17 +12,22 @@ import { Model } from "@tylix/orm";
|
|
|
12
12
|
import { createHash, randomBytes } from "node:crypto";
|
|
13
13
|
|
|
14
14
|
const RESET_TOKEN_TTL_SECONDS = 60 * 60; // 1 hour
|
|
15
|
+
const RAW_TOKEN = /^[0-9a-f]{64}$/;
|
|
15
16
|
|
|
16
17
|
export class PasswordReset extends Model {
|
|
17
18
|
static table = "password_resets";
|
|
18
19
|
|
|
19
20
|
static fillable = ["email", "token_hash", "expires_at", "used_at"];
|
|
20
21
|
|
|
22
|
+
// Only a hash is stored, so a database leak hands out no reset links.
|
|
21
23
|
static hash(rawToken) {
|
|
22
24
|
return createHash("sha256").update(rawToken).digest("hex");
|
|
23
25
|
}
|
|
24
26
|
|
|
25
27
|
static async issue(email) {
|
|
28
|
+
// Only the newest link works: older unused ones are retired first.
|
|
29
|
+
await this.invalidateFor(email);
|
|
30
|
+
|
|
26
31
|
const rawToken = randomBytes(32).toString("hex");
|
|
27
32
|
const expiresAt = new Date(Date.now() + RESET_TOKEN_TTL_SECONDS * 1000);
|
|
28
33
|
|
|
@@ -36,18 +41,35 @@ export class PasswordReset extends Model {
|
|
|
36
41
|
return { rawToken, expiresAt };
|
|
37
42
|
}
|
|
38
43
|
|
|
44
|
+
// One indexed lookup by hash (token_hash is unique), never a table scan.
|
|
39
45
|
static async findValid(rawToken, email) {
|
|
40
|
-
|
|
41
|
-
const
|
|
42
|
-
const record = all.find((r) => r.token_hash === tokenHash && r.email === email);
|
|
46
|
+
if (typeof rawToken !== "string" || !RAW_TOKEN.test(rawToken)) return null;
|
|
47
|
+
const record = await this.query().where("token_hash", this.hash(rawToken)).first();
|
|
43
48
|
|
|
44
49
|
if (!record) return null;
|
|
50
|
+
if (record.email !== email) return null;
|
|
45
51
|
if (record.used_at) return null;
|
|
46
52
|
if (new Date(record.expires_at).getTime() < Date.now()) return null;
|
|
47
53
|
|
|
48
54
|
return record;
|
|
49
55
|
}
|
|
50
56
|
|
|
57
|
+
// Claims the token. Single use even when two requests race: only one
|
|
58
|
+
// UPDATE can still match the original hash. Resolves true for the winner.
|
|
59
|
+
static async consume(record) {
|
|
60
|
+
const changed = await this.updateWhere(
|
|
61
|
+
{ id: record.id, token_hash: record.token_hash },
|
|
62
|
+
{ token_hash: `used:${record.token_hash}`, used_at: new Date().toISOString() },
|
|
63
|
+
);
|
|
64
|
+
return changed === 1;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
static async invalidateFor(email) {
|
|
68
|
+
const open = await this.query().where("email", email).whereNull("used_at").get();
|
|
69
|
+
for (const record of open) await this.consume(record);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Kept for controllers generated before consume() existed.
|
|
51
73
|
static async markUsed(id) {
|
|
52
74
|
return this.update(id, { used_at: new Date().toISOString() });
|
|
53
75
|
}
|
|
@@ -1,3 +1,30 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
<
|
|
1
|
+
<!-- Email layout: tables and inline styles, so it renders the same in
|
|
2
|
+
Gmail, Outlook and Apple Mail. The first link is the action link. -->
|
|
3
|
+
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f3f2f6;padding:32px 16px;font-family:-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;">
|
|
4
|
+
<tr>
|
|
5
|
+
<td align="center">
|
|
6
|
+
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:480px;background:#ffffff;border:1px solid #dedbe6;border-radius:14px;">
|
|
7
|
+
<tr>
|
|
8
|
+
<td style="padding:28px 32px 0;">
|
|
9
|
+
<span style="display:inline-block;width:10px;height:10px;border-radius:2px;background:#0034ca;transform:skewX(-20deg);"></span>
|
|
10
|
+
<span style="font-size:16px;font-weight:700;letter-spacing:-0.02em;color:#17151c;padding-left:6px;">Tylix</span>
|
|
11
|
+
</td>
|
|
12
|
+
</tr>
|
|
13
|
+
<tr>
|
|
14
|
+
<td style="padding:24px 32px 8px;">
|
|
15
|
+
<h1 style="margin:0 0 8px;font-size:22px;line-height:28px;font-weight:650;color:#17151c;">Reset your password</h1>
|
|
16
|
+
<p style="margin:0 0 24px;font-size:14px;line-height:22px;color:#3d3a47;">Someone asked to reset the password for your account. Choose a new one below.</p>
|
|
17
|
+
<a href="{{ resetUrl }}" style="display:inline-block;padding:11px 20px;background:#0034ca;color:#ffffff;font-size:14px;font-weight:600;text-decoration:none;border-radius:9px;">Choose a new password</a>
|
|
18
|
+
</td>
|
|
19
|
+
</tr>
|
|
20
|
+
<tr>
|
|
21
|
+
<td style="padding:24px 32px 28px;">
|
|
22
|
+
<p style="margin:0 0 6px;font-size:12px;line-height:18px;color:#6b6878;">Or paste this link into your browser:</p>
|
|
23
|
+
<p style="margin:0;font-size:12px;line-height:18px;word-break:break-all;"><a href="{{ resetUrl }}" style="color:#0034ca;">{{ resetUrl }}</a></p>
|
|
24
|
+
<p style="margin:18px 0 0;font-size:12px;line-height:18px;color:#6b6878;">If you didn't ask for this, ignore this email: your password stays the same.</p>
|
|
25
|
+
</td>
|
|
26
|
+
</tr>
|
|
27
|
+
</table>
|
|
28
|
+
</td>
|
|
29
|
+
</tr>
|
|
30
|
+
</table>
|
|
@@ -1,3 +1,30 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
<
|
|
1
|
+
<!-- Email layout: tables and inline styles, so it renders the same in
|
|
2
|
+
Gmail, Outlook and Apple Mail. The first link is the action link. -->
|
|
3
|
+
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f3f2f6;padding:32px 16px;font-family:-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;">
|
|
4
|
+
<tr>
|
|
5
|
+
<td align="center">
|
|
6
|
+
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:480px;background:#ffffff;border:1px solid #dedbe6;border-radius:14px;">
|
|
7
|
+
<tr>
|
|
8
|
+
<td style="padding:28px 32px 0;">
|
|
9
|
+
<span style="display:inline-block;width:10px;height:10px;border-radius:2px;background:#0034ca;transform:skewX(-20deg);"></span>
|
|
10
|
+
<span style="font-size:16px;font-weight:700;letter-spacing:-0.02em;color:#17151c;padding-left:6px;">Tylix</span>
|
|
11
|
+
</td>
|
|
12
|
+
</tr>
|
|
13
|
+
<tr>
|
|
14
|
+
<td style="padding:24px 32px 8px;">
|
|
15
|
+
<h1 style="margin:0 0 8px;font-size:22px;line-height:28px;font-weight:650;color:#17151c;">Verify your email</h1>
|
|
16
|
+
<p style="margin:0 0 24px;font-size:14px;line-height:22px;color:#3d3a47;">Confirm this address to finish setting up your account.</p>
|
|
17
|
+
<a href="{{ verifyUrl }}" style="display:inline-block;padding:11px 20px;background:#0034ca;color:#ffffff;font-size:14px;font-weight:600;text-decoration:none;border-radius:9px;">Verify email</a>
|
|
18
|
+
</td>
|
|
19
|
+
</tr>
|
|
20
|
+
<tr>
|
|
21
|
+
<td style="padding:24px 32px 28px;">
|
|
22
|
+
<p style="margin:0 0 6px;font-size:12px;line-height:18px;color:#6b6878;">Or paste this link into your browser:</p>
|
|
23
|
+
<p style="margin:0;font-size:12px;line-height:18px;word-break:break-all;"><a href="{{ verifyUrl }}" style="color:#0034ca;">{{ verifyUrl }}</a></p>
|
|
24
|
+
<p style="margin:18px 0 0;font-size:12px;line-height:18px;color:#6b6878;">The link expires in 24 hours. If you didn't create an account, you can ignore this email.</p>
|
|
25
|
+
</td>
|
|
26
|
+
</tr>
|
|
27
|
+
</table>
|
|
28
|
+
</td>
|
|
29
|
+
</tr>
|
|
30
|
+
</table>
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// Cookie parsing and serialisation with no dependencies (no cookie-parser).
|
|
2
|
+
|
|
3
|
+
const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/
|
|
4
|
+
const COOKIE_VALUE = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/
|
|
5
|
+
|
|
6
|
+
function decode(value) {
|
|
7
|
+
try {
|
|
8
|
+
return decodeURIComponent(value)
|
|
9
|
+
} catch {
|
|
10
|
+
return value
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Every value of every cookie, in header order: { name: [value, ...] }.
|
|
16
|
+
* Browsers send the most specific path first, and a name can repeat
|
|
17
|
+
* (another path, or a cookie planted by a sibling subdomain), so security
|
|
18
|
+
* code should look at all of them rather than whichever parsed last.
|
|
19
|
+
*/
|
|
20
|
+
export function parseCookieHeaderAll(header) {
|
|
21
|
+
const out = Object.create(null)
|
|
22
|
+
if (typeof header !== 'string' || header.length === 0) return out
|
|
23
|
+
for (const pair of header.split(';')) {
|
|
24
|
+
const eq = pair.indexOf('=')
|
|
25
|
+
if (eq === -1) continue
|
|
26
|
+
const name = pair.slice(0, eq).trim()
|
|
27
|
+
if (!name || !TOKEN.test(name)) continue
|
|
28
|
+
let value = pair.slice(eq + 1).trim()
|
|
29
|
+
if (value.startsWith('"') && value.endsWith('"') && value.length >= 2) value = value.slice(1, -1)
|
|
30
|
+
;(out[name] ??= []).push(decode(value))
|
|
31
|
+
}
|
|
32
|
+
return out
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** { name: value } using the first (most specific) value of each cookie. */
|
|
36
|
+
export function parseCookieHeader(header) {
|
|
37
|
+
const all = parseCookieHeaderAll(header)
|
|
38
|
+
const out = Object.create(null)
|
|
39
|
+
for (const name in all) out[name] = all[name][0]
|
|
40
|
+
return out
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* One Set-Cookie header value. Secure-by-default: HttpOnly and
|
|
45
|
+
* SameSite=Lax unless you say otherwise; SameSite=None forces Secure;
|
|
46
|
+
* __Host- and __Secure- prefixes are checked against their rules so a
|
|
47
|
+
* misconfiguration fails loudly instead of the browser silently
|
|
48
|
+
* dropping the cookie.
|
|
49
|
+
*/
|
|
50
|
+
export function serializeCookie(name, value, options = {}) {
|
|
51
|
+
const {
|
|
52
|
+
maxAge,
|
|
53
|
+
expires,
|
|
54
|
+
path = '/',
|
|
55
|
+
domain,
|
|
56
|
+
secure = false,
|
|
57
|
+
httpOnly = true,
|
|
58
|
+
sameSite = 'lax',
|
|
59
|
+
partitioned = false,
|
|
60
|
+
priority,
|
|
61
|
+
} = options
|
|
62
|
+
|
|
63
|
+
if (!TOKEN.test(name)) throw new TypeError(`Invalid cookie name ${JSON.stringify(name)}`)
|
|
64
|
+
const encoded = COOKIE_VALUE.test(value) ? value : encodeURIComponent(value)
|
|
65
|
+
|
|
66
|
+
const site = String(sameSite).toLowerCase()
|
|
67
|
+
if (!['lax', 'strict', 'none'].includes(site)) throw new TypeError(`Invalid sameSite ${JSON.stringify(sameSite)}`)
|
|
68
|
+
const mustBeSecure = secure || site === 'none' || partitioned || name.startsWith('__Secure-') || name.startsWith('__Host-')
|
|
69
|
+
if (name.startsWith('__Host-') && (domain || path !== '/')) {
|
|
70
|
+
throw new TypeError(`${name}: __Host- cookies must have Path=/ and no Domain.`)
|
|
71
|
+
}
|
|
72
|
+
if (path && /[;\r\n]/.test(path)) throw new TypeError('Invalid cookie path')
|
|
73
|
+
if (domain && !/^\.?[a-z0-9.-]+$/i.test(domain)) throw new TypeError('Invalid cookie domain')
|
|
74
|
+
|
|
75
|
+
let cookie = `${name}=${encoded}`
|
|
76
|
+
if (maxAge != null) cookie += `; Max-Age=${Math.max(0, Math.floor(maxAge))}`
|
|
77
|
+
if (expires) cookie += `; Expires=${(expires instanceof Date ? expires : new Date(expires)).toUTCString()}`
|
|
78
|
+
if (domain) cookie += `; Domain=${domain}`
|
|
79
|
+
if (path) cookie += `; Path=${path}`
|
|
80
|
+
if (httpOnly) cookie += '; HttpOnly'
|
|
81
|
+
if (mustBeSecure) cookie += '; Secure'
|
|
82
|
+
cookie += `; SameSite=${site[0].toUpperCase()}${site.slice(1)}`
|
|
83
|
+
if (partitioned) cookie += '; Partitioned'
|
|
84
|
+
if (priority) cookie += `; Priority=${priority}`
|
|
85
|
+
return cookie
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** A Set-Cookie value that deletes the cookie (same name, path and domain). */
|
|
89
|
+
export function expireCookie(name, options = {}) {
|
|
90
|
+
return serializeCookie(name, '', { ...options, maxAge: 0, expires: new Date(0) })
|
|
91
|
+
}
|