@jskit-ai/auth-provider-local-core 0.2.1 → 0.2.3
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/locales/en.json +15 -0
- package/package.json +6 -3
- package/src/server/lib/fileBackend.js +160 -2
- package/src/server/lib/oauth.js +207 -0
- package/src/server/lib/registerHookDecorator.js +19 -6
- package/src/server/lib/service.js +288 -49
- package/src/server/providers/AuthLocalProvider.js +9 -4
- package/test/oauthSignIn.test.js +359 -0
- package/test/providerRuntime.test.js +48 -0
- package/test-support/oauthHarness.js +167 -0
package/locales/en.json
CHANGED
|
@@ -18,6 +18,21 @@
|
|
|
18
18
|
"requested": "If an account exists for that email, password reset instructions have been sent.",
|
|
19
19
|
"tokenInvalid": "Recovery token is invalid or expired.",
|
|
20
20
|
"sessionRequired": "Recovery session required."
|
|
21
|
+
},
|
|
22
|
+
"oauth": {
|
|
23
|
+
"providerInvalid": "This sign-in provider is not available.",
|
|
24
|
+
"providerUnreachable": "{provider} can't be reached right now. Try again in a moment.",
|
|
25
|
+
"expired": "This sign-in took too long or started in another browser. Start again.",
|
|
26
|
+
"codeRequired": "OAuth code is required.",
|
|
27
|
+
"cancelled": "Sign-in was cancelled.",
|
|
28
|
+
"incomplete": "Sign-in was not completed. Start again.",
|
|
29
|
+
"unverified": "Your sign-in could not be verified. Start again.",
|
|
30
|
+
"emailMissing": "{provider} did not share an email address.",
|
|
31
|
+
"emailUnverified": "{provider} has not confirmed your email address, so this account can't sign in here.",
|
|
32
|
+
"accountUnavailable": "This account can't sign in.",
|
|
33
|
+
"identityTaken": "This {provider} account is already linked to another account.",
|
|
34
|
+
"notLinked": "{provider} is not linked to this account.",
|
|
35
|
+
"lastMethod": "Add a password or link another sign-in method before removing this one."
|
|
21
36
|
}
|
|
22
37
|
}
|
|
23
38
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jskit-ai/auth-provider-local-core",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.3",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"test": "node --test --test-concurrency=1"
|
|
@@ -10,7 +10,10 @@
|
|
|
10
10
|
"./server/lib/index": "./src/server/lib/index.js",
|
|
11
11
|
"./locales/en.json": "./locales/en.json"
|
|
12
12
|
},
|
|
13
|
-
"
|
|
13
|
+
"dependencies": {
|
|
14
|
+
"openid-client": "6.8.8"
|
|
15
|
+
},
|
|
16
|
+
"description": "Local auth provider with a file backend default, no database requirement, and optional Google, Microsoft and GitHub sign-in.",
|
|
14
17
|
"jskit": {
|
|
15
18
|
"kind": "runtime",
|
|
16
19
|
"capabilities": {
|
|
@@ -44,7 +47,7 @@
|
|
|
44
47
|
},
|
|
45
48
|
{
|
|
46
49
|
"subpath": "./server/lib/index",
|
|
47
|
-
"summary": "Exports local auth service, file backend helpers, password strategy helpers, and local auth register hook decorators."
|
|
50
|
+
"summary": "Exports local auth service, file backend helpers, password strategy helpers, and local auth register hook decorators. Google, Microsoft and GitHub sign-in turn on from AUTH_GOOGLE_*, AUTH_MICROSOFT_* and AUTH_GITHUB_* client id and secret pairs."
|
|
48
51
|
}
|
|
49
52
|
],
|
|
50
53
|
"extensionCapabilities": [
|
|
@@ -4,6 +4,8 @@ import path from "node:path";
|
|
|
4
4
|
const USER_FILE = "users.passwd";
|
|
5
5
|
const SESSION_FILE = "sessions.passwd";
|
|
6
6
|
const RECOVERY_FILE = "recovery.passwd";
|
|
7
|
+
const IDENTITY_FILE = "identities.passwd";
|
|
8
|
+
const OAUTH_ATTEMPT_FILE = "oauth-attempts.passwd";
|
|
7
9
|
const LOCK_FILE = "store.lock";
|
|
8
10
|
const JOURNAL_FILE = "transaction.journal";
|
|
9
11
|
const LOCK_STALE_MS = 30_000;
|
|
@@ -151,6 +153,87 @@ function serializeRecovery(records) {
|
|
|
151
153
|
.join("\n") + (records.length > 0 ? "\n" : "");
|
|
152
154
|
}
|
|
153
155
|
|
|
156
|
+
function parseIdentities(content) {
|
|
157
|
+
const identities = [];
|
|
158
|
+
for (const line of String(content || "").split("\n").filter(Boolean)) {
|
|
159
|
+
const parts = splitLine(line, "identity");
|
|
160
|
+
if (parts.length !== 7) {
|
|
161
|
+
throw new Error("Invalid identity record field count.");
|
|
162
|
+
}
|
|
163
|
+
identities.push({
|
|
164
|
+
userId: parts[2],
|
|
165
|
+
provider: parts[3],
|
|
166
|
+
providerSubject: decodeField(parts[4]),
|
|
167
|
+
email: decodeField(parts[5]),
|
|
168
|
+
createdAt: decodeField(parts[6])
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
return identities;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function serializeIdentities(identities) {
|
|
175
|
+
return [...identities]
|
|
176
|
+
.sort((left, right) =>
|
|
177
|
+
`${left.provider}:${left.providerSubject}`.localeCompare(`${right.provider}:${right.providerSubject}`))
|
|
178
|
+
.map((identity) =>
|
|
179
|
+
[
|
|
180
|
+
"identity",
|
|
181
|
+
"v1",
|
|
182
|
+
identity.userId,
|
|
183
|
+
identity.provider,
|
|
184
|
+
encodeField(identity.providerSubject),
|
|
185
|
+
encodeField(identity.email),
|
|
186
|
+
encodeField(identity.createdAt)
|
|
187
|
+
].join(":")
|
|
188
|
+
)
|
|
189
|
+
.join("\n") + (identities.length > 0 ? "\n" : "");
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function parseOAuthAttempts(content) {
|
|
193
|
+
const attempts = [];
|
|
194
|
+
for (const line of String(content || "").split("\n").filter(Boolean)) {
|
|
195
|
+
const parts = splitLine(line, "oauth_attempt");
|
|
196
|
+
if (parts.length !== 12) {
|
|
197
|
+
throw new Error("Invalid OAuth attempt record field count.");
|
|
198
|
+
}
|
|
199
|
+
attempts.push({
|
|
200
|
+
browserKeyHash: parts[2],
|
|
201
|
+
provider: parts[3],
|
|
202
|
+
intent: parts[4],
|
|
203
|
+
userId: parts[5],
|
|
204
|
+
state: parts[6],
|
|
205
|
+
nonce: parts[7],
|
|
206
|
+
codeVerifier: parts[8],
|
|
207
|
+
returnTo: decodeField(parts[9]),
|
|
208
|
+
createdAt: decodeField(parts[10]),
|
|
209
|
+
expiresAt: decodeField(parts[11])
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
return attempts;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function serializeOAuthAttempts(attempts) {
|
|
216
|
+
return [...attempts]
|
|
217
|
+
.sort((left, right) => String(left.browserKeyHash).localeCompare(String(right.browserKeyHash)))
|
|
218
|
+
.map((attempt) =>
|
|
219
|
+
[
|
|
220
|
+
"oauth_attempt",
|
|
221
|
+
"v1",
|
|
222
|
+
attempt.browserKeyHash,
|
|
223
|
+
attempt.provider,
|
|
224
|
+
attempt.intent,
|
|
225
|
+
attempt.userId,
|
|
226
|
+
attempt.state,
|
|
227
|
+
attempt.nonce,
|
|
228
|
+
attempt.codeVerifier,
|
|
229
|
+
encodeField(attempt.returnTo),
|
|
230
|
+
encodeField(attempt.createdAt),
|
|
231
|
+
encodeField(attempt.expiresAt)
|
|
232
|
+
].join(":")
|
|
233
|
+
)
|
|
234
|
+
.join("\n") + (attempts.length > 0 ? "\n" : "");
|
|
235
|
+
}
|
|
236
|
+
|
|
154
237
|
async function readText(filePath) {
|
|
155
238
|
try {
|
|
156
239
|
return await fs.readFile(filePath, "utf8");
|
|
@@ -199,7 +282,7 @@ function parseJournal(content) {
|
|
|
199
282
|
}
|
|
200
283
|
return parsed.files.map((entry) => {
|
|
201
284
|
const name = String(entry?.name || "").trim();
|
|
202
|
-
if (![USER_FILE, SESSION_FILE, RECOVERY_FILE].includes(name)) {
|
|
285
|
+
if (![USER_FILE, SESSION_FILE, RECOVERY_FILE, IDENTITY_FILE, OAUTH_ATTEMPT_FILE].includes(name)) {
|
|
203
286
|
throw new Error("Invalid local auth transaction journal file.");
|
|
204
287
|
}
|
|
205
288
|
return {
|
|
@@ -436,6 +519,67 @@ function createTx(state, touched) {
|
|
|
436
519
|
}
|
|
437
520
|
return count;
|
|
438
521
|
}
|
|
522
|
+
}),
|
|
523
|
+
identities: Object.freeze({
|
|
524
|
+
async create(input) {
|
|
525
|
+
if (state.identities.some((entry) =>
|
|
526
|
+
entry.provider === input.provider && entry.providerSubject === input.providerSubject)) {
|
|
527
|
+
throw new Error("Local auth identity already exists.");
|
|
528
|
+
}
|
|
529
|
+
const identity = {
|
|
530
|
+
...clone(input),
|
|
531
|
+
createdAt: input.createdAt || nowIso()
|
|
532
|
+
};
|
|
533
|
+
state.identities.push(identity);
|
|
534
|
+
mark("identities");
|
|
535
|
+
return clone(identity);
|
|
536
|
+
},
|
|
537
|
+
async findByProviderSubject(provider, providerSubject) {
|
|
538
|
+
return clone(state.identities.find((entry) =>
|
|
539
|
+
entry.provider === provider && entry.providerSubject === providerSubject) || null);
|
|
540
|
+
},
|
|
541
|
+
async listForUser(userId) {
|
|
542
|
+
return clone(state.identities.filter((entry) => entry.userId === userId));
|
|
543
|
+
},
|
|
544
|
+
async deleteForUser(userId, provider) {
|
|
545
|
+
const before = state.identities.length;
|
|
546
|
+
state.identities = state.identities.filter((entry) => !(entry.userId === userId && entry.provider === provider));
|
|
547
|
+
const count = before - state.identities.length;
|
|
548
|
+
if (count > 0) {
|
|
549
|
+
mark("identities");
|
|
550
|
+
}
|
|
551
|
+
return count;
|
|
552
|
+
}
|
|
553
|
+
}),
|
|
554
|
+
oauthAttempts: Object.freeze({
|
|
555
|
+
async create(input) {
|
|
556
|
+
const attempt = {
|
|
557
|
+
...clone(input),
|
|
558
|
+
createdAt: input.createdAt || nowIso()
|
|
559
|
+
};
|
|
560
|
+
state.oauthAttempts.push(attempt);
|
|
561
|
+
mark("oauthAttempts");
|
|
562
|
+
return clone(attempt);
|
|
563
|
+
},
|
|
564
|
+
// Removes and returns the attempt; the store lock makes this single-use.
|
|
565
|
+
async take(browserKeyHash) {
|
|
566
|
+
const attempt = state.oauthAttempts.find((entry) => entry.browserKeyHash === browserKeyHash);
|
|
567
|
+
if (!attempt) {
|
|
568
|
+
return null;
|
|
569
|
+
}
|
|
570
|
+
state.oauthAttempts = state.oauthAttempts.filter((entry) => entry !== attempt);
|
|
571
|
+
mark("oauthAttempts");
|
|
572
|
+
return clone(attempt);
|
|
573
|
+
},
|
|
574
|
+
async deleteExpired(now) {
|
|
575
|
+
const before = state.oauthAttempts.length;
|
|
576
|
+
state.oauthAttempts = state.oauthAttempts.filter((entry) => Date.parse(entry.expiresAt) > Date.parse(now));
|
|
577
|
+
const count = before - state.oauthAttempts.length;
|
|
578
|
+
if (count > 0) {
|
|
579
|
+
mark("oauthAttempts");
|
|
580
|
+
}
|
|
581
|
+
return count;
|
|
582
|
+
}
|
|
439
583
|
})
|
|
440
584
|
});
|
|
441
585
|
}
|
|
@@ -451,7 +595,9 @@ function createLocalFileBackend({ storeDir }) {
|
|
|
451
595
|
const state = {
|
|
452
596
|
users: parseUsers(await readText(path.join(resolvedStoreDir, USER_FILE))),
|
|
453
597
|
sessions: parseSessions(await readText(path.join(resolvedStoreDir, SESSION_FILE))),
|
|
454
|
-
recovery: parseRecovery(await readText(path.join(resolvedStoreDir, RECOVERY_FILE)))
|
|
598
|
+
recovery: parseRecovery(await readText(path.join(resolvedStoreDir, RECOVERY_FILE))),
|
|
599
|
+
identities: parseIdentities(await readText(path.join(resolvedStoreDir, IDENTITY_FILE))),
|
|
600
|
+
oauthAttempts: parseOAuthAttempts(await readText(path.join(resolvedStoreDir, OAUTH_ATTEMPT_FILE)))
|
|
455
601
|
};
|
|
456
602
|
const touched = new Set();
|
|
457
603
|
const result = await callback(createTx(state, touched));
|
|
@@ -474,6 +620,18 @@ function createLocalFileBackend({ storeDir }) {
|
|
|
474
620
|
content: serializeRecovery(state.recovery)
|
|
475
621
|
});
|
|
476
622
|
}
|
|
623
|
+
if (touched.has("identities")) {
|
|
624
|
+
commitEntries.push({
|
|
625
|
+
name: IDENTITY_FILE,
|
|
626
|
+
content: serializeIdentities(state.identities)
|
|
627
|
+
});
|
|
628
|
+
}
|
|
629
|
+
if (touched.has("oauthAttempts")) {
|
|
630
|
+
commitEntries.push({
|
|
631
|
+
name: OAUTH_ATTEMPT_FILE,
|
|
632
|
+
content: serializeOAuthAttempts(state.oauthAttempts)
|
|
633
|
+
});
|
|
634
|
+
}
|
|
477
635
|
if (commitEntries.length > 0) {
|
|
478
636
|
await writeCommitJournal(resolvedStoreDir, commitEntries);
|
|
479
637
|
for (const entry of commitEntries) {
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import * as client from "openid-client";
|
|
2
|
+
import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
|
|
3
|
+
import { normalizeEmail } from "@jskit-ai/auth-core/server/utils";
|
|
4
|
+
|
|
5
|
+
const OIDC_SCOPE = "openid email profile";
|
|
6
|
+
const GITHUB_SCOPE = "read:user user:email";
|
|
7
|
+
// Personal Microsoft accounts sign in through this tenant; their address is the account itself.
|
|
8
|
+
const MICROSOFT_CONSUMER_TENANT_ID = "9188040d-6c67-4c5b-b112-36a304b66dad";
|
|
9
|
+
|
|
10
|
+
// Google and Microsoft speak OpenID Connect (discovery from `issuer`); GitHub
|
|
11
|
+
// speaks plain OAuth 2.0 and its API names the person.
|
|
12
|
+
const OAUTH_PROVIDER_DEFINITIONS = Object.freeze([
|
|
13
|
+
Object.freeze({ id: "google", label: "Google", envPrefix: "AUTH_GOOGLE", issuer: "https://accounts.google.com" }),
|
|
14
|
+
Object.freeze({
|
|
15
|
+
id: "microsoft",
|
|
16
|
+
label: "Microsoft",
|
|
17
|
+
envPrefix: "AUTH_MICROSOFT",
|
|
18
|
+
issuer: "https://login.microsoftonline.com/common/v2.0"
|
|
19
|
+
}),
|
|
20
|
+
Object.freeze({
|
|
21
|
+
id: "github",
|
|
22
|
+
label: "GitHub",
|
|
23
|
+
envPrefix: "AUTH_GITHUB",
|
|
24
|
+
authorizationEndpoint: "https://github.com/login/oauth/authorize",
|
|
25
|
+
tokenEndpoint: "https://github.com/login/oauth/access_token",
|
|
26
|
+
apiUrl: "https://api.github.com"
|
|
27
|
+
})
|
|
28
|
+
]);
|
|
29
|
+
|
|
30
|
+
/** The providers whose client id and secret are both set, in catalog order. */
|
|
31
|
+
function resolveOAuthProviders(env = {}) {
|
|
32
|
+
const providers = [];
|
|
33
|
+
for (const definition of OAUTH_PROVIDER_DEFINITIONS) {
|
|
34
|
+
const clientId = String(env[`${definition.envPrefix}_CLIENT_ID`] || "").trim();
|
|
35
|
+
const clientSecret = String(env[`${definition.envPrefix}_CLIENT_SECRET`] || "").trim();
|
|
36
|
+
if (!clientId && !clientSecret) {
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
if (!clientId || !clientSecret) {
|
|
40
|
+
throw new Error(`${definition.envPrefix}_CLIENT_ID and ${definition.envPrefix}_CLIENT_SECRET must be set together.`);
|
|
41
|
+
}
|
|
42
|
+
providers.push(Object.freeze({ ...definition, clientId, clientSecret }));
|
|
43
|
+
}
|
|
44
|
+
return Object.freeze(providers);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Errors that name a provider carry its label as the provider param.
|
|
48
|
+
function signInError(statusCode, message, { code, provider = null }) {
|
|
49
|
+
return new AppError(statusCode, message, {
|
|
50
|
+
code,
|
|
51
|
+
...(provider ? { params: { provider: provider.label } } : {})
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function unverifiedSignIn() {
|
|
56
|
+
return signInError(401, "Your sign-in could not be verified. Start again.", { code: "auth.local.oauth.unverified" });
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function displayNameFrom(source = {}) {
|
|
60
|
+
return String(source.name || [source.given_name, source.family_name].filter(Boolean).join(" ") || "").trim();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Each reader returns { subject, email, emailVerified, name } from what the provider vouches for.
|
|
64
|
+
const IDENTITY_READERS = Object.freeze({
|
|
65
|
+
async google(configuration, tokens) {
|
|
66
|
+
const claims = tokens.claims() || {};
|
|
67
|
+
const source = claims.email || !tokens.access_token
|
|
68
|
+
? claims
|
|
69
|
+
: await client.fetchUserInfo(configuration, tokens.access_token, claims.sub);
|
|
70
|
+
return { subject: claims.sub, email: source.email, emailVerified: source.email_verified === true, name: displayNameFrom(source) };
|
|
71
|
+
},
|
|
72
|
+
// A work or school account's email claim is whatever its tenant typed, so it
|
|
73
|
+
// counts only when Microsoft verified the tenant's domain (xms_edov).
|
|
74
|
+
async microsoft(_configuration, tokens) {
|
|
75
|
+
const claims = tokens.claims() || {};
|
|
76
|
+
return {
|
|
77
|
+
subject: claims.sub,
|
|
78
|
+
email: claims.email,
|
|
79
|
+
emailVerified: claims.tid === MICROSOFT_CONSUMER_TENANT_ID || claims.xms_edov === true,
|
|
80
|
+
name: displayNameFrom(claims)
|
|
81
|
+
};
|
|
82
|
+
},
|
|
83
|
+
async github(configuration, tokens, provider) {
|
|
84
|
+
async function read(path) {
|
|
85
|
+
const response = await client.fetchProtectedResource(
|
|
86
|
+
configuration,
|
|
87
|
+
tokens.access_token,
|
|
88
|
+
new URL(path, provider.apiUrl),
|
|
89
|
+
"GET",
|
|
90
|
+
undefined,
|
|
91
|
+
new Headers({ accept: "application/vnd.github+json" })
|
|
92
|
+
);
|
|
93
|
+
if (!response.ok) {
|
|
94
|
+
throw unverifiedSignIn();
|
|
95
|
+
}
|
|
96
|
+
return response.json();
|
|
97
|
+
}
|
|
98
|
+
const user = await read("/user");
|
|
99
|
+
const emails = await read("/user/emails");
|
|
100
|
+
const primary = (Array.isArray(emails) ? emails : []).find((entry) => entry?.primary === true);
|
|
101
|
+
return {
|
|
102
|
+
subject: user?.id == null ? "" : String(user.id),
|
|
103
|
+
email: primary?.email,
|
|
104
|
+
emailVerified: primary?.verified === true,
|
|
105
|
+
name: String(user?.name || user?.login || "").trim()
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* The authorization-code (PKCE) client for each configured provider. Provider
|
|
112
|
+
* tokens are used once to learn who signed in and are never kept.
|
|
113
|
+
*/
|
|
114
|
+
function createOAuthClients({ logger = null } = {}) {
|
|
115
|
+
const configurations = new Map();
|
|
116
|
+
|
|
117
|
+
async function createConfiguration(provider) {
|
|
118
|
+
const clientAuthentication = client.ClientSecretPost(provider.clientSecret);
|
|
119
|
+
const address = new URL(provider.issuer || provider.authorizationEndpoint);
|
|
120
|
+
// Real providers are https; only a local test provider is plain http.
|
|
121
|
+
const insecure = address.protocol === "http:";
|
|
122
|
+
if (!provider.issuer) {
|
|
123
|
+
const configuration = new client.Configuration(
|
|
124
|
+
{
|
|
125
|
+
issuer: address.origin,
|
|
126
|
+
authorization_endpoint: provider.authorizationEndpoint,
|
|
127
|
+
token_endpoint: provider.tokenEndpoint
|
|
128
|
+
},
|
|
129
|
+
provider.clientId,
|
|
130
|
+
undefined,
|
|
131
|
+
clientAuthentication
|
|
132
|
+
);
|
|
133
|
+
if (insecure) client.allowInsecureRequests(configuration);
|
|
134
|
+
return configuration;
|
|
135
|
+
}
|
|
136
|
+
const configuration = await client.discovery(
|
|
137
|
+
address,
|
|
138
|
+
provider.clientId,
|
|
139
|
+
undefined,
|
|
140
|
+
clientAuthentication,
|
|
141
|
+
insecure ? { execute: [client.allowInsecureRequests] } : undefined
|
|
142
|
+
);
|
|
143
|
+
// Verify ID token signatures against the provider's published keys (JWKS).
|
|
144
|
+
client.enableNonRepudiationChecks(configuration);
|
|
145
|
+
return configuration;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async function configurationFor(provider) {
|
|
149
|
+
if (!configurations.has(provider.id)) {
|
|
150
|
+
configurations.set(provider.id, createConfiguration(provider).catch((error) => {
|
|
151
|
+
configurations.delete(provider.id);
|
|
152
|
+
logger?.warn?.({ err: error, provider: provider.id }, "OAuth provider discovery failed.");
|
|
153
|
+
throw signInError(503, `${provider.label} can't be reached right now. Try again in a moment.`,
|
|
154
|
+
{ code: "auth.local.oauth.providerUnreachable", provider });
|
|
155
|
+
}));
|
|
156
|
+
}
|
|
157
|
+
return configurations.get(provider.id);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async function authorizationUrl(provider, { redirectUri, state, nonce, codeVerifier }) {
|
|
161
|
+
const configuration = await configurationFor(provider);
|
|
162
|
+
return client.buildAuthorizationUrl(configuration, {
|
|
163
|
+
redirect_uri: redirectUri,
|
|
164
|
+
scope: provider.issuer ? OIDC_SCOPE : GITHUB_SCOPE,
|
|
165
|
+
state,
|
|
166
|
+
...(provider.issuer ? { nonce } : {}),
|
|
167
|
+
code_challenge: await client.calculatePKCECodeChallenge(codeVerifier),
|
|
168
|
+
code_challenge_method: "S256"
|
|
169
|
+
}).href;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Exchanges the code and returns the person's provider subject and verified
|
|
174
|
+
* email, or refuses: wrong state, nonce, issuer, audience, signature or an
|
|
175
|
+
* unverified email never reach an account.
|
|
176
|
+
*/
|
|
177
|
+
async function verifiedIdentity(provider, { callbackUrl, attempt }) {
|
|
178
|
+
const configuration = await configurationFor(provider);
|
|
179
|
+
let tokens;
|
|
180
|
+
try {
|
|
181
|
+
tokens = await client.authorizationCodeGrant(configuration, callbackUrl, {
|
|
182
|
+
pkceCodeVerifier: attempt.codeVerifier,
|
|
183
|
+
expectedState: attempt.state,
|
|
184
|
+
...(provider.issuer ? { expectedNonce: attempt.nonce, idTokenExpected: true } : {})
|
|
185
|
+
});
|
|
186
|
+
} catch (error) {
|
|
187
|
+
logger?.warn?.({ err: { name: error?.name, code: error?.code, message: error?.message }, provider: provider.id },
|
|
188
|
+
"OAuth sign-in was rejected.");
|
|
189
|
+
throw unverifiedSignIn();
|
|
190
|
+
}
|
|
191
|
+
const identity = await IDENTITY_READERS[provider.id](configuration, tokens, provider);
|
|
192
|
+
const email = normalizeEmail(identity.email);
|
|
193
|
+
if (!email || !identity.subject) {
|
|
194
|
+
throw signInError(401, `${provider.label} did not share an email address.`,
|
|
195
|
+
{ code: "auth.local.oauth.emailMissing", provider });
|
|
196
|
+
}
|
|
197
|
+
if (!identity.emailVerified) {
|
|
198
|
+
throw signInError(401, `${provider.label} has not confirmed your email address, so this account can't sign in here.`,
|
|
199
|
+
{ code: "auth.local.oauth.emailUnverified", provider });
|
|
200
|
+
}
|
|
201
|
+
return { provider: provider.id, providerSubject: String(identity.subject), email, name: identity.name.slice(0, 160) };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
return Object.freeze({ authorizationUrl, verifiedIdentity });
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export { createOAuthClients, resolveOAuthProviders };
|
|
@@ -76,12 +76,25 @@ function createLocalAuthRegisterHookDecorator({
|
|
|
76
76
|
}
|
|
77
77
|
|
|
78
78
|
return Object.freeze(
|
|
79
|
-
Object.
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
79
|
+
Object.defineProperties(Object.create(authService), {
|
|
80
|
+
register: {
|
|
81
|
+
enumerable: true,
|
|
82
|
+
value: async function register(input = {}) {
|
|
83
|
+
const result = await authService.register(input);
|
|
84
|
+
await runRegisterHook({ hook: registerHook, result, logger });
|
|
85
|
+
return result;
|
|
86
|
+
}
|
|
87
|
+
},
|
|
88
|
+
// A first sign-in through a provider creates the user the way register does.
|
|
89
|
+
oauthComplete: {
|
|
90
|
+
enumerable: true,
|
|
91
|
+
value: async function oauthComplete(input = {}, request = null) {
|
|
92
|
+
const result = await authService.oauthComplete(input, request);
|
|
93
|
+
if (result?.registered === true) {
|
|
94
|
+
await runRegisterHook({ hook: registerHook, result, logger });
|
|
95
|
+
}
|
|
96
|
+
return result;
|
|
97
|
+
}
|
|
85
98
|
}
|
|
86
99
|
})
|
|
87
100
|
);
|