@crossfox/elysia-auth 0.1.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 +118 -0
- package/README.md +78 -0
- package/dist/adapters/memory.d.ts +38 -0
- package/dist/adapters/memory.js +158 -0
- package/dist/cookies.d.ts +21 -0
- package/dist/cookies.js +34 -0
- package/dist/createAuth.d.ts +29 -0
- package/dist/createAuth.js +199 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +5 -0
- package/dist/oauth/providers.d.ts +14 -0
- package/dist/oauth/providers.js +118 -0
- package/dist/service.d.ts +49 -0
- package/dist/service.js +121 -0
- package/dist/types.d.ts +99 -0
- package/dist/types.js +2 -0
- package/package.json +69 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
# PolyForm Noncommercial License 1.0.0
|
|
2
|
+
|
|
3
|
+
<https://polyformproject.org/licenses/noncommercial/1.0.0>
|
|
4
|
+
|
|
5
|
+
## Acceptance
|
|
6
|
+
|
|
7
|
+
In order to get any license under these terms, you must agree to them as both
|
|
8
|
+
strict conditions and as covenants.
|
|
9
|
+
|
|
10
|
+
## Copyright License
|
|
11
|
+
|
|
12
|
+
The licensor grants you a copyright license for the software to do everything
|
|
13
|
+
you might do with the software that would otherwise infringe the licensor's
|
|
14
|
+
copyright in it for any permitted purpose. However, you may only distribute
|
|
15
|
+
the software according to [Distribution License](#distribution-license) and
|
|
16
|
+
make modifications or new works based on the software according to
|
|
17
|
+
[Changes and New Works License](#changes-and-new-works-license).
|
|
18
|
+
|
|
19
|
+
## Distribution License
|
|
20
|
+
|
|
21
|
+
The licensor grants you an additional copyright license to distribute copies
|
|
22
|
+
of the software. Your license to distribute covers distributing the software
|
|
23
|
+
with changes and new works permitted by
|
|
24
|
+
[Changes and New Works License](#changes-and-new-works-license).
|
|
25
|
+
|
|
26
|
+
## Notices
|
|
27
|
+
|
|
28
|
+
You must ensure that anyone who gets a copy of any part of the software from
|
|
29
|
+
you also gets a copy of these terms or the URL for them above, as well as
|
|
30
|
+
copies of any plain-text lines beginning with `Required Notice:` that the
|
|
31
|
+
licensor provided with the software. For example:
|
|
32
|
+
|
|
33
|
+
> Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
|
|
34
|
+
|
|
35
|
+
Required Notice: Copyright Oleksii Fursov (https://crossfox.online)
|
|
36
|
+
|
|
37
|
+
## Changes and New Works License
|
|
38
|
+
|
|
39
|
+
The licensor grants you an additional copyright license to make modifications
|
|
40
|
+
and new works based on the software for any permitted purpose.
|
|
41
|
+
|
|
42
|
+
## Patent License
|
|
43
|
+
|
|
44
|
+
The licensor grants you a patent license for the software that covers patent
|
|
45
|
+
claims the licensor can license, or becomes able to license, that you infringe
|
|
46
|
+
by using the software.
|
|
47
|
+
|
|
48
|
+
## Noncommercial Purposes
|
|
49
|
+
|
|
50
|
+
Any noncommercial purpose is a permitted purpose.
|
|
51
|
+
|
|
52
|
+
## Personal Uses
|
|
53
|
+
|
|
54
|
+
Personal use for research, experiment, and testing for the benefit of public
|
|
55
|
+
knowledge, personal study, private entertainment, hobby projects, amateur
|
|
56
|
+
pursuits, or religious observance, without any anticipated commercial
|
|
57
|
+
application, is use for a permitted purpose.
|
|
58
|
+
|
|
59
|
+
## Noncommercial Organizations
|
|
60
|
+
|
|
61
|
+
Use by any charitable organization, educational institution, public research
|
|
62
|
+
organization, public safety or health organization, environmental protection
|
|
63
|
+
organization, or government institution is use for a permitted purpose.
|
|
64
|
+
Use by a for-profit organization, or for-profit activity by a nonprofit
|
|
65
|
+
organization, is not use for a permitted purpose. The licensor may make an
|
|
66
|
+
exception for a specific organization in writing.
|
|
67
|
+
|
|
68
|
+
## Fair Use
|
|
69
|
+
|
|
70
|
+
You may have "fair use" rights for the software under the law. These terms do
|
|
71
|
+
not limit them.
|
|
72
|
+
|
|
73
|
+
## No Other Rights
|
|
74
|
+
|
|
75
|
+
These terms do not allow you to sublicense or transfer any of your licenses
|
|
76
|
+
to anyone else, or prevent the licensor from granting licenses to anyone else.
|
|
77
|
+
These terms do not imply any other licenses.
|
|
78
|
+
|
|
79
|
+
## Patent Defense
|
|
80
|
+
|
|
81
|
+
If you make any written claim that the software infringes or contributes to
|
|
82
|
+
infringement of any patent, your patent license for the software granted under
|
|
83
|
+
these terms ends immediately. If your company makes such a claim, your patent
|
|
84
|
+
license ends immediately for work on behalf of your company.
|
|
85
|
+
|
|
86
|
+
## Violations
|
|
87
|
+
|
|
88
|
+
The first time you are notified in writing that you have violated any of these
|
|
89
|
+
terms, or done anything with the software that is not licensed, your license
|
|
90
|
+
can nonetheless continue if you come into full compliance with these terms,
|
|
91
|
+
and take practical steps to correct past violations, within 32 days of
|
|
92
|
+
receiving notice. Otherwise, all your licenses end immediately.
|
|
93
|
+
|
|
94
|
+
## No Liability
|
|
95
|
+
|
|
96
|
+
***As far as the law allows, the software comes as is, without any warranty
|
|
97
|
+
or condition, and the licensor will not be liable to you for any damages
|
|
98
|
+
arising out of these terms or the use or nature of the software, under any
|
|
99
|
+
kind of legal claim.***
|
|
100
|
+
|
|
101
|
+
## Definitions
|
|
102
|
+
|
|
103
|
+
The **licensor** is the individual or entity offering these terms, and the
|
|
104
|
+
**software** is the software the licensor makes available under these terms.
|
|
105
|
+
|
|
106
|
+
**You** refers to the individual or entity agreeing to these terms.
|
|
107
|
+
|
|
108
|
+
**Your company** is any legal entity, sole proprietorship, or other kind of
|
|
109
|
+
organization that you work for, plus all organizations that have control over,
|
|
110
|
+
are under the control of, or are under common control with that organization.
|
|
111
|
+
**Control** means ownership of substantially all the assets of an entity, or
|
|
112
|
+
the power to direct its management and policies by vote, contract, or
|
|
113
|
+
otherwise. Control can be direct or indirect.
|
|
114
|
+
|
|
115
|
+
**Your licenses** are all the licenses granted to you for the software under
|
|
116
|
+
these terms.
|
|
117
|
+
|
|
118
|
+
**Use** means anything you do with the software requiring one of your licenses.
|
package/README.md
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
# @crossfox/elysia-auth
|
|
2
|
+
|
|
3
|
+
Auth for **Elysia** on Bun: **opaque** access/refresh tokens (hashed at rest), login, refresh rotation, password reset, OAuth (Google / Facebook / Instagram via Meta).
|
|
4
|
+
|
|
5
|
+
Peers: `@crossfox/elysia-kit`, `elysia`.
|
|
6
|
+
|
|
7
|
+
[](https://www.npmjs.com/package/@crossfox/elysia-auth)
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
bun add @crossfox/elysia-auth @crossfox/elysia-kit elysia
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Quick start
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { createApp } from "@crossfox/elysia-kit";
|
|
19
|
+
import {
|
|
20
|
+
createAuth,
|
|
21
|
+
createMemoryAuthStore,
|
|
22
|
+
hashPassword,
|
|
23
|
+
} from "@crossfox/elysia-auth";
|
|
24
|
+
|
|
25
|
+
const store = createMemoryAuthStore();
|
|
26
|
+
store.seedUser({
|
|
27
|
+
id: 1,
|
|
28
|
+
email: "me@example.com",
|
|
29
|
+
role: "user",
|
|
30
|
+
passwordHash: await hashPassword("secret-pass"),
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
const auth = createAuth({
|
|
34
|
+
baseUrl: "https://api.example.com",
|
|
35
|
+
users: store.users,
|
|
36
|
+
tokens: store.tokens,
|
|
37
|
+
resets: store.resets,
|
|
38
|
+
mailer: {
|
|
39
|
+
async sendPasswordReset({ to, resetUrl }) {
|
|
40
|
+
console.log("reset", to, resetUrl);
|
|
41
|
+
},
|
|
42
|
+
},
|
|
43
|
+
frontendResetUrl: "https://app.example.com/reset-password",
|
|
44
|
+
providers: {
|
|
45
|
+
google: {
|
|
46
|
+
clientId: Bun.env.GOOGLE_CLIENT_ID!,
|
|
47
|
+
clientSecret: Bun.env.GOOGLE_CLIENT_SECRET!,
|
|
48
|
+
},
|
|
49
|
+
facebook: { clientId: "...", clientSecret: "..." },
|
|
50
|
+
instagram: { clientId: "...", clientSecret: "..." }, // Meta app
|
|
51
|
+
},
|
|
52
|
+
bearer: true,
|
|
53
|
+
cookies: { enabled: true },
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
createApp({ plugins: [auth.plugin] });
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
### Routes
|
|
60
|
+
|
|
61
|
+
| Method | Path | |
|
|
62
|
+
|--------|------|--|
|
|
63
|
+
| POST | `/auth/login` | `{ login, password }` → tokens |
|
|
64
|
+
| POST | `/auth/refresh` | cookie/body refresh + CSRF header |
|
|
65
|
+
| POST | `/auth/logout` | revoke refresh |
|
|
66
|
+
| POST | `/auth/password/forgot` | `{ email }` |
|
|
67
|
+
| POST | `/auth/password/reset` | `{ token, password }` |
|
|
68
|
+
| GET | `/auth/google` … | OAuth start |
|
|
69
|
+
| GET | `/auth/*/callback` | OAuth finish |
|
|
70
|
+
|
|
71
|
+
Wire your own `UserAdapter` / `TokenAdapter` / `PasswordResetAdapter` (store `hashToken(token)` only).
|
|
72
|
+
|
|
73
|
+
## License
|
|
74
|
+
|
|
75
|
+
[PolyForm Noncommercial 1.0.0](https://polyformproject.org/licenses/noncommercial/1.0.0) —
|
|
76
|
+
`Required Notice: Copyright Oleksii Fursov`.
|
|
77
|
+
|
|
78
|
+
Commercial use: [nodepro777@gmail.com](mailto:nodepro777@gmail.com).
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { type AuthUser, type AuthUserWithPassword, type PasswordResetAdapter, type RefreshRecord, type TokenAdapter, type UserAdapter, type AuthTtlOptions } from "../types";
|
|
2
|
+
interface AccessRow {
|
|
3
|
+
tokenHash: string;
|
|
4
|
+
userId: string | number;
|
|
5
|
+
expiresAt: Date;
|
|
6
|
+
user: AuthUser;
|
|
7
|
+
}
|
|
8
|
+
interface RefreshRow extends RefreshRecord {
|
|
9
|
+
}
|
|
10
|
+
interface ResetRow {
|
|
11
|
+
tokenHash: string;
|
|
12
|
+
userId: string | number;
|
|
13
|
+
expiresAt: Date;
|
|
14
|
+
used: boolean;
|
|
15
|
+
}
|
|
16
|
+
/** In-memory adapters для тестов / локальной разработки. */
|
|
17
|
+
export declare function createMemoryAuthStore(opts?: {
|
|
18
|
+
ttl?: AuthTtlOptions;
|
|
19
|
+
users?: AuthUserWithPassword[];
|
|
20
|
+
}): {
|
|
21
|
+
users: UserAdapter;
|
|
22
|
+
tokens: TokenAdapter;
|
|
23
|
+
resets: PasswordResetAdapter;
|
|
24
|
+
/** Для тестов: добавить юзера с уже готовым passwordHash. */
|
|
25
|
+
seedUser(user: AuthUserWithPassword): void;
|
|
26
|
+
_debug: {
|
|
27
|
+
accessStore: Map<string, AccessRow>;
|
|
28
|
+
refreshStore: Map<string, RefreshRow>;
|
|
29
|
+
resetStore: Map<string, ResetRow>;
|
|
30
|
+
users: Map<string, AuthUserWithPassword>;
|
|
31
|
+
};
|
|
32
|
+
ttl: {
|
|
33
|
+
accessTtlMs: number;
|
|
34
|
+
refreshTtlMs: number;
|
|
35
|
+
resetTtlMs: number;
|
|
36
|
+
};
|
|
37
|
+
};
|
|
38
|
+
export {};
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { createOpaqueToken, hashToken, } from "../types";
|
|
2
|
+
/** In-memory adapters для тестов / локальной разработки. */
|
|
3
|
+
export function createMemoryAuthStore(opts = {}) {
|
|
4
|
+
const accessTtlMs = opts.ttl?.accessTtlMs ?? 15 * 60_000;
|
|
5
|
+
const refreshTtlMs = opts.ttl?.refreshTtlMs ?? 30 * 24 * 60 * 60_000;
|
|
6
|
+
const resetTtlMs = opts.ttl?.resetTtlMs ?? 60 * 60_000;
|
|
7
|
+
const users = new Map();
|
|
8
|
+
const byEmail = new Map();
|
|
9
|
+
const byLogin = new Map();
|
|
10
|
+
const oauth = new Map(); // provider:accountId → userId
|
|
11
|
+
for (const u of opts.users ?? []) {
|
|
12
|
+
const id = String(u.id);
|
|
13
|
+
users.set(id, u);
|
|
14
|
+
if (u.email) {
|
|
15
|
+
byEmail.set(u.email.toLowerCase(), id);
|
|
16
|
+
byLogin.set(u.email.toLowerCase(), id);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
const accessStore = new Map();
|
|
20
|
+
const refreshStore = new Map();
|
|
21
|
+
const resetStore = new Map();
|
|
22
|
+
const userAdapter = {
|
|
23
|
+
async findByLogin(login) {
|
|
24
|
+
const id = byLogin.get(login.toLowerCase());
|
|
25
|
+
return id ? users.get(id) ?? null : null;
|
|
26
|
+
},
|
|
27
|
+
async findById(id) {
|
|
28
|
+
const u = users.get(String(id));
|
|
29
|
+
if (!u)
|
|
30
|
+
return null;
|
|
31
|
+
const { passwordHash: _, ...rest } = u;
|
|
32
|
+
return rest;
|
|
33
|
+
},
|
|
34
|
+
async findByEmail(email) {
|
|
35
|
+
const id = byEmail.get(email.toLowerCase());
|
|
36
|
+
if (!id)
|
|
37
|
+
return null;
|
|
38
|
+
const u = users.get(id);
|
|
39
|
+
const { passwordHash: _, ...rest } = u;
|
|
40
|
+
return rest;
|
|
41
|
+
},
|
|
42
|
+
async updatePassword(userId, passwordHash) {
|
|
43
|
+
const u = users.get(String(userId));
|
|
44
|
+
if (!u)
|
|
45
|
+
return;
|
|
46
|
+
u.passwordHash = passwordHash;
|
|
47
|
+
},
|
|
48
|
+
async findOrCreateFromOAuth(profile) {
|
|
49
|
+
const key = `${profile.provider}:${profile.providerAccountId}`;
|
|
50
|
+
const existing = oauth.get(key);
|
|
51
|
+
if (existing) {
|
|
52
|
+
const u = users.get(existing);
|
|
53
|
+
const { passwordHash: _, ...rest } = u;
|
|
54
|
+
return rest;
|
|
55
|
+
}
|
|
56
|
+
const id = `oauth_${users.size + 1}`;
|
|
57
|
+
const user = {
|
|
58
|
+
id,
|
|
59
|
+
email: profile.email ?? null,
|
|
60
|
+
name: profile.name ?? null,
|
|
61
|
+
role: "user",
|
|
62
|
+
passwordHash: "",
|
|
63
|
+
};
|
|
64
|
+
users.set(id, user);
|
|
65
|
+
oauth.set(key, id);
|
|
66
|
+
if (user.email) {
|
|
67
|
+
byEmail.set(user.email.toLowerCase(), id);
|
|
68
|
+
byLogin.set(user.email.toLowerCase(), id);
|
|
69
|
+
}
|
|
70
|
+
const { passwordHash: _, ...rest } = user;
|
|
71
|
+
return rest;
|
|
72
|
+
},
|
|
73
|
+
};
|
|
74
|
+
function issue(type, user, ttl) {
|
|
75
|
+
const token = createOpaqueToken(type === "access" ? "at" : "rt");
|
|
76
|
+
const tokenHash = hashToken(token);
|
|
77
|
+
const expiresAt = new Date(Date.now() + ttl);
|
|
78
|
+
if (type === "access") {
|
|
79
|
+
accessStore.set(tokenHash, { tokenHash, userId: user.id, expiresAt, user });
|
|
80
|
+
}
|
|
81
|
+
else {
|
|
82
|
+
refreshStore.set(tokenHash, {
|
|
83
|
+
tokenHash,
|
|
84
|
+
userId: user.id,
|
|
85
|
+
expiresAt,
|
|
86
|
+
revoked: false,
|
|
87
|
+
role: user.role,
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
return { token, tokenHash, expiresAt };
|
|
91
|
+
}
|
|
92
|
+
const tokenAdapter = {
|
|
93
|
+
async issueTokens(user, _meta) {
|
|
94
|
+
return {
|
|
95
|
+
access: issue("access", user, accessTtlMs),
|
|
96
|
+
refresh: issue("refresh", user, refreshTtlMs),
|
|
97
|
+
};
|
|
98
|
+
},
|
|
99
|
+
async verifyAccessToken(token, meta) {
|
|
100
|
+
const row = accessStore.get(meta.tokenHash || hashToken(token));
|
|
101
|
+
if (!row)
|
|
102
|
+
return null;
|
|
103
|
+
if (row.expiresAt.getTime() <= Date.now()) {
|
|
104
|
+
accessStore.delete(row.tokenHash);
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
return row.user;
|
|
108
|
+
},
|
|
109
|
+
async findRefresh(tokenHash) {
|
|
110
|
+
return refreshStore.get(tokenHash) ?? null;
|
|
111
|
+
},
|
|
112
|
+
async revokeRefresh(tokenHash) {
|
|
113
|
+
const row = refreshStore.get(tokenHash);
|
|
114
|
+
if (row)
|
|
115
|
+
row.revoked = true;
|
|
116
|
+
},
|
|
117
|
+
async revokeAllForUser(userId) {
|
|
118
|
+
for (const row of refreshStore.values()) {
|
|
119
|
+
if (String(row.userId) === String(userId))
|
|
120
|
+
row.revoked = true;
|
|
121
|
+
}
|
|
122
|
+
for (const [k, row] of accessStore) {
|
|
123
|
+
if (String(row.userId) === String(userId))
|
|
124
|
+
accessStore.delete(k);
|
|
125
|
+
}
|
|
126
|
+
},
|
|
127
|
+
};
|
|
128
|
+
const resetAdapter = {
|
|
129
|
+
async create(userId, tokenHash, expiresAt) {
|
|
130
|
+
resetStore.set(tokenHash, { tokenHash, userId, expiresAt, used: false });
|
|
131
|
+
},
|
|
132
|
+
async consume(tokenHash) {
|
|
133
|
+
const row = resetStore.get(tokenHash);
|
|
134
|
+
if (!row || row.used)
|
|
135
|
+
return null;
|
|
136
|
+
if (row.expiresAt.getTime() <= Date.now())
|
|
137
|
+
return null;
|
|
138
|
+
row.used = true;
|
|
139
|
+
return { userId: row.userId };
|
|
140
|
+
},
|
|
141
|
+
};
|
|
142
|
+
return {
|
|
143
|
+
users: userAdapter,
|
|
144
|
+
tokens: tokenAdapter,
|
|
145
|
+
resets: resetAdapter,
|
|
146
|
+
/** Для тестов: добавить юзера с уже готовым passwordHash. */
|
|
147
|
+
seedUser(user) {
|
|
148
|
+
const id = String(user.id);
|
|
149
|
+
users.set(id, user);
|
|
150
|
+
if (user.email) {
|
|
151
|
+
byEmail.set(user.email.toLowerCase(), id);
|
|
152
|
+
byLogin.set(user.email.toLowerCase(), id);
|
|
153
|
+
}
|
|
154
|
+
},
|
|
155
|
+
_debug: { accessStore, refreshStore, resetStore, users },
|
|
156
|
+
ttl: { accessTtlMs, refreshTtlMs, resetTtlMs },
|
|
157
|
+
};
|
|
158
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { AuthCookieOptions, IssuedTokenPair } from "./types";
|
|
2
|
+
export declare const REFRESH_COOKIE = "refresh_token";
|
|
3
|
+
export declare const ACCESS_COOKIE = "access_token";
|
|
4
|
+
export declare const CSRF_COOKIE = "csrf_token";
|
|
5
|
+
export declare const CSRF_HEADER = "x-csrf-token";
|
|
6
|
+
export declare function cookieBase(opts: AuthCookieOptions | undefined, maxAge: number): {
|
|
7
|
+
httpOnly: boolean;
|
|
8
|
+
path: string;
|
|
9
|
+
sameSite: "strict" | "lax" | "none";
|
|
10
|
+
secure: boolean;
|
|
11
|
+
domain: string | undefined;
|
|
12
|
+
maxAge: number;
|
|
13
|
+
};
|
|
14
|
+
export declare function applyAuthCookies(cookie: Record<string, {
|
|
15
|
+
set: (v: unknown, o?: object) => void;
|
|
16
|
+
remove?: () => void;
|
|
17
|
+
}>, opts: AuthCookieOptions | undefined, pair: IssuedTokenPair, csrf: string): void;
|
|
18
|
+
export declare function clearAuthCookies(cookie: Record<string, {
|
|
19
|
+
set: (v: unknown, o?: object) => void;
|
|
20
|
+
remove?: () => void;
|
|
21
|
+
}>, opts: AuthCookieOptions | undefined): void;
|
package/dist/cookies.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
export const REFRESH_COOKIE = "refresh_token";
|
|
2
|
+
export const ACCESS_COOKIE = "access_token";
|
|
3
|
+
export const CSRF_COOKIE = "csrf_token";
|
|
4
|
+
export const CSRF_HEADER = "x-csrf-token";
|
|
5
|
+
export function cookieBase(opts, maxAge) {
|
|
6
|
+
return {
|
|
7
|
+
httpOnly: true,
|
|
8
|
+
path: opts?.path ?? "/",
|
|
9
|
+
sameSite: opts?.sameSite ?? "lax",
|
|
10
|
+
secure: opts?.secure ?? process.env.NODE_ENV === "production",
|
|
11
|
+
domain: opts?.domain,
|
|
12
|
+
maxAge,
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
export function applyAuthCookies(cookie, opts, pair, csrf) {
|
|
16
|
+
const accessName = opts?.accessName ?? ACCESS_COOKIE;
|
|
17
|
+
const refreshName = opts?.refreshName ?? REFRESH_COOKIE;
|
|
18
|
+
const csrfName = opts?.csrfName ?? CSRF_COOKIE;
|
|
19
|
+
const accessMax = Math.max(60, Math.floor((pair.access.expiresAt.getTime() - Date.now()) / 1000));
|
|
20
|
+
const refreshMax = Math.max(60, Math.floor((pair.refresh.expiresAt.getTime() - Date.now()) / 1000));
|
|
21
|
+
cookie[accessName]?.set(pair.access.token, cookieBase(opts, accessMax));
|
|
22
|
+
cookie[refreshName]?.set(pair.refresh.token, cookieBase(opts, refreshMax));
|
|
23
|
+
// CSRF readable by JS for double-submit
|
|
24
|
+
cookie[csrfName]?.set(csrf, { ...cookieBase(opts, refreshMax), httpOnly: false });
|
|
25
|
+
}
|
|
26
|
+
export function clearAuthCookies(cookie, opts) {
|
|
27
|
+
const accessName = opts?.accessName ?? ACCESS_COOKIE;
|
|
28
|
+
const refreshName = opts?.refreshName ?? REFRESH_COOKIE;
|
|
29
|
+
const csrfName = opts?.csrfName ?? CSRF_COOKIE;
|
|
30
|
+
const empty = cookieBase(opts, 0);
|
|
31
|
+
cookie[accessName]?.set("", empty);
|
|
32
|
+
cookie[refreshName]?.set("", empty);
|
|
33
|
+
cookie[csrfName]?.set("", { ...empty, httpOnly: false });
|
|
34
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { Elysia } from "elysia";
|
|
2
|
+
import { AuthService, type AuthServiceOptions } from "./service";
|
|
3
|
+
import type { AuthCookieOptions, AuthProviderId, OAuthProviderCredentials } from "./types";
|
|
4
|
+
export interface CreateAuthOptions extends AuthServiceOptions {
|
|
5
|
+
baseUrl: string;
|
|
6
|
+
prefix?: string;
|
|
7
|
+
cookies?: AuthCookieOptions;
|
|
8
|
+
/** Bearer verify на все роуты кроме isPublic. */
|
|
9
|
+
bearer?: boolean;
|
|
10
|
+
/** CSRF double-submit для refresh (default true если cookies). */
|
|
11
|
+
csrf?: boolean;
|
|
12
|
+
providers?: {
|
|
13
|
+
google?: OAuthProviderCredentials;
|
|
14
|
+
facebook?: OAuthProviderCredentials;
|
|
15
|
+
instagram?: OAuthProviderCredentials;
|
|
16
|
+
};
|
|
17
|
+
oauthResponseMode?: "json" | "redirect" | "cookies";
|
|
18
|
+
successRedirect?: string;
|
|
19
|
+
failureRedirect?: string;
|
|
20
|
+
}
|
|
21
|
+
export interface AuthInstance {
|
|
22
|
+
service: AuthService;
|
|
23
|
+
plugin: Elysia;
|
|
24
|
+
providers: AuthProviderId[];
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Полный auth: login / refresh / logout / password reset / OAuth + Bearer.
|
|
28
|
+
*/
|
|
29
|
+
export declare function createAuth(opts: CreateAuthOptions): AuthInstance;
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import { Elysia } from "elysia";
|
|
2
|
+
import { generateCodeVerifier, generateState } from "arctic";
|
|
3
|
+
import { clientIp, error, hashToken, routeMacros, storage, } from "@crossfox/elysia-kit";
|
|
4
|
+
import { AuthService } from "./service";
|
|
5
|
+
import { applyAuthCookies, clearAuthCookies, cookieBase, CSRF_COOKIE, CSRF_HEADER, REFRESH_COOKIE, } from "./cookies";
|
|
6
|
+
import { buildFacebook, buildGoogle, buildInstagram, } from "./oauth/providers";
|
|
7
|
+
const STATE_COOKIE = "oauth_state";
|
|
8
|
+
const PKCE_COOKIE = "oauth_pkce";
|
|
9
|
+
function joinUrl(base, path) {
|
|
10
|
+
return `${base.replace(/\/$/, "")}${path.startsWith("/") ? path : `/${path}`}`;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Полный auth: login / refresh / logout / password reset / OAuth + Bearer.
|
|
14
|
+
*/
|
|
15
|
+
export function createAuth(opts) {
|
|
16
|
+
const service = new AuthService(opts);
|
|
17
|
+
const prefix = opts.prefix ?? "/auth";
|
|
18
|
+
const baseUrl = opts.baseUrl.replace(/\/$/, "");
|
|
19
|
+
const cookiesCfg = opts.cookies ?? { enabled: true };
|
|
20
|
+
const useCsrf = opts.csrf ?? Boolean(cookiesCfg.enabled !== false);
|
|
21
|
+
const oauthMode = opts.oauthResponseMode ?? "json";
|
|
22
|
+
const clients = new Map();
|
|
23
|
+
const register = (id, build, creds) => {
|
|
24
|
+
if (!creds)
|
|
25
|
+
return;
|
|
26
|
+
const redirectUri = creds.redirectUri ?? joinUrl(baseUrl, `${prefix}/${id}/callback`);
|
|
27
|
+
clients.set(id, build(redirectUri));
|
|
28
|
+
};
|
|
29
|
+
register("google", (u) => buildGoogle(opts.providers.google, u), opts.providers?.google);
|
|
30
|
+
register("facebook", (u) => buildFacebook(opts.providers.facebook, u), opts.providers?.facebook);
|
|
31
|
+
register("instagram", (u) => buildInstagram(opts.providers.instagram, u), opts.providers?.instagram);
|
|
32
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
33
|
+
let plugin = new Elysia({ name: "crossfox-elysia-auth" }).use(routeMacros);
|
|
34
|
+
if (opts.bearer !== false) {
|
|
35
|
+
plugin = plugin
|
|
36
|
+
.derive({ as: "global" }, async ({ request, server }) => {
|
|
37
|
+
const meta = storage.getStore() ?? {
|
|
38
|
+
userAgent: request.headers.get("user-agent") ?? null,
|
|
39
|
+
ip: null,
|
|
40
|
+
url: request.url ?? null,
|
|
41
|
+
};
|
|
42
|
+
meta.ip = clientIp(request, server);
|
|
43
|
+
return { meta };
|
|
44
|
+
})
|
|
45
|
+
.onBeforeHandle({ as: "global" }, async (context) => {
|
|
46
|
+
const c = context;
|
|
47
|
+
c.meta.method = c.request.method ?? null;
|
|
48
|
+
c.meta.route = c.route ?? null;
|
|
49
|
+
if (c.skipAuthVerify === true) {
|
|
50
|
+
c.auth = null;
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
const header = c.headers.authorization ?? c.request.headers.get("authorization") ?? "";
|
|
54
|
+
const m = /^Bearer\s+(.+)$/i.exec(header);
|
|
55
|
+
if (!m?.[1])
|
|
56
|
+
error(401, "Unauthorized");
|
|
57
|
+
const raw = m[1].trim();
|
|
58
|
+
c.meta.tokenHash = hashToken(raw);
|
|
59
|
+
const user = await service.verifyAccess(raw, {
|
|
60
|
+
ip: c.meta.ip ?? null,
|
|
61
|
+
userAgent: c.meta.userAgent ?? null,
|
|
62
|
+
});
|
|
63
|
+
c.auth = user;
|
|
64
|
+
c.meta.userId = typeof user.id === "number" ? user.id : Number(user.id) || undefined;
|
|
65
|
+
c.meta.role = user.role;
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
const metaFrom = (request, server) => ({
|
|
69
|
+
ip: clientIp(request, server),
|
|
70
|
+
userAgent: request.headers.get("user-agent"),
|
|
71
|
+
});
|
|
72
|
+
plugin = plugin
|
|
73
|
+
.post(`${prefix}/login`, async ({ body, request, server, cookie }) => {
|
|
74
|
+
const login = String(body?.login ?? body?.email ?? "");
|
|
75
|
+
const password = String(body?.password ?? "");
|
|
76
|
+
const { user, tokens } = await service.login(login, password, metaFrom(request, server));
|
|
77
|
+
const csrf = service.issueCsrfToken();
|
|
78
|
+
if (cookiesCfg.enabled !== false) {
|
|
79
|
+
applyAuthCookies(cookie, cookiesCfg, tokens, csrf);
|
|
80
|
+
}
|
|
81
|
+
return {
|
|
82
|
+
ok: true,
|
|
83
|
+
user,
|
|
84
|
+
access_token: tokens.access.token,
|
|
85
|
+
refresh_token: tokens.refresh.token,
|
|
86
|
+
expires_at: tokens.access.expiresAt.toISOString(),
|
|
87
|
+
csrf_token: csrf,
|
|
88
|
+
};
|
|
89
|
+
}, { isPublic: true })
|
|
90
|
+
.post(`${prefix}/refresh`, async ({ body, request, server, cookie, headers }) => {
|
|
91
|
+
const fromCookie = cookie[cookiesCfg.refreshName ?? REFRESH_COOKIE]?.value;
|
|
92
|
+
const refreshToken = String(body?.refresh_token ?? fromCookie ?? "");
|
|
93
|
+
if (!refreshToken)
|
|
94
|
+
error(401, "Missing refresh token");
|
|
95
|
+
if (useCsrf && cookiesCfg.enabled !== false) {
|
|
96
|
+
const csrfCookie = String(cookie[cookiesCfg.csrfName ?? CSRF_COOKIE]?.value ?? "");
|
|
97
|
+
const csrfHeader = String(headers[CSRF_HEADER] ?? request.headers.get(CSRF_HEADER) ?? "");
|
|
98
|
+
if (!csrfCookie || !csrfHeader || csrfCookie !== csrfHeader) {
|
|
99
|
+
error(403, "Invalid CSRF token");
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
const { user, tokens } = await service.refresh(refreshToken, metaFrom(request, server));
|
|
103
|
+
const csrf = useCsrf
|
|
104
|
+
? String(cookie[cookiesCfg.csrfName ?? CSRF_COOKIE]?.value ?? "") || service.issueCsrfToken()
|
|
105
|
+
: service.issueCsrfToken();
|
|
106
|
+
if (cookiesCfg.enabled !== false) {
|
|
107
|
+
applyAuthCookies(cookie, cookiesCfg, tokens, csrf);
|
|
108
|
+
}
|
|
109
|
+
return {
|
|
110
|
+
ok: true,
|
|
111
|
+
user,
|
|
112
|
+
access_token: tokens.access.token,
|
|
113
|
+
refresh_token: tokens.refresh.token,
|
|
114
|
+
expires_at: tokens.access.expiresAt.toISOString(),
|
|
115
|
+
csrf_token: csrf,
|
|
116
|
+
};
|
|
117
|
+
}, { isPublic: true })
|
|
118
|
+
.post(`${prefix}/logout`, async ({ body, cookie }) => {
|
|
119
|
+
const fromCookie = cookie[cookiesCfg.refreshName ?? REFRESH_COOKIE]?.value;
|
|
120
|
+
await service.logout(String(body?.refresh_token ?? fromCookie ?? "") || null);
|
|
121
|
+
clearAuthCookies(cookie, cookiesCfg);
|
|
122
|
+
return { ok: true };
|
|
123
|
+
}, { isPublic: true })
|
|
124
|
+
.post(`${prefix}/password/forgot`, async ({ body }) => {
|
|
125
|
+
const email = String(body?.email ?? "");
|
|
126
|
+
return service.requestPasswordReset(email);
|
|
127
|
+
}, { isPublic: true })
|
|
128
|
+
.post(`${prefix}/password/reset`, async ({ body }) => {
|
|
129
|
+
return service.resetPassword(String(body?.token ?? ""), String(body?.password ?? ""));
|
|
130
|
+
}, { isPublic: true });
|
|
131
|
+
for (const [id, client] of clients) {
|
|
132
|
+
plugin = plugin
|
|
133
|
+
.get(`${prefix}/${id}`, ({ cookie, redirect, set }) => {
|
|
134
|
+
const state = generateState();
|
|
135
|
+
cookie[STATE_COOKIE].set(state, cookieBase(cookiesCfg, 600));
|
|
136
|
+
let codeVerifier = null;
|
|
137
|
+
if (client.usesPkce) {
|
|
138
|
+
codeVerifier = generateCodeVerifier();
|
|
139
|
+
cookie[PKCE_COOKIE].set(codeVerifier, cookieBase(cookiesCfg, 600));
|
|
140
|
+
}
|
|
141
|
+
const url = client.createAuthorizationURL(state, codeVerifier);
|
|
142
|
+
set.redirect = url.toString();
|
|
143
|
+
return redirect(url.toString());
|
|
144
|
+
}, { isPublic: true })
|
|
145
|
+
.get(`${prefix}/${id}/callback`, async ({ query, cookie, request, server, redirect, set }) => {
|
|
146
|
+
try {
|
|
147
|
+
const code = String(query.code ?? "");
|
|
148
|
+
const state = String(query.state ?? "");
|
|
149
|
+
const storedState = cookie[STATE_COOKIE]?.value;
|
|
150
|
+
const codeVerifier = client.usesPkce
|
|
151
|
+
? String(cookie[PKCE_COOKIE]?.value ?? "")
|
|
152
|
+
: null;
|
|
153
|
+
cookie[STATE_COOKIE]?.remove?.();
|
|
154
|
+
cookie[PKCE_COOKIE]?.remove?.();
|
|
155
|
+
if (!code || !state || !storedState || state !== storedState) {
|
|
156
|
+
error(400, "Invalid OAuth state");
|
|
157
|
+
}
|
|
158
|
+
const providerAccess = await client.validateAuthorizationCode(code, client.usesPkce ? codeVerifier : null);
|
|
159
|
+
const profile = await client.fetchProfile(providerAccess);
|
|
160
|
+
const { user, tokens } = await service.loginWithOAuth(profile, metaFrom(request, server));
|
|
161
|
+
const csrf = service.issueCsrfToken();
|
|
162
|
+
if (cookiesCfg.enabled !== false || oauthMode === "cookies") {
|
|
163
|
+
applyAuthCookies(cookie, cookiesCfg, tokens, csrf);
|
|
164
|
+
}
|
|
165
|
+
if (oauthMode === "redirect") {
|
|
166
|
+
if (!opts.successRedirect)
|
|
167
|
+
error(500, "successRedirect required");
|
|
168
|
+
const u = new URL(opts.successRedirect, baseUrl);
|
|
169
|
+
u.searchParams.set("access_token", tokens.access.token);
|
|
170
|
+
set.redirect = u.toString();
|
|
171
|
+
return redirect(u.toString());
|
|
172
|
+
}
|
|
173
|
+
if (oauthMode === "cookies") {
|
|
174
|
+
return { ok: true, user, csrf_token: csrf };
|
|
175
|
+
}
|
|
176
|
+
return {
|
|
177
|
+
ok: true,
|
|
178
|
+
user,
|
|
179
|
+
access_token: tokens.access.token,
|
|
180
|
+
refresh_token: tokens.refresh.token,
|
|
181
|
+
expires_at: tokens.access.expiresAt.toISOString(),
|
|
182
|
+
csrf_token: csrf,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
catch (e) {
|
|
186
|
+
if (opts.failureRedirect) {
|
|
187
|
+
set.redirect = opts.failureRedirect;
|
|
188
|
+
return redirect(opts.failureRedirect);
|
|
189
|
+
}
|
|
190
|
+
throw e;
|
|
191
|
+
}
|
|
192
|
+
}, { isPublic: true });
|
|
193
|
+
}
|
|
194
|
+
return {
|
|
195
|
+
service,
|
|
196
|
+
plugin: plugin,
|
|
197
|
+
providers: [...clients.keys()],
|
|
198
|
+
};
|
|
199
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { createAuth, type CreateAuthOptions, type AuthInstance } from "./createAuth";
|
|
2
|
+
export { AuthService, type AuthServiceOptions } from "./service";
|
|
3
|
+
export { createMemoryAuthStore } from "./adapters/memory";
|
|
4
|
+
export { REFRESH_COOKIE, ACCESS_COOKIE, CSRF_COOKIE, CSRF_HEADER, applyAuthCookies, clearAuthCookies, } from "./cookies";
|
|
5
|
+
export type { AuthProviderId, AuthUser, AuthUserWithPassword, OAuthProfile, UserAdapter, TokenAdapter, PasswordResetAdapter, Mailer, IssuedToken, IssuedTokenPair, RefreshRecord, RequestMetaLite, OAuthProviderCredentials, AuthCookieOptions, AuthTtlOptions, } from "./types";
|
|
6
|
+
export { createOpaqueToken, hashToken, hashPassword, verifyPassword, } from "./types";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { createAuth } from "./createAuth";
|
|
2
|
+
export { AuthService } from "./service";
|
|
3
|
+
export { createMemoryAuthStore } from "./adapters/memory";
|
|
4
|
+
export { REFRESH_COOKIE, ACCESS_COOKIE, CSRF_COOKIE, CSRF_HEADER, applyAuthCookies, clearAuthCookies, } from "./cookies";
|
|
5
|
+
export { createOpaqueToken, hashToken, hashPassword, verifyPassword, } from "./types";
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import * as arctic from "arctic";
|
|
2
|
+
import type { AuthProviderId, OAuthProfile, OAuthProviderCredentials } from "../types";
|
|
3
|
+
export interface ProviderClient {
|
|
4
|
+
id: AuthProviderId;
|
|
5
|
+
usesPkce: boolean;
|
|
6
|
+
createAuthorizationURL(state: string, codeVerifier: string | null): URL;
|
|
7
|
+
validateAuthorizationCode(code: string, codeVerifier: string | null): Promise<string>;
|
|
8
|
+
fetchProfile(accessToken: string): Promise<OAuthProfile>;
|
|
9
|
+
}
|
|
10
|
+
export declare function buildGoogle(creds: OAuthProviderCredentials, redirectUri: string): ProviderClient;
|
|
11
|
+
export declare function buildFacebook(creds: OAuthProviderCredentials, redirectUri: string, providerId?: AuthProviderId): ProviderClient;
|
|
12
|
+
/** Instagram через Meta App (Facebook Login + Graph). */
|
|
13
|
+
export declare function buildInstagram(creds: OAuthProviderCredentials, redirectUri: string): ProviderClient;
|
|
14
|
+
export { arctic };
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import * as arctic from "arctic";
|
|
2
|
+
function requireCreds(id, c) {
|
|
3
|
+
if (!c?.clientId || !c?.clientSecret) {
|
|
4
|
+
throw new Error(`@crossfox/elysia-auth: provider "${id}" missing clientId/clientSecret`);
|
|
5
|
+
}
|
|
6
|
+
return c;
|
|
7
|
+
}
|
|
8
|
+
export function buildGoogle(creds, redirectUri) {
|
|
9
|
+
const c = requireCreds("google", creds);
|
|
10
|
+
const google = new arctic.Google(c.clientId, c.clientSecret, redirectUri);
|
|
11
|
+
const scopes = c.scopes ?? ["openid", "profile", "email"];
|
|
12
|
+
return {
|
|
13
|
+
id: "google",
|
|
14
|
+
usesPkce: true,
|
|
15
|
+
createAuthorizationURL(state, codeVerifier) {
|
|
16
|
+
if (!codeVerifier)
|
|
17
|
+
throw new Error("google requires PKCE code_verifier");
|
|
18
|
+
return google.createAuthorizationURL(state, codeVerifier, scopes);
|
|
19
|
+
},
|
|
20
|
+
async validateAuthorizationCode(code, codeVerifier) {
|
|
21
|
+
if (!codeVerifier)
|
|
22
|
+
throw new Error("google requires PKCE code_verifier");
|
|
23
|
+
const tokens = await google.validateAuthorizationCode(code, codeVerifier);
|
|
24
|
+
return tokens.accessToken();
|
|
25
|
+
},
|
|
26
|
+
async fetchProfile(accessToken) {
|
|
27
|
+
const res = await fetch("https://openidconnect.googleapis.com/v1/userinfo", {
|
|
28
|
+
headers: { Authorization: `Bearer ${accessToken}` },
|
|
29
|
+
});
|
|
30
|
+
if (!res.ok)
|
|
31
|
+
throw new Error(`Google userinfo failed: ${res.status}`);
|
|
32
|
+
const u = (await res.json());
|
|
33
|
+
return {
|
|
34
|
+
provider: "google",
|
|
35
|
+
providerAccountId: String(u.sub),
|
|
36
|
+
email: u.email ?? null,
|
|
37
|
+
name: u.name ?? null,
|
|
38
|
+
avatarUrl: u.picture ?? null,
|
|
39
|
+
raw: u,
|
|
40
|
+
};
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
export function buildFacebook(creds, redirectUri, providerId = "facebook") {
|
|
45
|
+
const c = requireCreds(providerId, creds);
|
|
46
|
+
const facebook = new arctic.Facebook(c.clientId, c.clientSecret, redirectUri);
|
|
47
|
+
const scopes = c.scopes ?? ["email", "public_profile"];
|
|
48
|
+
return {
|
|
49
|
+
id: providerId,
|
|
50
|
+
usesPkce: false,
|
|
51
|
+
createAuthorizationURL(state) {
|
|
52
|
+
return facebook.createAuthorizationURL(state, scopes);
|
|
53
|
+
},
|
|
54
|
+
async validateAuthorizationCode(code) {
|
|
55
|
+
const tokens = await facebook.validateAuthorizationCode(code);
|
|
56
|
+
return tokens.accessToken();
|
|
57
|
+
},
|
|
58
|
+
async fetchProfile(accessToken) {
|
|
59
|
+
const params = new URLSearchParams({
|
|
60
|
+
access_token: accessToken,
|
|
61
|
+
fields: "id,name,email,picture.type(large)",
|
|
62
|
+
});
|
|
63
|
+
const res = await fetch(`https://graph.facebook.com/me?${params}`);
|
|
64
|
+
if (!res.ok)
|
|
65
|
+
throw new Error(`Facebook /me failed: ${res.status}`);
|
|
66
|
+
const u = (await res.json());
|
|
67
|
+
return {
|
|
68
|
+
provider: providerId,
|
|
69
|
+
providerAccountId: String(u.id),
|
|
70
|
+
email: u.email ?? null,
|
|
71
|
+
name: u.name ?? null,
|
|
72
|
+
avatarUrl: u.picture?.data?.url ?? null,
|
|
73
|
+
raw: u,
|
|
74
|
+
};
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/** Instagram через Meta App (Facebook Login + Graph). */
|
|
79
|
+
export function buildInstagram(creds, redirectUri) {
|
|
80
|
+
const c = requireCreds("instagram", creds);
|
|
81
|
+
const scopes = c.scopes ?? ["email", "public_profile"];
|
|
82
|
+
const base = buildFacebook({ ...c, scopes }, redirectUri, "instagram");
|
|
83
|
+
return {
|
|
84
|
+
...base,
|
|
85
|
+
async fetchProfile(accessToken) {
|
|
86
|
+
try {
|
|
87
|
+
const pagesRes = await fetch(`https://graph.facebook.com/v21.0/me/accounts?access_token=${encodeURIComponent(accessToken)}`);
|
|
88
|
+
if (pagesRes.ok) {
|
|
89
|
+
const pages = (await pagesRes.json());
|
|
90
|
+
const page = pages.data?.[0];
|
|
91
|
+
if (page?.id) {
|
|
92
|
+
const igRes = await fetch(`https://graph.facebook.com/v21.0/${page.id}?fields=instagram_business_account{id,username,profile_picture_url}&access_token=${encodeURIComponent(page.access_token ?? accessToken)}`);
|
|
93
|
+
if (igRes.ok) {
|
|
94
|
+
const ig = (await igRes.json());
|
|
95
|
+
const acc = ig.instagram_business_account;
|
|
96
|
+
if (acc?.id) {
|
|
97
|
+
return {
|
|
98
|
+
provider: "instagram",
|
|
99
|
+
providerAccountId: String(acc.id),
|
|
100
|
+
email: null,
|
|
101
|
+
name: acc.username ?? null,
|
|
102
|
+
avatarUrl: acc.profile_picture_url ?? null,
|
|
103
|
+
raw: ig,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
/* fall through */
|
|
112
|
+
}
|
|
113
|
+
const fb = await base.fetchProfile(accessToken);
|
|
114
|
+
return { ...fb, provider: "instagram" };
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
export { arctic };
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { type AuthUser, type IssuedTokenPair, type Mailer, type OAuthProfile, type PasswordResetAdapter, type RequestMetaLite, type TokenAdapter, type UserAdapter, type AuthTtlOptions } from "./types";
|
|
2
|
+
export interface AuthServiceOptions {
|
|
3
|
+
users: UserAdapter;
|
|
4
|
+
tokens: TokenAdapter;
|
|
5
|
+
resets?: PasswordResetAdapter;
|
|
6
|
+
mailer?: Mailer;
|
|
7
|
+
ttl?: AuthTtlOptions;
|
|
8
|
+
/**
|
|
9
|
+
* Базовый URL фронта для ссылки сброса:
|
|
10
|
+
* `{frontendResetUrl}?token=...`
|
|
11
|
+
*/
|
|
12
|
+
frontendResetUrl?: string;
|
|
13
|
+
}
|
|
14
|
+
export declare class AuthService {
|
|
15
|
+
readonly users: UserAdapter;
|
|
16
|
+
readonly tokens: TokenAdapter;
|
|
17
|
+
readonly resets?: PasswordResetAdapter;
|
|
18
|
+
readonly mailer?: Mailer;
|
|
19
|
+
readonly ttl: Required<AuthTtlOptions>;
|
|
20
|
+
readonly frontendResetUrl?: string;
|
|
21
|
+
constructor(opts: AuthServiceOptions);
|
|
22
|
+
issueCsrfToken(): string;
|
|
23
|
+
/** Login + password → user + opaque token pair. */
|
|
24
|
+
login(login: string, password: string, meta: RequestMetaLite): Promise<{
|
|
25
|
+
user: AuthUser;
|
|
26
|
+
tokens: IssuedTokenPair;
|
|
27
|
+
}>;
|
|
28
|
+
/**
|
|
29
|
+
* Ротация refresh: старый revoke → новая пара.
|
|
30
|
+
* При reuse отозванного — revokeAllForUser (если реализовано) + 401.
|
|
31
|
+
*/
|
|
32
|
+
refresh(refreshToken: string, meta: RequestMetaLite): Promise<{
|
|
33
|
+
user: AuthUser;
|
|
34
|
+
tokens: IssuedTokenPair;
|
|
35
|
+
}>;
|
|
36
|
+
logout(refreshToken: string | null | undefined): Promise<void>;
|
|
37
|
+
verifyAccess(accessToken: string, meta: RequestMetaLite): Promise<AuthUser>;
|
|
38
|
+
/** Всегда 200 — не светим, есть ли email. */
|
|
39
|
+
requestPasswordReset(email: string): Promise<{
|
|
40
|
+
ok: true;
|
|
41
|
+
}>;
|
|
42
|
+
resetPassword(token: string, newPassword: string): Promise<{
|
|
43
|
+
ok: true;
|
|
44
|
+
}>;
|
|
45
|
+
loginWithOAuth(profile: OAuthProfile, meta: RequestMetaLite): Promise<{
|
|
46
|
+
user: AuthUser;
|
|
47
|
+
tokens: IssuedTokenPair;
|
|
48
|
+
}>;
|
|
49
|
+
}
|
package/dist/service.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { createOpaqueToken, hashToken, hashPassword, verifyPassword, } from "./types";
|
|
2
|
+
import { error } from "@crossfox/elysia-kit";
|
|
3
|
+
export class AuthService {
|
|
4
|
+
users;
|
|
5
|
+
tokens;
|
|
6
|
+
resets;
|
|
7
|
+
mailer;
|
|
8
|
+
ttl;
|
|
9
|
+
frontendResetUrl;
|
|
10
|
+
constructor(opts) {
|
|
11
|
+
this.users = opts.users;
|
|
12
|
+
this.tokens = opts.tokens;
|
|
13
|
+
this.resets = opts.resets;
|
|
14
|
+
this.mailer = opts.mailer;
|
|
15
|
+
this.frontendResetUrl = opts.frontendResetUrl;
|
|
16
|
+
this.ttl = {
|
|
17
|
+
accessTtlMs: opts.ttl?.accessTtlMs ?? 15 * 60_000,
|
|
18
|
+
refreshTtlMs: opts.ttl?.refreshTtlMs ?? 30 * 24 * 60 * 60_000,
|
|
19
|
+
resetTtlMs: opts.ttl?.resetTtlMs ?? 60 * 60_000,
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
issueCsrfToken() {
|
|
23
|
+
return createOpaqueToken("csrf");
|
|
24
|
+
}
|
|
25
|
+
/** Login + password → user + opaque token pair. */
|
|
26
|
+
async login(login, password, meta) {
|
|
27
|
+
const row = await this.users.findByLogin(login.trim().toLowerCase());
|
|
28
|
+
if (!row)
|
|
29
|
+
error(401, "Login or password is incorrect");
|
|
30
|
+
const ok = await verifyPassword(password, row.passwordHash);
|
|
31
|
+
if (!ok)
|
|
32
|
+
error(401, "Login or password is incorrect");
|
|
33
|
+
const { passwordHash: _, ...user } = row;
|
|
34
|
+
const tokens = await this.tokens.issueTokens(user, meta);
|
|
35
|
+
return { user, tokens };
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Ротация refresh: старый revoke → новая пара.
|
|
39
|
+
* При reuse отозванного — revokeAllForUser (если реализовано) + 401.
|
|
40
|
+
*/
|
|
41
|
+
async refresh(refreshToken, meta) {
|
|
42
|
+
const tokenHash = hashToken(refreshToken);
|
|
43
|
+
const row = await this.tokens.findRefresh(tokenHash);
|
|
44
|
+
if (!row)
|
|
45
|
+
error(401, "Invalid refresh token");
|
|
46
|
+
if (row.revoked) {
|
|
47
|
+
await this.tokens.revokeAllForUser?.(row.userId);
|
|
48
|
+
error(401, "Refresh token revoked");
|
|
49
|
+
}
|
|
50
|
+
if (row.expiresAt.getTime() <= Date.now()) {
|
|
51
|
+
await this.tokens.revokeRefresh(tokenHash);
|
|
52
|
+
error(401, "Refresh token expired");
|
|
53
|
+
}
|
|
54
|
+
const user = await this.users.findById(row.userId);
|
|
55
|
+
if (!user)
|
|
56
|
+
error(401, "User not found");
|
|
57
|
+
await this.tokens.revokeRefresh(tokenHash);
|
|
58
|
+
const tokens = await this.tokens.issueTokens(user, meta);
|
|
59
|
+
return { user, tokens };
|
|
60
|
+
}
|
|
61
|
+
async logout(refreshToken) {
|
|
62
|
+
if (!refreshToken)
|
|
63
|
+
return;
|
|
64
|
+
await this.tokens.revokeRefresh(hashToken(refreshToken));
|
|
65
|
+
}
|
|
66
|
+
async verifyAccess(accessToken, meta) {
|
|
67
|
+
const tokenHash = hashToken(accessToken);
|
|
68
|
+
const user = await this.tokens.verifyAccessToken(accessToken, {
|
|
69
|
+
...meta,
|
|
70
|
+
tokenHash,
|
|
71
|
+
});
|
|
72
|
+
if (!user)
|
|
73
|
+
error(401, "Unauthorized");
|
|
74
|
+
return user;
|
|
75
|
+
}
|
|
76
|
+
/** Всегда 200 — не светим, есть ли email. */
|
|
77
|
+
async requestPasswordReset(email) {
|
|
78
|
+
if (!this.resets || !this.mailer || !this.frontendResetUrl) {
|
|
79
|
+
error(500, "Password reset is not configured");
|
|
80
|
+
}
|
|
81
|
+
const normalized = email.trim().toLowerCase();
|
|
82
|
+
const user = await this.users.findByEmail(normalized);
|
|
83
|
+
if (user) {
|
|
84
|
+
const token = createOpaqueToken("rp");
|
|
85
|
+
const tokenHash = hashToken(token);
|
|
86
|
+
const expiresAt = new Date(Date.now() + this.ttl.resetTtlMs);
|
|
87
|
+
await this.resets.create(user.id, tokenHash, expiresAt);
|
|
88
|
+
const url = new URL(this.frontendResetUrl);
|
|
89
|
+
url.searchParams.set("token", token);
|
|
90
|
+
await this.mailer.sendPasswordReset({
|
|
91
|
+
to: normalized,
|
|
92
|
+
user,
|
|
93
|
+
token,
|
|
94
|
+
resetUrl: url.toString(),
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
return { ok: true };
|
|
98
|
+
}
|
|
99
|
+
async resetPassword(token, newPassword) {
|
|
100
|
+
if (!this.resets)
|
|
101
|
+
error(500, "Password reset is not configured");
|
|
102
|
+
if (!newPassword || newPassword.length < 8) {
|
|
103
|
+
error(422, "Password must be at least 8 characters");
|
|
104
|
+
}
|
|
105
|
+
const consumed = await this.resets.consume(hashToken(token));
|
|
106
|
+
if (!consumed)
|
|
107
|
+
error(400, "Invalid or expired reset token");
|
|
108
|
+
const passwordHash = await hashPassword(newPassword);
|
|
109
|
+
await this.users.updatePassword(consumed.userId, passwordHash);
|
|
110
|
+
await this.tokens.revokeAllForUser?.(consumed.userId);
|
|
111
|
+
return { ok: true };
|
|
112
|
+
}
|
|
113
|
+
async loginWithOAuth(profile, meta) {
|
|
114
|
+
if (!this.users.findOrCreateFromOAuth) {
|
|
115
|
+
error(500, "OAuth user adapter is not configured");
|
|
116
|
+
}
|
|
117
|
+
const user = await this.users.findOrCreateFromOAuth(profile);
|
|
118
|
+
const tokens = await this.tokens.issueTokens(user, meta);
|
|
119
|
+
return { user, tokens };
|
|
120
|
+
}
|
|
121
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { createOpaqueToken, hashToken, hashPassword, verifyPassword } from "@crossfox/elysia-kit";
|
|
2
|
+
export type AuthProviderId = "google" | "facebook" | "instagram" | (string & {});
|
|
3
|
+
export interface AuthUser {
|
|
4
|
+
id: string | number;
|
|
5
|
+
email?: string | null;
|
|
6
|
+
name?: string | null;
|
|
7
|
+
role?: string;
|
|
8
|
+
[key: string]: unknown;
|
|
9
|
+
}
|
|
10
|
+
export interface AuthUserWithPassword extends AuthUser {
|
|
11
|
+
/** Bun.password / argon2 / bcrypt hash */
|
|
12
|
+
passwordHash: string;
|
|
13
|
+
}
|
|
14
|
+
export interface OAuthProfile {
|
|
15
|
+
provider: AuthProviderId;
|
|
16
|
+
providerAccountId: string;
|
|
17
|
+
email?: string | null;
|
|
18
|
+
name?: string | null;
|
|
19
|
+
avatarUrl?: string | null;
|
|
20
|
+
raw?: unknown;
|
|
21
|
+
}
|
|
22
|
+
export interface RequestMetaLite {
|
|
23
|
+
ip: string | null;
|
|
24
|
+
userAgent: string | null;
|
|
25
|
+
}
|
|
26
|
+
export interface IssuedToken {
|
|
27
|
+
token: string;
|
|
28
|
+
tokenHash: string;
|
|
29
|
+
expiresAt: Date;
|
|
30
|
+
}
|
|
31
|
+
export interface IssuedTokenPair {
|
|
32
|
+
access: IssuedToken;
|
|
33
|
+
refresh: IssuedToken;
|
|
34
|
+
}
|
|
35
|
+
export interface RefreshRecord {
|
|
36
|
+
userId: string | number;
|
|
37
|
+
tokenHash: string;
|
|
38
|
+
expiresAt: Date;
|
|
39
|
+
revoked: boolean;
|
|
40
|
+
role?: string;
|
|
41
|
+
}
|
|
42
|
+
/** Пользователи + пароли + OAuth upsert. */
|
|
43
|
+
export interface UserAdapter {
|
|
44
|
+
findByLogin(login: string): Promise<AuthUserWithPassword | null>;
|
|
45
|
+
findById(id: string | number): Promise<AuthUser | null>;
|
|
46
|
+
findByEmail(email: string): Promise<AuthUser | null>;
|
|
47
|
+
updatePassword(userId: string | number, passwordHash: string): Promise<void>;
|
|
48
|
+
findOrCreateFromOAuth?(profile: OAuthProfile): Promise<AuthUser>;
|
|
49
|
+
}
|
|
50
|
+
/** Opaque access/refresh — в БД только hash. */
|
|
51
|
+
export interface TokenAdapter {
|
|
52
|
+
issueTokens(user: AuthUser, meta: RequestMetaLite): Promise<IssuedTokenPair>;
|
|
53
|
+
verifyAccessToken(token: string, meta: RequestMetaLite & {
|
|
54
|
+
tokenHash: string;
|
|
55
|
+
}): Promise<AuthUser | null>;
|
|
56
|
+
findRefresh(tokenHash: string): Promise<RefreshRecord | null>;
|
|
57
|
+
/** Пометить refresh отозванным (после logout / rotation / reuse). */
|
|
58
|
+
revokeRefresh(tokenHash: string): Promise<void>;
|
|
59
|
+
revokeAllForUser?(userId: string | number): Promise<void>;
|
|
60
|
+
}
|
|
61
|
+
/** Одноразовые токены сброса пароля (храните hash). */
|
|
62
|
+
export interface PasswordResetAdapter {
|
|
63
|
+
create(userId: string | number, tokenHash: string, expiresAt: Date): Promise<void>;
|
|
64
|
+
/** Вернуть userId и инвалидировать токен; null если нет/истёк. */
|
|
65
|
+
consume(tokenHash: string): Promise<{
|
|
66
|
+
userId: string | number;
|
|
67
|
+
} | null>;
|
|
68
|
+
}
|
|
69
|
+
export interface Mailer {
|
|
70
|
+
sendPasswordReset(input: {
|
|
71
|
+
to: string;
|
|
72
|
+
user: AuthUser;
|
|
73
|
+
/** Сырой токен — только в письме, не в БД. */
|
|
74
|
+
token: string;
|
|
75
|
+
resetUrl: string;
|
|
76
|
+
}): Promise<void>;
|
|
77
|
+
}
|
|
78
|
+
export interface OAuthProviderCredentials {
|
|
79
|
+
clientId: string;
|
|
80
|
+
clientSecret: string;
|
|
81
|
+
scopes?: string[];
|
|
82
|
+
redirectUri?: string;
|
|
83
|
+
}
|
|
84
|
+
export interface AuthCookieOptions {
|
|
85
|
+
enabled?: boolean;
|
|
86
|
+
accessName?: string;
|
|
87
|
+
refreshName?: string;
|
|
88
|
+
csrfName?: string;
|
|
89
|
+
secure?: boolean;
|
|
90
|
+
sameSite?: "strict" | "lax" | "none";
|
|
91
|
+
path?: string;
|
|
92
|
+
domain?: string;
|
|
93
|
+
}
|
|
94
|
+
export interface AuthTtlOptions {
|
|
95
|
+
accessTtlMs?: number;
|
|
96
|
+
refreshTtlMs?: number;
|
|
97
|
+
resetTtlMs?: number;
|
|
98
|
+
}
|
|
99
|
+
export { createOpaqueToken, hashToken, hashPassword, verifyPassword, };
|
package/dist/types.js
ADDED
package/package.json
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@crossfox/elysia-auth",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Elysia auth: opaque access/refresh tokens, login, password reset, OAuth (Google/Facebook/Instagram). Adapter-based.",
|
|
5
|
+
"license": "PolyForm-Noncommercial-1.0.0",
|
|
6
|
+
"author": "Oleksii Fursov <nodepro777@gmail.com>",
|
|
7
|
+
"homepage": "https://crossfox.online",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/OleksiiFursov/packages.git",
|
|
11
|
+
"directory": "elysia-auth"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/OleksiiFursov/packages/issues",
|
|
15
|
+
"email": "nodepro777@gmail.com"
|
|
16
|
+
},
|
|
17
|
+
"type": "module",
|
|
18
|
+
"sideEffects": false,
|
|
19
|
+
"engines": {
|
|
20
|
+
"bun": ">=1.1.0"
|
|
21
|
+
},
|
|
22
|
+
"main": "./dist/index.js",
|
|
23
|
+
"types": "./dist/index.d.ts",
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"import": "./dist/index.js",
|
|
28
|
+
"default": "./dist/index.js"
|
|
29
|
+
},
|
|
30
|
+
"./package.json": "./package.json"
|
|
31
|
+
},
|
|
32
|
+
"files": ["dist", "README.md", "LICENSE"],
|
|
33
|
+
"scripts": {
|
|
34
|
+
"build": "tsc -p tsconfig.build.json",
|
|
35
|
+
"typecheck": "tsc --noEmit",
|
|
36
|
+
"test": "bun test",
|
|
37
|
+
"check": "bun run typecheck && bun test",
|
|
38
|
+
"prepublishOnly": "bun run check && bun run build"
|
|
39
|
+
},
|
|
40
|
+
"dependencies": {
|
|
41
|
+
"arctic": "^3.7.0"
|
|
42
|
+
},
|
|
43
|
+
"peerDependencies": {
|
|
44
|
+
"@crossfox/elysia-kit": ">=0.1.0",
|
|
45
|
+
"elysia": ">=1.4"
|
|
46
|
+
},
|
|
47
|
+
"devDependencies": {
|
|
48
|
+
"@crossfox/elysia-kit": "workspace:*",
|
|
49
|
+
"@types/bun": "^1.3.14",
|
|
50
|
+
"elysia": "^1.4.28",
|
|
51
|
+
"typescript": "6.0.3"
|
|
52
|
+
},
|
|
53
|
+
"keywords": [
|
|
54
|
+
"elysia",
|
|
55
|
+
"auth",
|
|
56
|
+
"oauth",
|
|
57
|
+
"refresh-token",
|
|
58
|
+
"opaque-token",
|
|
59
|
+
"password-reset",
|
|
60
|
+
"google",
|
|
61
|
+
"facebook",
|
|
62
|
+
"instagram",
|
|
63
|
+
"bun",
|
|
64
|
+
"crossfox"
|
|
65
|
+
],
|
|
66
|
+
"publishConfig": {
|
|
67
|
+
"access": "public"
|
|
68
|
+
}
|
|
69
|
+
}
|