@jskit-ai/auth-provider-local-core 0.2.1 → 0.2.2
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 +271 -39
- package/src/server/providers/AuthLocalProvider.js +9 -4
- package/test/oauthSignIn.test.js +359 -0
- package/test-support/oauthHarness.js +167 -0
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import test from "node:test";
|
|
6
|
+
import { decodeJwt, generateKeyPair, SignJWT } from "jose";
|
|
7
|
+
import { createService as createProfileSyncService } from "../../users-core/src/server/common/services/authProfileSyncService.js";
|
|
8
|
+
import { createLocalAuthRegisterHookDecorator, createLocalFileBackend } from "../src/server/lib/index.js";
|
|
9
|
+
import { sha256Base64url } from "../src/server/lib/tokens.js";
|
|
10
|
+
import { resolveConfig } from "../src/server/providers/AuthLocalProvider.js";
|
|
11
|
+
import {
|
|
12
|
+
APP_URL,
|
|
13
|
+
ATTEMPT_COOKIE,
|
|
14
|
+
approveAtProvider,
|
|
15
|
+
createService,
|
|
16
|
+
oidcProviderEntry,
|
|
17
|
+
sessionCookies,
|
|
18
|
+
startFakeGitHub,
|
|
19
|
+
startOidcProvider
|
|
20
|
+
} from "../test-support/oauthHarness.js";
|
|
21
|
+
|
|
22
|
+
const MICROSOFT_CONSUMER_TENANT_ID = "9188040d-6c67-4c5b-b112-36a304b66dad";
|
|
23
|
+
const UNVERIFIED = { statusCode: 401, code: "auth.local.oauth.unverified" };
|
|
24
|
+
const EXPIRED = { statusCode: 400, code: "auth.local.oauth.expired" };
|
|
25
|
+
|
|
26
|
+
async function fileBackend() {
|
|
27
|
+
const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-local-oauth-"));
|
|
28
|
+
return createLocalFileBackend({ storeDir });
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The users-core profile sync service over memory repositories. Its lifecycle
|
|
33
|
+
* contributor stands where workspaces-core registers personal-workspace
|
|
34
|
+
* provisioning (`afterIdentityProfileSynced`).
|
|
35
|
+
*/
|
|
36
|
+
function createUsersProfileSync() {
|
|
37
|
+
const profiles = [];
|
|
38
|
+
const provisioned = [];
|
|
39
|
+
const profileProjector = createProfileSyncService({
|
|
40
|
+
userProfilesRepository: {
|
|
41
|
+
async findByIdentity(identity) {
|
|
42
|
+
return profiles.find((profile) => profile.authProviderUserSid === identity.providerUserId) || null;
|
|
43
|
+
},
|
|
44
|
+
async upsert(payload) {
|
|
45
|
+
const existing = profiles.find((profile) => profile.authProviderUserSid === payload.authProviderUserSid);
|
|
46
|
+
if (existing) return Object.assign(existing, payload);
|
|
47
|
+
const profile = { id: String(profiles.length + 1), ...payload };
|
|
48
|
+
profiles.push(profile);
|
|
49
|
+
return profile;
|
|
50
|
+
},
|
|
51
|
+
async withTransaction(work) {
|
|
52
|
+
return work({});
|
|
53
|
+
}
|
|
54
|
+
},
|
|
55
|
+
userSettingsRepository: {
|
|
56
|
+
async ensureForUserId(userId) {
|
|
57
|
+
return { userId };
|
|
58
|
+
}
|
|
59
|
+
},
|
|
60
|
+
resolveLifecycleContributors: () => [{
|
|
61
|
+
contributorId: "workspaces.provisioning",
|
|
62
|
+
async afterIdentityProfileSynced({ profile, created }) {
|
|
63
|
+
if (created) provisioned.push(profile.email);
|
|
64
|
+
}
|
|
65
|
+
}]
|
|
66
|
+
});
|
|
67
|
+
return { profileProjector, profiles, provisioned };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function googleSetup(t, { account, profileProjector = null } = {}) {
|
|
71
|
+
const issuer = await startOidcProvider({ account });
|
|
72
|
+
t.after(() => issuer.close());
|
|
73
|
+
const backend = await fileBackend();
|
|
74
|
+
const service = createService({ backend, profileProjector, oauthProviders: [oidcProviderEntry(issuer)] });
|
|
75
|
+
return { issuer, backend, service };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Re-signs the provider's ID token with changed claims, as a hostile token
|
|
79
|
+
// endpoint would; `key` signs it with a key the provider never published.
|
|
80
|
+
function tamperIdToken(t, issuer, change, { key = null } = {}) {
|
|
81
|
+
const realFetch = globalThis.fetch;
|
|
82
|
+
t.mock.method(globalThis, "fetch", async (url, options) => {
|
|
83
|
+
const response = await realFetch(url, options);
|
|
84
|
+
if (!String(url).endsWith("/token")) return response;
|
|
85
|
+
const body = await response.json();
|
|
86
|
+
const claims = { ...decodeJwt(body.id_token), ...change };
|
|
87
|
+
body.id_token = key
|
|
88
|
+
? await new SignJWT(claims).setProtectedHeader({ alg: "RS256", kid: "test-key" }).sign(key)
|
|
89
|
+
: await issuer.sign(claims);
|
|
90
|
+
return Response.json(body, { status: response.status });
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
test("a first Google sign-in creates the user like register, provisions it, and keeps no provider tokens", async (t) => {
|
|
95
|
+
const usersSync = createUsersProfileSync();
|
|
96
|
+
const { issuer, backend, service: baseService } = await googleSetup(t, { profileProjector: usersSync.profileProjector });
|
|
97
|
+
const registered = [];
|
|
98
|
+
const service = createLocalAuthRegisterHookDecorator({
|
|
99
|
+
hook: { blocking: true, handle: (payload) => registered.push(payload.actor.email) }
|
|
100
|
+
}).decorateAuthService(baseService);
|
|
101
|
+
|
|
102
|
+
assert.deepEqual(service.getCapabilities().features.oauthLogin.providers, [{ id: "google", label: "Google" }]);
|
|
103
|
+
const { started, input, request } = await approveAtProvider(service);
|
|
104
|
+
assert.equal(new URL(started.url).searchParams.get("code_challenge_method"), "S256");
|
|
105
|
+
assert.ok(new URL(started.url).searchParams.get("nonce"));
|
|
106
|
+
assert.equal(new URL(started.url).searchParams.get("redirect_uri"), `${APP_URL}/auth/login`);
|
|
107
|
+
|
|
108
|
+
const result = await service.oauthComplete(input, request);
|
|
109
|
+
assert.equal(result.actor.email, issuer.account.email);
|
|
110
|
+
assert.equal(result.actor.displayName, issuer.account.name);
|
|
111
|
+
assert.equal(result.provider, "google");
|
|
112
|
+
assert.equal(result.returnTo, "/home");
|
|
113
|
+
assert.equal(result.session.purpose, "normal");
|
|
114
|
+
assert.deepEqual(usersSync.provisioned, [issuer.account.email]);
|
|
115
|
+
assert.deepEqual(registered, [issuer.account.email]);
|
|
116
|
+
|
|
117
|
+
// An ordinary local session signs the person in; the account has no password.
|
|
118
|
+
const authenticated = await service.authenticateRequest({ cookies: sessionCookies(result.session) });
|
|
119
|
+
assert.equal(authenticated.authenticated, true);
|
|
120
|
+
assert.equal(authenticated.actor.appUserId, "1");
|
|
121
|
+
await assert.rejects(service.login({ email: issuer.account.email, password: "anything at all" }),
|
|
122
|
+
{ code: "auth.login.invalidCredentials" });
|
|
123
|
+
|
|
124
|
+
const stored = await fs.readFile(path.join(backend.storeDir, "identities.passwd"), "utf8");
|
|
125
|
+
assert.equal(stored.trim().split("\n").length, 1);
|
|
126
|
+
const attempts = await fs.readFile(path.join(backend.storeDir, "oauth-attempts.passwd"), "utf8");
|
|
127
|
+
assert.equal(attempts, "", "a completed attempt is deleted");
|
|
128
|
+
for (const file of await fs.readdir(backend.storeDir)) {
|
|
129
|
+
const content = await fs.readFile(path.join(backend.storeDir, file), "utf8").catch(() => "");
|
|
130
|
+
assert.doesNotMatch(content, /eyJ/u, `${file} holds no provider token`);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// A second sign-in finds the same user and provisions nothing new.
|
|
134
|
+
const again = await approveAtProvider(service);
|
|
135
|
+
const second = await service.oauthComplete(again.input, again.request);
|
|
136
|
+
assert.equal(second.actor.providerUserId, result.actor.providerUserId);
|
|
137
|
+
assert.deepEqual(usersSync.provisioned, [issuer.account.email]);
|
|
138
|
+
assert.deepEqual(registered, [issuer.account.email]);
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
test("a verified email that matches an existing account signs it in and links Google; later sign-ins match the subject", async (t) => {
|
|
142
|
+
const { issuer, service } = await googleSetup(t);
|
|
143
|
+
const existing = await service.register({ email: issuer.account.email, password: "correct horse battery" });
|
|
144
|
+
|
|
145
|
+
const first = await approveAtProvider(service);
|
|
146
|
+
const linked = await service.oauthComplete(first.input, first.request);
|
|
147
|
+
assert.equal(linked.actor.providerUserId, existing.actor.providerUserId);
|
|
148
|
+
assert.equal(linked.registered, false);
|
|
149
|
+
|
|
150
|
+
// The provider now reports another address: the subject still finds the account.
|
|
151
|
+
const realFetch = globalThis.fetch;
|
|
152
|
+
t.mock.method(globalThis, "fetch", async (url, options) => {
|
|
153
|
+
const response = await realFetch(url, options);
|
|
154
|
+
if (!String(url).endsWith("/me")) return response;
|
|
155
|
+
const body = await response.json();
|
|
156
|
+
return Response.json({ ...body, email: "renamed@example.test" }, { status: response.status });
|
|
157
|
+
});
|
|
158
|
+
const later = await approveAtProvider(service);
|
|
159
|
+
const again = await service.oauthComplete(later.input, later.request);
|
|
160
|
+
assert.equal(again.actor.providerUserId, existing.actor.providerUserId);
|
|
161
|
+
assert.equal(again.actor.email, issuer.account.email);
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
test("a callback with the wrong state, another browser's attempt, or a used attempt is refused", async (t) => {
|
|
165
|
+
const { backend, service } = await googleSetup(t);
|
|
166
|
+
const { input, request } = await approveAtProvider(service);
|
|
167
|
+
await assert.rejects(service.oauthComplete({ ...input, state: "not-the-state" }, request), EXPIRED);
|
|
168
|
+
// The refused try consumed the attempt: the right state can no longer use it.
|
|
169
|
+
await assert.rejects(service.oauthComplete(input, request), EXPIRED);
|
|
170
|
+
|
|
171
|
+
const next = await approveAtProvider(service);
|
|
172
|
+
await assert.rejects(service.oauthComplete(next.input, { cookies: {} }), EXPIRED, "no attempt cookie in this browser");
|
|
173
|
+
const other = await service.oauthStart({ provider: "google" });
|
|
174
|
+
await assert.rejects(service.oauthComplete(next.input, { cookies: { [ATTEMPT_COOKIE]: other.attempt } }), EXPIRED);
|
|
175
|
+
|
|
176
|
+
const stale = await approveAtProvider(service);
|
|
177
|
+
await backend.withTransaction(async (tx) => {
|
|
178
|
+
const attempt = await tx.oauthAttempts.take(sha256Base64url(stale.started.attempt));
|
|
179
|
+
await tx.oauthAttempts.create({ ...attempt, expiresAt: new Date(Date.now() - 1000).toISOString() });
|
|
180
|
+
});
|
|
181
|
+
await assert.rejects(service.oauthComplete(stale.input, stale.request), EXPIRED, "an attempt older than ten minutes");
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
test("an ID token with the wrong nonce, audience or issuer, or signed by another key, is refused", async (t) => {
|
|
185
|
+
const { privateKey: foreignKey } = await generateKeyPair("RS256");
|
|
186
|
+
const cases = [
|
|
187
|
+
["nonce", { nonce: "another-nonce" }],
|
|
188
|
+
["audience", { aud: "another-app" }],
|
|
189
|
+
["issuer", { iss: "https://attacker.example" }],
|
|
190
|
+
["expiry", { exp: Math.floor(Date.now() / 1000) - 600 }]
|
|
191
|
+
];
|
|
192
|
+
for (const [reason, change] of cases) {
|
|
193
|
+
await t.test(reason, async (st) => {
|
|
194
|
+
const { issuer, backend, service } = await googleSetup(st);
|
|
195
|
+
tamperIdToken(st, issuer, change);
|
|
196
|
+
const { input, request } = await approveAtProvider(service);
|
|
197
|
+
await assert.rejects(service.oauthComplete(input, request), UNVERIFIED);
|
|
198
|
+
assert.equal(await backend.withTransaction((tx) => tx.users.findByEmail(issuer.account.email)), null);
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
await t.test("signature", async (st) => {
|
|
202
|
+
const { issuer, backend, service } = await googleSetup(st);
|
|
203
|
+
tamperIdToken(st, issuer, {}, { key: foreignKey });
|
|
204
|
+
const { input, request } = await approveAtProvider(service);
|
|
205
|
+
await assert.rejects(service.oauthComplete(input, request), UNVERIFIED);
|
|
206
|
+
assert.equal(await backend.withTransaction((tx) => tx.users.findByEmail(issuer.account.email)), null);
|
|
207
|
+
});
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
test("an email Google has not verified never reaches an account", async (t) => {
|
|
211
|
+
const { backend, service } = await googleSetup(t, {
|
|
212
|
+
account: { sub: "usr_test_eve", email: "eve@example.test", name: "Eve", emailVerified: false }
|
|
213
|
+
});
|
|
214
|
+
const { input, request } = await approveAtProvider(service);
|
|
215
|
+
await assert.rejects(service.oauthComplete(input, request), {
|
|
216
|
+
statusCode: 401,
|
|
217
|
+
code: "auth.local.oauth.emailUnverified",
|
|
218
|
+
message: "Google has not confirmed your email address, so this account can't sign in here."
|
|
219
|
+
});
|
|
220
|
+
assert.equal(await backend.withTransaction((tx) => tx.users.findByEmail("eve@example.test")), null);
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
test("Microsoft accepts personal accounts and work accounts on a verified domain only", async (t) => {
|
|
224
|
+
const cases = [
|
|
225
|
+
["personal account", { tid: MICROSOFT_CONSUMER_TENANT_ID, email: "ada@outlook.example" }, true],
|
|
226
|
+
["work account, verified domain", { tid: "11111111-2222-3333-4444-555555555555", xms_edov: true, email: "ada@contoso.example" }, true],
|
|
227
|
+
["work account, unverified domain", { tid: "11111111-2222-3333-4444-555555555555", xms_edov: false, email: "ceo@victim.example" }, "auth.local.oauth.emailUnverified"],
|
|
228
|
+
["work account, no domain claim", { tid: "11111111-2222-3333-4444-555555555555", email: "ceo@victim.example" }, "auth.local.oauth.emailUnverified"],
|
|
229
|
+
["no email claim", { tid: MICROSOFT_CONSUMER_TENANT_ID, email: undefined }, "auth.local.oauth.emailMissing"]
|
|
230
|
+
];
|
|
231
|
+
for (const [reason, claims, outcome] of cases) {
|
|
232
|
+
await t.test(reason, async (st) => {
|
|
233
|
+
const issuer = await startOidcProvider();
|
|
234
|
+
st.after(() => issuer.close());
|
|
235
|
+
const service = createService({
|
|
236
|
+
backend: await fileBackend(),
|
|
237
|
+
oauthProviders: [oidcProviderEntry(issuer, { id: "microsoft", label: "Microsoft" })]
|
|
238
|
+
});
|
|
239
|
+
tamperIdToken(st, issuer, claims);
|
|
240
|
+
const { input, request } = await approveAtProvider(service, { provider: "microsoft" });
|
|
241
|
+
if (outcome === true) {
|
|
242
|
+
const result = await service.oauthComplete(input, request);
|
|
243
|
+
assert.equal(result.actor.email, claims.email);
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
await assert.rejects(service.oauthComplete(input, request), { statusCode: 401, code: outcome });
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
test("GitHub signs in with the primary verified address and refuses an unverified one", async (t) => {
|
|
252
|
+
const github = await startFakeGitHub();
|
|
253
|
+
t.after(() => github.close());
|
|
254
|
+
const backend = await fileBackend();
|
|
255
|
+
const service = createService({ backend, oauthProviders: [github.provider] });
|
|
256
|
+
|
|
257
|
+
const { started, input, request } = await approveAtProvider(service, { provider: "github" });
|
|
258
|
+
assert.equal(new URL(started.url).searchParams.get("scope"), "read:user user:email");
|
|
259
|
+
assert.equal(new URL(started.url).searchParams.get("nonce"), null);
|
|
260
|
+
const result = await service.oauthComplete(input, request);
|
|
261
|
+
assert.equal(result.actor.email, "ada@example.test");
|
|
262
|
+
assert.equal(result.actor.displayName, "Ada Lovelace");
|
|
263
|
+
|
|
264
|
+
github.state.user = { id: 5151, login: "mallory" };
|
|
265
|
+
github.state.emails = [
|
|
266
|
+
{ email: "ada@example.test", primary: false, verified: true },
|
|
267
|
+
{ email: "mallory@example.test", primary: true, verified: false }
|
|
268
|
+
];
|
|
269
|
+
const unverified = await approveAtProvider(service, { provider: "github" });
|
|
270
|
+
await assert.rejects(service.oauthComplete(unverified.input, unverified.request), {
|
|
271
|
+
statusCode: 401,
|
|
272
|
+
code: "auth.local.oauth.emailUnverified"
|
|
273
|
+
});
|
|
274
|
+
assert.equal(await backend.withTransaction((tx) => tx.users.findByEmail("mallory@example.test")), null);
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
test("account settings link and unlink providers, never removing the last sign-in method", async (t) => {
|
|
278
|
+
const issuer = await startOidcProvider();
|
|
279
|
+
const github = await startFakeGitHub({ emails: [{ email: "gh-ada@example.test", primary: true, verified: true }] });
|
|
280
|
+
t.after(async () => {
|
|
281
|
+
await issuer.close();
|
|
282
|
+
await github.close();
|
|
283
|
+
});
|
|
284
|
+
const service = createService({
|
|
285
|
+
backend: await fileBackend(),
|
|
286
|
+
oauthProviders: [oidcProviderEntry(issuer), github.provider]
|
|
287
|
+
});
|
|
288
|
+
const methods = async (cookies) => Object.fromEntries((await service.getSecurityStatus({ cookies })).authMethods
|
|
289
|
+
.map((method) => [method.id, { enabled: method.enabled, canEnable: method.canEnable ?? false, canDisable: method.canDisable }]));
|
|
290
|
+
|
|
291
|
+
// Signed up through Google: no password, so Google is the only sign-in method.
|
|
292
|
+
const signUp = await approveAtProvider(service);
|
|
293
|
+
const cookies = sessionCookies((await service.oauthComplete(signUp.input, signUp.request)).session);
|
|
294
|
+
assert.deepEqual(await methods(cookies), {
|
|
295
|
+
password: { enabled: false, canEnable: false, canDisable: false },
|
|
296
|
+
"oauth:google": { enabled: true, canEnable: false, canDisable: false },
|
|
297
|
+
"oauth:github": { enabled: false, canEnable: true, canDisable: false }
|
|
298
|
+
});
|
|
299
|
+
await assert.rejects(service.unlinkProvider({ cookies }, { provider: "google" }), {
|
|
300
|
+
statusCode: 409,
|
|
301
|
+
code: "auth.local.oauth.lastMethod"
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
// Linking GitHub, whose address differs, returns to settings without a new session.
|
|
305
|
+
const link = await approveAtProvider(service, { provider: "github", cookies, link: true, returnTo: "/account?section=sign-in-methods" });
|
|
306
|
+
const linked = await service.oauthComplete(link.input, link.request);
|
|
307
|
+
assert.equal(linked.session, null);
|
|
308
|
+
assert.equal(linked.returnTo, "/account?section=sign-in-methods");
|
|
309
|
+
assert.equal(linked.actor.email, issuer.account.email);
|
|
310
|
+
assert.deepEqual((await methods(cookies))["oauth:github"], { enabled: true, canEnable: false, canDisable: true });
|
|
311
|
+
|
|
312
|
+
const unlinked = await service.unlinkProvider({ cookies }, { provider: "google" });
|
|
313
|
+
assert.equal(unlinked.securityStatus.authMethods.find((method) => method.id === "oauth:google").enabled, false);
|
|
314
|
+
await assert.rejects(service.unlinkProvider({ cookies }, { provider: "github" }), { code: "auth.local.oauth.lastMethod" });
|
|
315
|
+
await assert.rejects(service.unlinkProvider({ cookies }, { provider: "google" }), { statusCode: 404, code: "auth.local.oauth.notLinked" });
|
|
316
|
+
|
|
317
|
+
// Another account cannot link the same GitHub identity.
|
|
318
|
+
const other = await service.register({ email: "grace@example.test", password: "correct horse battery" });
|
|
319
|
+
const otherCookies = sessionCookies(other.session);
|
|
320
|
+
const taken = await approveAtProvider(service, { provider: "github", cookies: otherCookies, link: true });
|
|
321
|
+
await assert.rejects(service.oauthComplete(taken.input, taken.request), {
|
|
322
|
+
statusCode: 409,
|
|
323
|
+
code: "auth.local.oauth.identityTaken",
|
|
324
|
+
message: "This GitHub account is already linked to another account."
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
// A link started by one account completes only in that account's session.
|
|
328
|
+
const hijack = await approveAtProvider(service, { cookies: otherCookies, link: true });
|
|
329
|
+
await assert.rejects(service.oauthComplete(hijack.input, { cookies: { ...cookies, [ATTEMPT_COOKIE]: hijack.started.attempt } }), {
|
|
330
|
+
code: "auth.session.required"
|
|
331
|
+
});
|
|
332
|
+
});
|
|
333
|
+
|
|
334
|
+
test("returnTo stays on the app's own origin", async (t) => {
|
|
335
|
+
const { service } = await googleSetup(t);
|
|
336
|
+
assert.equal((await service.oauthStart({ provider: "google", returnTo: "https://attacker.example/steal" })).returnTo, "/");
|
|
337
|
+
assert.equal((await service.oauthStart({ provider: "google", returnTo: "//attacker.example" })).returnTo, "/");
|
|
338
|
+
assert.equal((await service.oauthStart({ provider: "google", returnTo: `${APP_URL}/inbox` })).returnTo, `${APP_URL}/inbox`);
|
|
339
|
+
await assert.rejects(service.oauthStart({ provider: "facebook" }), { statusCode: 400, code: "auth.local.oauth.providerInvalid" });
|
|
340
|
+
});
|
|
341
|
+
|
|
342
|
+
test("a provider appears only when its client id and secret are both set", () => {
|
|
343
|
+
const base = { NODE_ENV: "test", AUTH_LOCAL_SESSION_SECRET: "secret", APP_PUBLIC_URL: APP_URL };
|
|
344
|
+
const config = (env) => resolveConfig({ appRoot: os.tmpdir(), backend: {}, env: { ...base, ...env }, logger: null });
|
|
345
|
+
|
|
346
|
+
assert.deepEqual(config({}).oauthProviders, []);
|
|
347
|
+
assert.deepEqual(config({
|
|
348
|
+
AUTH_GITHUB_CLIENT_ID: "gh-id",
|
|
349
|
+
AUTH_GITHUB_CLIENT_SECRET: "gh-secret",
|
|
350
|
+
AUTH_GOOGLE_CLIENT_ID: "g-id",
|
|
351
|
+
AUTH_GOOGLE_CLIENT_SECRET: "g-secret"
|
|
352
|
+
}).oauthProviders.map(({ id, clientId }) => [id, clientId]), [["google", "g-id"], ["github", "gh-id"]]);
|
|
353
|
+
assert.equal(config({ AUTH_MICROSOFT_CLIENT_ID: "m-id", AUTH_MICROSOFT_CLIENT_SECRET: "m-secret" }).oauthProviders[0].issuer,
|
|
354
|
+
"https://login.microsoftonline.com/common/v2.0");
|
|
355
|
+
assert.throws(() => config({ AUTH_GOOGLE_CLIENT_ID: "g-id" }),
|
|
356
|
+
/AUTH_GOOGLE_CLIENT_ID and AUTH_GOOGLE_CLIENT_SECRET must be set together/u);
|
|
357
|
+
assert.throws(() => config({ APP_PUBLIC_URL: "", AUTH_GITHUB_CLIENT_ID: "id", AUTH_GITHUB_CLIENT_SECRET: "secret" }),
|
|
358
|
+
/APP_PUBLIC_URL is required when local auth OAuth sign-in is configured/u);
|
|
359
|
+
});
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import http from "node:http";
|
|
3
|
+
import { once } from "node:events";
|
|
4
|
+
import { followAuthorization, startMockIssuer } from "../../auth-provider-oidc-core/test-support/mockIssuer.js";
|
|
5
|
+
import { createLocalAuthService } from "../src/server/lib/service.js";
|
|
6
|
+
|
|
7
|
+
const APP_URL = "http://localhost:5173";
|
|
8
|
+
const REDIRECT_URI = `${APP_URL}/auth/login`;
|
|
9
|
+
const ATTEMPT_COOKIE = "jskit_local_oauth_attempt";
|
|
10
|
+
const CLIENT = Object.freeze({ clientId: "local-app", clientSecret: "local-app-secret-0123456789abcdef" });
|
|
11
|
+
|
|
12
|
+
/** A local OpenID Connect provider (Google or Microsoft stand-in) with this app as its static client. */
|
|
13
|
+
async function startOidcProvider({ account } = {}) {
|
|
14
|
+
return startMockIssuer({
|
|
15
|
+
account,
|
|
16
|
+
staticClients: [{
|
|
17
|
+
client_id: CLIENT.clientId,
|
|
18
|
+
client_secret: CLIENT.clientSecret,
|
|
19
|
+
redirect_uris: [REDIRECT_URI],
|
|
20
|
+
grant_types: ["authorization_code"],
|
|
21
|
+
response_types: ["code"],
|
|
22
|
+
token_endpoint_auth_method: "client_secret_post"
|
|
23
|
+
}]
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function readBody(req) {
|
|
28
|
+
return new Promise((resolve) => {
|
|
29
|
+
let body = "";
|
|
30
|
+
req.on("data", (chunk) => { body += chunk; });
|
|
31
|
+
req.on("end", () => resolve(body));
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* GitHub's OAuth 2.0 endpoints and the two API reads sign-in makes. The token
|
|
37
|
+
* endpoint checks the client secret, redirect address and PKCE verifier.
|
|
38
|
+
*/
|
|
39
|
+
async function startFakeGitHub({ user = { id: 4242, login: "ada", name: "Ada Lovelace" }, emails } = {}) {
|
|
40
|
+
const grants = new Map();
|
|
41
|
+
const accessToken = "gho_fake_access_token";
|
|
42
|
+
const state = {
|
|
43
|
+
user,
|
|
44
|
+
emails: emails || [{ email: "ada@example.test", primary: true, verified: true }]
|
|
45
|
+
};
|
|
46
|
+
const server = http.createServer(async (req, res) => {
|
|
47
|
+
const url = new URL(req.url, "http://github.test");
|
|
48
|
+
const json = (status, body) => {
|
|
49
|
+
res.statusCode = status;
|
|
50
|
+
res.setHeader("content-type", "application/json");
|
|
51
|
+
res.end(JSON.stringify(body));
|
|
52
|
+
};
|
|
53
|
+
if (url.pathname === "/login/oauth/authorize") {
|
|
54
|
+
const code = `gh_code_${grants.size + 1}`;
|
|
55
|
+
grants.set(code, {
|
|
56
|
+
challenge: url.searchParams.get("code_challenge"),
|
|
57
|
+
redirectUri: url.searchParams.get("redirect_uri")
|
|
58
|
+
});
|
|
59
|
+
const back = new URL(url.searchParams.get("redirect_uri"));
|
|
60
|
+
back.searchParams.set("code", code);
|
|
61
|
+
back.searchParams.set("state", url.searchParams.get("state"));
|
|
62
|
+
res.statusCode = 302;
|
|
63
|
+
res.setHeader("location", back.href);
|
|
64
|
+
res.end();
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (url.pathname === "/login/oauth/access_token" && req.method === "POST") {
|
|
68
|
+
const form = new URLSearchParams(await readBody(req));
|
|
69
|
+
const grant = grants.get(form.get("code"));
|
|
70
|
+
grants.delete(form.get("code"));
|
|
71
|
+
const verifierMatches = grant &&
|
|
72
|
+
createHash("sha256").update(form.get("code_verifier") || "").digest("base64url") === grant.challenge;
|
|
73
|
+
if (!grant || !verifierMatches || form.get("client_secret") !== CLIENT.clientSecret ||
|
|
74
|
+
form.get("redirect_uri") !== grant.redirectUri) {
|
|
75
|
+
json(400, { error: "bad_verification_code" });
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
json(200, { access_token: accessToken, token_type: "bearer", scope: "read:user,user:email" });
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
if (req.headers.authorization !== `Bearer ${accessToken}`) {
|
|
82
|
+
json(401, { message: "Bad credentials" });
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
if (url.pathname === "/user") {
|
|
86
|
+
json(200, state.user);
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
if (url.pathname === "/user/emails") {
|
|
90
|
+
json(200, state.emails);
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
json(404, { message: "Not Found" });
|
|
94
|
+
});
|
|
95
|
+
server.listen(0, "127.0.0.1");
|
|
96
|
+
await once(server, "listening");
|
|
97
|
+
const origin = `http://127.0.0.1:${server.address().port}`;
|
|
98
|
+
return {
|
|
99
|
+
state,
|
|
100
|
+
provider: {
|
|
101
|
+
id: "github",
|
|
102
|
+
label: "GitHub",
|
|
103
|
+
...CLIENT,
|
|
104
|
+
authorizationEndpoint: `${origin}/login/oauth/authorize`,
|
|
105
|
+
tokenEndpoint: `${origin}/login/oauth/access_token`,
|
|
106
|
+
apiUrl: origin
|
|
107
|
+
},
|
|
108
|
+
async close() {
|
|
109
|
+
server.closeAllConnections?.();
|
|
110
|
+
server.close();
|
|
111
|
+
await once(server, "close");
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function oidcProviderEntry(issuer, { id = "google", label = "Google" } = {}) {
|
|
117
|
+
return { id, label, ...CLIENT, issuer: issuer.issuer };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function createService({ backend, oauthProviders, profileProjector = null }) {
|
|
121
|
+
return createLocalAuthService({
|
|
122
|
+
backend,
|
|
123
|
+
profileProjector,
|
|
124
|
+
config: {
|
|
125
|
+
sessionSecret: "oauth-test-session-secret",
|
|
126
|
+
nodeEnv: "test",
|
|
127
|
+
appPublicUrl: APP_URL,
|
|
128
|
+
oauthProviders
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function sessionCookies(session) {
|
|
134
|
+
return { jskit_local_access_token: session.access_token, jskit_local_refresh_token: session.refresh_token };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Starts a sign-in (or, with `link`, a link for the signed-in `cookies`), lets
|
|
139
|
+
* the provider approve it, and returns the callback input and browser request.
|
|
140
|
+
*/
|
|
141
|
+
async function approveAtProvider(service, { provider = "google", returnTo = "/home", cookies = {}, link = false } = {}) {
|
|
142
|
+
const started = link
|
|
143
|
+
? await service.startProviderLink({ cookies }, { provider, returnTo })
|
|
144
|
+
: await service.oauthStart({ provider, returnTo });
|
|
145
|
+
const callback = await followAuthorization(started.url, { redirectPrefix: REDIRECT_URI });
|
|
146
|
+
return {
|
|
147
|
+
started,
|
|
148
|
+
input: {
|
|
149
|
+
provider,
|
|
150
|
+
code: callback.searchParams.get("code"),
|
|
151
|
+
state: callback.searchParams.get("state"),
|
|
152
|
+
iss: callback.searchParams.get("iss") || undefined
|
|
153
|
+
},
|
|
154
|
+
request: { cookies: { ...cookies, [ATTEMPT_COOKIE]: started.attempt } }
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export {
|
|
159
|
+
APP_URL,
|
|
160
|
+
ATTEMPT_COOKIE,
|
|
161
|
+
approveAtProvider,
|
|
162
|
+
createService,
|
|
163
|
+
oidcProviderEntry,
|
|
164
|
+
sessionCookies,
|
|
165
|
+
startFakeGitHub,
|
|
166
|
+
startOidcProvider
|
|
167
|
+
};
|