@jskit-ai/auth-provider-local-core 0.2.10 → 0.2.12
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/CHANGELOG.md +13 -0
- package/locales/en.json +10 -1
- package/package.json +7 -6
- package/src/server/lib/accounts.js +94 -34
- package/src/server/lib/config.js +83 -7
- package/src/server/lib/emailConfirmation.js +188 -0
- package/src/server/lib/fileBackend.js +104 -222
- package/src/server/lib/fileRecords.js +323 -0
- package/src/server/lib/firstAccountSetup.js +186 -0
- package/src/server/lib/index.js +2 -0
- package/src/server/lib/oauthFlows.js +16 -1
- package/src/server/lib/passwordFlows.js +7 -3
- package/src/server/lib/registerHookDecorator.js +15 -2
- package/src/server/lib/service.js +42 -4
- package/src/server/lib/signInThrottle.js +123 -0
- package/src/server/providers/AuthLocalProvider.js +18 -3
- package/src/server/types.js +47 -2
- package/test/codedTexts.test.js +1 -1
- package/test/emailConfirmation.test.js +77 -0
- package/test/firstAccountSetup.test.js +202 -0
- package/test/oauthSignIn.test.js +34 -1
- package/test/packageMetadata.test.js +2 -1
- package/test/providerRuntime.test.js +140 -4
- package/test/signInThrottle.test.js +88 -0
- package/test-support/emailConfirmationScenario.js +86 -0
- package/test-support/localService.js +11 -3
- package/test-support/oauthHarness.js +4 -2
- package/test-support/signInThrottleScenario.js +71 -0
package/src/server/types.js
CHANGED
|
@@ -9,9 +9,10 @@
|
|
|
9
9
|
* create(input: object): Promise<object>,
|
|
10
10
|
* findById(userId: string): Promise<object | null>,
|
|
11
11
|
* findByEmail(email: string): Promise<object | null>,
|
|
12
|
+
* hasAny(): Promise<boolean>,
|
|
12
13
|
* updatePassword(userId: string, passwordRecord: object): Promise<object | null>,
|
|
13
14
|
* updateProfile(userId: string, updates: object): Promise<object | null>
|
|
14
|
-
* }} users
|
|
15
|
+
* }} users `hasAny` answers whether any account exists.
|
|
15
16
|
* @property {{
|
|
16
17
|
* create(input: object): Promise<object>,
|
|
17
18
|
* findById(sessionId: string): Promise<object | null>,
|
|
@@ -36,11 +37,48 @@
|
|
|
36
37
|
* take(browserKeyHash: string): Promise<object | null>,
|
|
37
38
|
* deleteExpired(now: string): Promise<number>
|
|
38
39
|
* }} oauthAttempts
|
|
40
|
+
* @property {{
|
|
41
|
+
* find(email: string): Promise<AuthLocalSignInFailures | null>,
|
|
42
|
+
* save(record: AuthLocalSignInFailures): Promise<AuthLocalSignInFailures>,
|
|
43
|
+
* clear(email: string): Promise<number>,
|
|
44
|
+
* deleteBefore(lastFailedAt: string): Promise<number>
|
|
45
|
+
* }} signInFailures One record per account email, existing or not; `save`
|
|
46
|
+
* replaces the email's record and `deleteBefore` removes those whose last failure is older.
|
|
47
|
+
* @property {{
|
|
48
|
+
* save(record: AuthLocalRegistration): Promise<AuthLocalRegistration>,
|
|
49
|
+
* findByEmail(email: string): Promise<AuthLocalRegistration | null>,
|
|
50
|
+
* findByTokenHash(tokenHash: string): Promise<AuthLocalRegistration | null>,
|
|
51
|
+
* delete(email: string): Promise<number>,
|
|
52
|
+
* deleteExpired(now: string): Promise<number>
|
|
53
|
+
* }} registrations Registrations waiting for their email to be confirmed, one per
|
|
54
|
+
* email; `save` replaces the email's registration. Used only while
|
|
55
|
+
* AUTH_LOCAL_EMAIL_CONFIRMATION is on.
|
|
56
|
+
*/
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* A registration waiting for its email to be confirmed: the account it will
|
|
60
|
+
* create, the hash of its confirmation link's code, and when that link
|
|
61
|
+
* expires. Times are ISO strings.
|
|
62
|
+
* @typedef {object} AuthLocalRegistration
|
|
63
|
+
* @property {string} email
|
|
64
|
+
* @property {string} displayName
|
|
65
|
+
* @property {object} password The stored password record, as users keep it.
|
|
66
|
+
* @property {{ token: string, source: string } | null} invitation The invitation it registered with.
|
|
67
|
+
* @property {string} tokenHash
|
|
68
|
+
* @property {string} createdAt
|
|
69
|
+
* @property {string} expiresAt
|
|
70
|
+
*/
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* An account's recent failed sign-ins: how many, the last one, and when it may
|
|
74
|
+
* try again ("" when it need not wait). Times are ISO strings.
|
|
75
|
+
* @typedef {{ email: string, failures: number, lastFailedAt: string, lockedUntil: string }} AuthLocalSignInFailures
|
|
39
76
|
*/
|
|
40
77
|
|
|
41
78
|
/**
|
|
42
79
|
* The `auth.local.backend` capability: where local auth keeps its users,
|
|
43
|
-
* sessions, recovery tokens, linked identities
|
|
80
|
+
* sessions, recovery tokens, linked identities, OAuth attempts, failed
|
|
81
|
+
* sign-ins and unconfirmed registrations. Without
|
|
44
82
|
* one, local auth keeps them in files under AUTH_LOCAL_STORE_DIR;
|
|
45
83
|
* `@jskit-ai/auth-provider-local-db-core` provides one that keeps them in the
|
|
46
84
|
* database. Each backend implements this contract.
|
|
@@ -65,8 +103,15 @@
|
|
|
65
103
|
* @typedef {(delivery: { email: string, recoveryUrl: string }) => Promise<void>} AuthLocalRecoverySender
|
|
66
104
|
*/
|
|
67
105
|
|
|
106
|
+
/**
|
|
107
|
+
* The `auth.local.confirmation-sender` capability: sends a new registration's
|
|
108
|
+
* email confirmation link to the address it registered.
|
|
109
|
+
* @typedef {(delivery: { email: string, confirmationUrl: string }) => Promise<void>} AuthLocalConfirmationSender
|
|
110
|
+
*/
|
|
111
|
+
|
|
68
112
|
/** @typedef {ReturnType<typeof import("./lib/config.js").resolveLocalAuthConfig>} AuthLocalConfig */
|
|
69
113
|
/** @typedef {AuthLocalConfig["oauthProviders"][number]} AuthLocalOAuthProvider */
|
|
114
|
+
/** @typedef {ReturnType<typeof import("./lib/firstAccountSetup.js").createFirstAccountSetup>} AuthLocalFirstAccountSetup */
|
|
70
115
|
/** @typedef {ReturnType<typeof import("./lib/passwords.js").normalizePasswordStrategy>} AuthLocalPasswords */
|
|
71
116
|
/** @typedef {ReturnType<typeof import("./lib/sessions.js").createLocalSessions>} AuthLocalSessions */
|
|
72
117
|
|
package/test/codedTexts.test.js
CHANGED
|
@@ -54,7 +54,7 @@ test("local auth errors carry codes whose English is the thrown message", async
|
|
|
54
54
|
await assert.rejects(() => service.updateDisplayName({ cookies: {} }, { displayName: "Ada" }),
|
|
55
55
|
(error) => assertCoded(error, "auth.session.required"));
|
|
56
56
|
|
|
57
|
-
const disabled = await createService(t, { NODE_ENV: "production", AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "
|
|
57
|
+
const disabled = await createService(t, { NODE_ENV: "production", AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "" });
|
|
58
58
|
await assert.rejects(() => disabled.requestPasswordReset({ email: "ada@example.com" }),
|
|
59
59
|
(error) => assertCoded(error, "auth.local.recovery.notConfigured"));
|
|
60
60
|
});
|
|
@@ -0,0 +1,77 @@
|
|
|
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 { invitationAsGiven } from "@jskit-ai/auth-core/server/authExtensions";
|
|
7
|
+
import { createLocalAuthService, createLocalFileBackend } from "../src/server/lib/index.js";
|
|
8
|
+
import { localServiceOptions } from "../test-support/localService.js";
|
|
9
|
+
import { exerciseEmailConfirmation } from "../test-support/emailConfirmationScenario.js";
|
|
10
|
+
|
|
11
|
+
const PASSWORD = "correct horse battery staple";
|
|
12
|
+
|
|
13
|
+
async function startService(t, { env = {}, ...overrides } = {}) {
|
|
14
|
+
const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-confirmation-"));
|
|
15
|
+
t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
|
|
16
|
+
const backend = createLocalFileBackend({ storeDir });
|
|
17
|
+
// "" leaves AUTH_LOCAL_EMAIL_CONFIRMATION unset: confirmation on, its default.
|
|
18
|
+
const options = localServiceOptions({ env: { AUTH_LOCAL_EMAIL_CONFIRMATION: "", ...env } });
|
|
19
|
+
return { service: createLocalAuthService({ ...options, backend, ...overrides }), storeDir };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
test("registration waits for its email to be confirmed, with a hashed, single-use, expiring link (file backend)", async (t) => {
|
|
23
|
+
t.mock.timers.enable({ apis: ["Date"], now: Date.parse("2026-11-06T10:00:00.000Z") });
|
|
24
|
+
const { service, storeDir } = await startService(t);
|
|
25
|
+
assert.deepEqual(
|
|
26
|
+
[service.getCapabilities().features.emailConfirmation, service.getCapabilities().features.emailConfirmationCode],
|
|
27
|
+
[true, true]
|
|
28
|
+
);
|
|
29
|
+
await exerciseEmailConfirmation(t, service, () =>
|
|
30
|
+
fs.readFile(path.join(storeDir, "registrations.passwd"), "utf8").catch(() => ""));
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test("AUTH_LOCAL_EMAIL_CONFIRMATION=false registers and signs in at once, and confirming is unsupported", async (t) => {
|
|
34
|
+
const { service } = await startService(t, { env: { AUTH_LOCAL_EMAIL_CONFIRMATION: "false" } });
|
|
35
|
+
const registered = await service.register({ email: "ada@example.com", password: PASSWORD });
|
|
36
|
+
assert.equal(registered.requiresEmailConfirmation, false);
|
|
37
|
+
assert.ok(registered.session);
|
|
38
|
+
assert.equal(service.getCapabilities().features.emailConfirmationCode, false);
|
|
39
|
+
await assert.rejects(async () => service.confirmRegistration({ token: "any" }), { code: "AUTH_OPERATION_UNSUPPORTED" });
|
|
40
|
+
await assert.rejects(async () => service.resendRegisterConfirmation({ email: "ada@example.com" }), {
|
|
41
|
+
code: "AUTH_OPERATION_UNSUPPORTED"
|
|
42
|
+
});
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test("an invitation is checked on registering and given to the account its confirmation creates", async (t) => {
|
|
46
|
+
const synced = [];
|
|
47
|
+
const { service } = await startService(t, {
|
|
48
|
+
invitationContextResolver: {
|
|
49
|
+
async resolveInvitationContext(invitation) {
|
|
50
|
+
if (invitation.token === "unusable") throw new Error("This invitation cannot be used.");
|
|
51
|
+
return invitationAsGiven.resolveInvitationContext(invitation);
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
profileProjector: {
|
|
55
|
+
async syncIdentityProfile(profile, options) {
|
|
56
|
+
synced.push({ email: profile.email, source: options.source, token: options.invitation?.token });
|
|
57
|
+
return null;
|
|
58
|
+
},
|
|
59
|
+
async findByIdentity() {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
await assert.rejects(
|
|
65
|
+
service.register({ email: "guest@example.com", password: PASSWORD, invitation: { token: "unusable" } }),
|
|
66
|
+
/This invitation cannot be used\./u
|
|
67
|
+
);
|
|
68
|
+
const registered = await service.register({
|
|
69
|
+
email: "guest@example.com",
|
|
70
|
+
password: PASSWORD,
|
|
71
|
+
invitation: { token: "invite-1", source: "workspace-invite" }
|
|
72
|
+
});
|
|
73
|
+
assert.deepEqual(synced, []);
|
|
74
|
+
const token = new URL(registered.confirmationUrl).searchParams.get("confirmation_token");
|
|
75
|
+
await service.confirmRegistration({ token });
|
|
76
|
+
assert.deepEqual(synced, [{ email: "guest@example.com", source: "workspace-invite", token: "invite-1" }]);
|
|
77
|
+
});
|
|
@@ -0,0 +1,202 @@
|
|
|
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 {
|
|
7
|
+
SETUP_CODE_FILE,
|
|
8
|
+
createFirstAccountSetup,
|
|
9
|
+
createLocalAuthService,
|
|
10
|
+
createLocalFileBackend
|
|
11
|
+
} from "../src/server/lib/index.js";
|
|
12
|
+
import { localServiceOptions } from "../test-support/localService.js";
|
|
13
|
+
|
|
14
|
+
const PASSWORD = "correct horse battery staple";
|
|
15
|
+
const SETUP_CODE_PATTERN = /^[0-9A-HJKMNP-TV-Z]{5}(?:-[0-9A-HJKMNP-TV-Z]{5}){3}$/u;
|
|
16
|
+
const codeRequired = { status: 403, code: "auth.local.setup.codeRequired" };
|
|
17
|
+
const codeInvalid = { status: 403, code: "auth.local.setup.codeInvalid" };
|
|
18
|
+
|
|
19
|
+
async function temporaryStoreDir(t) {
|
|
20
|
+
const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-setup-"));
|
|
21
|
+
t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
|
|
22
|
+
return storeDir;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* A local auth server over the file store in `storeDir`, started as its
|
|
27
|
+
* provider starts it: production unless `env` says otherwise.
|
|
28
|
+
*/
|
|
29
|
+
async function startServer(storeDir, { env = {}, confirmationSender } = {}) {
|
|
30
|
+
const warnings = [];
|
|
31
|
+
const logger = { info() {}, warn: (fields, message) => warnings.push({ fields, message }), error() {}, debug() {} };
|
|
32
|
+
const options = localServiceOptions({
|
|
33
|
+
env: {
|
|
34
|
+
NODE_ENV: "production",
|
|
35
|
+
AUTH_LOCAL_STORE_DIR: storeDir,
|
|
36
|
+
AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "",
|
|
37
|
+
APP_PUBLIC_URL: "https://app.example.test",
|
|
38
|
+
...env
|
|
39
|
+
},
|
|
40
|
+
emailConfirmationSender: confirmationSender !== undefined
|
|
41
|
+
});
|
|
42
|
+
const backend = createLocalFileBackend({ storeDir });
|
|
43
|
+
const firstAccountSetup = createFirstAccountSetup({ backend, config: options.config, logger });
|
|
44
|
+
await firstAccountSetup.start();
|
|
45
|
+
const service = createLocalAuthService({
|
|
46
|
+
...options,
|
|
47
|
+
backend,
|
|
48
|
+
logger,
|
|
49
|
+
firstAccountSetup,
|
|
50
|
+
...(confirmationSender && { confirmationSender })
|
|
51
|
+
});
|
|
52
|
+
const logged = warnings.filter((warning) => warning.fields.firstAccountSetupCode);
|
|
53
|
+
return { service, warnings, setupCode: logged.at(-1)?.fields.firstAccountSetupCode || "" };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function waitingForFirstAccount(service) {
|
|
57
|
+
return service.getCapabilities().features.firstAccountSetupCode;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async function codeFile(storeDir) {
|
|
61
|
+
const file = path.join(storeDir, SETUP_CODE_FILE);
|
|
62
|
+
try {
|
|
63
|
+
return { text: await fs.readFile(file, "utf8"), mode: (await fs.stat(file)).mode & 0o777 };
|
|
64
|
+
} catch (error) {
|
|
65
|
+
if (error.code === "ENOENT") return null;
|
|
66
|
+
throw error;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
test("a production server without accounts asks its first registration for the setup code it logs, then never again", async (t) => {
|
|
71
|
+
const storeDir = await temporaryStoreDir(t);
|
|
72
|
+
const { service, warnings, setupCode } = await startServer(storeDir);
|
|
73
|
+
assert.match(setupCode, SETUP_CODE_PATTERN);
|
|
74
|
+
assert.deepEqual(warnings, [{
|
|
75
|
+
fields: { firstAccountSetupCode: setupCode, firstAccountSetupCodeFile: path.join(storeDir, SETUP_CODE_FILE) },
|
|
76
|
+
message: "Local auth has no account yet: register the first account with this setup code."
|
|
77
|
+
}]);
|
|
78
|
+
assert.deepEqual(await codeFile(storeDir), { text: `${setupCode}\n`, mode: 0o600 });
|
|
79
|
+
assert.equal(waitingForFirstAccount(service), true);
|
|
80
|
+
|
|
81
|
+
await assert.rejects(service.register({ email: "owner@example.com", password: PASSWORD }), codeRequired);
|
|
82
|
+
await assert.rejects(
|
|
83
|
+
service.register({ email: "owner@example.com", password: PASSWORD, setupCode: "AAAAA-AAAAA-AAAAA-AAAAA" }),
|
|
84
|
+
codeInvalid
|
|
85
|
+
);
|
|
86
|
+
// Letter case, spaces and dashes do not matter.
|
|
87
|
+
const typed = setupCode.toLowerCase().replaceAll("-", " ");
|
|
88
|
+
const owner = await service.register({ email: "owner@example.com", password: PASSWORD, setupCode: typed });
|
|
89
|
+
assert.ok(owner.session.access_token);
|
|
90
|
+
|
|
91
|
+
// The first account exists: the code stops working and its file is gone.
|
|
92
|
+
assert.equal(waitingForFirstAccount(service), false);
|
|
93
|
+
assert.equal(await codeFile(storeDir), null);
|
|
94
|
+
const second = await service.register({ email: "second@example.com", password: PASSWORD });
|
|
95
|
+
assert.ok(second.session.access_token);
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
test("restarting while there is no account makes a new code, and the old one stops working", async (t) => {
|
|
99
|
+
const storeDir = await temporaryStoreDir(t);
|
|
100
|
+
const first = await startServer(storeDir);
|
|
101
|
+
const restarted = await startServer(storeDir);
|
|
102
|
+
assert.match(restarted.setupCode, SETUP_CODE_PATTERN);
|
|
103
|
+
assert.notEqual(restarted.setupCode, first.setupCode);
|
|
104
|
+
assert.equal((await codeFile(storeDir)).text, `${restarted.setupCode}\n`);
|
|
105
|
+
await assert.rejects(
|
|
106
|
+
restarted.service.register({ email: "owner@example.com", password: PASSWORD, setupCode: first.setupCode }),
|
|
107
|
+
codeInvalid
|
|
108
|
+
);
|
|
109
|
+
await restarted.service.register({ email: "owner@example.com", password: PASSWORD, setupCode: restarted.setupCode });
|
|
110
|
+
|
|
111
|
+
// Once an account exists, a restart makes no code and removes a leftover file.
|
|
112
|
+
await fs.writeFile(path.join(storeDir, SETUP_CODE_FILE), "LEFTOVER\n");
|
|
113
|
+
const later = await startServer(storeDir);
|
|
114
|
+
assert.equal(later.setupCode, "");
|
|
115
|
+
assert.deepEqual(later.warnings, []);
|
|
116
|
+
assert.equal(await codeFile(storeDir), null);
|
|
117
|
+
assert.equal(waitingForFirstAccount(later.service), false);
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
test("with email confirmation, the code admits the first registration, and confirming it ends the setup", async (t) => {
|
|
121
|
+
const storeDir = await temporaryStoreDir(t);
|
|
122
|
+
const links = [];
|
|
123
|
+
const { service, setupCode } = await startServer(storeDir, {
|
|
124
|
+
env: { AUTH_LOCAL_EMAIL_CONFIRMATION: "" },
|
|
125
|
+
confirmationSender: async ({ confirmationUrl }) => { links.push(new URL(confirmationUrl)); }
|
|
126
|
+
});
|
|
127
|
+
const waiting = await service.register({ email: "owner@example.com", password: PASSWORD, setupCode });
|
|
128
|
+
assert.equal(waiting.requiresEmailConfirmation, true);
|
|
129
|
+
// Until that registration is confirmed there is still no account, so the code is still needed.
|
|
130
|
+
assert.equal(waitingForFirstAccount(service), true);
|
|
131
|
+
await assert.rejects(service.register({ email: "early@example.com", password: PASSWORD }), codeRequired);
|
|
132
|
+
|
|
133
|
+
const owner = await service.confirmRegistration({ token: links[0].searchParams.get("confirmation_token") });
|
|
134
|
+
assert.equal(owner.actor.email, "owner@example.com");
|
|
135
|
+
assert.ok(owner.session.access_token);
|
|
136
|
+
assert.equal(waitingForFirstAccount(service), false);
|
|
137
|
+
assert.equal(await codeFile(storeDir), null);
|
|
138
|
+
assert.equal((await service.register({ email: "later@example.com", password: PASSWORD })).requiresEmailConfirmation, true);
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
test("development asks for no setup code", async (t) => {
|
|
142
|
+
const storeDir = await temporaryStoreDir(t);
|
|
143
|
+
const { service, warnings } = await startServer(storeDir, { env: { NODE_ENV: "development" } });
|
|
144
|
+
assert.deepEqual(warnings, []);
|
|
145
|
+
assert.equal(await codeFile(storeDir), null);
|
|
146
|
+
assert.equal(waitingForFirstAccount(service), false);
|
|
147
|
+
assert.ok((await service.register({ email: "dev@example.com", password: PASSWORD })).session.access_token);
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
test("a service composed without a started setup checks for an account on its first registration", async (t) => {
|
|
151
|
+
const storeDir = await temporaryStoreDir(t);
|
|
152
|
+
const options = localServiceOptions({
|
|
153
|
+
env: { NODE_ENV: "production", AUTH_LOCAL_STORE_DIR: storeDir, AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "" }
|
|
154
|
+
});
|
|
155
|
+
const service = createLocalAuthService({ ...options, backend: createLocalFileBackend({ storeDir }) });
|
|
156
|
+
await assert.rejects(service.register({ email: "owner@example.com", password: PASSWORD }), codeRequired);
|
|
157
|
+
const setupCode = (await codeFile(storeDir)).text.trim();
|
|
158
|
+
assert.match(setupCode, SETUP_CODE_PATTERN);
|
|
159
|
+
await service.register({ email: "owner@example.com", password: PASSWORD, setupCode });
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
test("a setup code supplied in AUTH_LOCAL_SETUP_CODE is asked for at every start, and is never logged or written", async (t) => {
|
|
163
|
+
const storeDir = await temporaryStoreDir(t);
|
|
164
|
+
const supplied = "Gq7v-K2pX_9mLr4TzWb8NcYd3HsJ5eFa";
|
|
165
|
+
await fs.writeFile(path.join(storeDir, SETUP_CODE_FILE), "LEFTOVER\n");
|
|
166
|
+
const first = await startServer(storeDir, { env: { AUTH_LOCAL_SETUP_CODE: supplied } });
|
|
167
|
+
assert.deepEqual(first.warnings, [{
|
|
168
|
+
fields: { firstAccountSetupCodeEnv: "AUTH_LOCAL_SETUP_CODE" },
|
|
169
|
+
message: "Local auth has no account yet: register the first account with the setup code in AUTH_LOCAL_SETUP_CODE."
|
|
170
|
+
}]);
|
|
171
|
+
assert.equal(JSON.stringify(first.warnings).includes(supplied), false);
|
|
172
|
+
assert.equal(await codeFile(storeDir), null);
|
|
173
|
+
assert.equal(waitingForFirstAccount(first.service), true);
|
|
174
|
+
|
|
175
|
+
// A restart, or a second server, asks for the same code.
|
|
176
|
+
const restarted = await startServer(storeDir, { env: { AUTH_LOCAL_SETUP_CODE: supplied } });
|
|
177
|
+
await assert.rejects(restarted.service.register({ email: "owner@example.com", password: PASSWORD }), codeRequired);
|
|
178
|
+
await assert.rejects(
|
|
179
|
+
restarted.service.register({ email: "owner@example.com", password: PASSWORD, setupCode: "AAAAA-AAAAA-AAAAA-AAAAA" }),
|
|
180
|
+
codeInvalid
|
|
181
|
+
);
|
|
182
|
+
const owner = await restarted.service.register({
|
|
183
|
+
email: "owner@example.com",
|
|
184
|
+
password: PASSWORD,
|
|
185
|
+
setupCode: supplied.toLowerCase()
|
|
186
|
+
});
|
|
187
|
+
assert.ok(owner.session.access_token);
|
|
188
|
+
assert.equal(waitingForFirstAccount(restarted.service), false);
|
|
189
|
+
|
|
190
|
+
// Once an account exists, the supplied code is not asked for and nothing is logged.
|
|
191
|
+
const later = await startServer(storeDir, { env: { AUTH_LOCAL_SETUP_CODE: supplied } });
|
|
192
|
+
assert.deepEqual(later.warnings, []);
|
|
193
|
+
assert.ok((await later.service.register({ email: "second@example.com", password: PASSWORD })).session.access_token);
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
test("a supplied setup code needs 20 letters and digits in production, and development ignores it", () => {
|
|
197
|
+
assert.throws(
|
|
198
|
+
() => localServiceOptions({ env: { NODE_ENV: "production", AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "", AUTH_LOCAL_SETUP_CODE: "short-code-1234" } }),
|
|
199
|
+
/AUTH_LOCAL_SETUP_CODE must have at least 20 letters and digits\./u
|
|
200
|
+
);
|
|
201
|
+
assert.equal(localServiceOptions({ env: { NODE_ENV: "development", AUTH_LOCAL_SETUP_CODE: "short" } }).config.setupCode, "");
|
|
202
|
+
});
|
package/test/oauthSignIn.test.js
CHANGED
|
@@ -7,7 +7,11 @@ import { decodeJwt, generateKeyPair, SignJWT } from "jose";
|
|
|
7
7
|
import { createService as createProfileSyncService } from "../../users-core/src/server/common/services/authProfileSyncService.js";
|
|
8
8
|
import { noAppProfiles } from "@jskit-ai/auth-core/server/noAppProfiles";
|
|
9
9
|
import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
|
|
10
|
-
import {
|
|
10
|
+
import {
|
|
11
|
+
createFirstAccountSetup,
|
|
12
|
+
createLocalAuthRegisterHookDecorator,
|
|
13
|
+
createLocalFileBackend
|
|
14
|
+
} from "../src/server/lib/index.js";
|
|
11
15
|
import { sha256Base64url } from "../src/server/lib/tokens.js";
|
|
12
16
|
import { resolveLocalAuthConfig } from "../src/server/lib/config.js";
|
|
13
17
|
import {
|
|
@@ -142,6 +146,35 @@ test("a first Google sign-in creates the user like register, provisions it, and
|
|
|
142
146
|
assert.deepEqual(registered, [issuer.account.email]);
|
|
143
147
|
});
|
|
144
148
|
|
|
149
|
+
test("while a production server waits for its first account, a Google sign-in cannot create it", async (t) => {
|
|
150
|
+
const issuer = await startOidcProvider();
|
|
151
|
+
t.after(() => issuer.close());
|
|
152
|
+
const backend = await fileBackend(t);
|
|
153
|
+
const codes = [];
|
|
154
|
+
const firstAccountSetup = createFirstAccountSetup({
|
|
155
|
+
backend,
|
|
156
|
+
config: { isProduction: true, storeDir: backend.storeDir },
|
|
157
|
+
logger: { warn: (fields) => codes.push(fields.firstAccountSetupCode) }
|
|
158
|
+
});
|
|
159
|
+
await firstAccountSetup.start();
|
|
160
|
+
const service = createService({
|
|
161
|
+
backend,
|
|
162
|
+
profileProjector: noAppProfiles,
|
|
163
|
+
oauthProviders: [oidcProviderEntry(issuer)],
|
|
164
|
+
firstAccountSetup
|
|
165
|
+
});
|
|
166
|
+
const refused = await approveAtProvider(service);
|
|
167
|
+
await assert.rejects(service.oauthComplete(refused.input, refused.request), {
|
|
168
|
+
statusCode: 403,
|
|
169
|
+
code: "auth.local.setup.codeRequired"
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
// Once the first account has registered with the code, Google sign-in creates accounts again.
|
|
173
|
+
await service.register({ email: "owner@example.com", password: "correct horse battery staple", setupCode: codes[0] });
|
|
174
|
+
const again = await approveAtProvider(service);
|
|
175
|
+
assert.equal((await service.oauthComplete(again.input, again.request)).actor.email, issuer.account.email);
|
|
176
|
+
});
|
|
177
|
+
|
|
145
178
|
test("a verified email that matches an existing account signs it in and links Google; later sign-ins match the subject", async (t) => {
|
|
146
179
|
const { issuer, service } = await googleSetup(t);
|
|
147
180
|
const existing = await service.register({ email: issuer.account.email, password: "correct horse battery" });
|
|
@@ -9,7 +9,8 @@ test("local auth has no package mutation or CI recipe", () => {
|
|
|
9
9
|
assert.equal(Object.hasOwn(packageMetadata, "mutations"), false);
|
|
10
10
|
});
|
|
11
11
|
|
|
12
|
-
test("local auth delegates recovery delivery to the application", () => {
|
|
12
|
+
test("local auth delegates recovery and confirmation delivery to the application", () => {
|
|
13
13
|
assert.equal(packageJson.dependencies?.nodemailer, undefined);
|
|
14
14
|
assert.ok(packageMetadata.metadata.apiSummary.extensionCapabilities.includes("auth.local.recovery-sender"));
|
|
15
|
+
assert.ok(packageMetadata.metadata.apiSummary.extensionCapabilities.includes("auth.local.confirmation-sender"));
|
|
15
16
|
});
|
|
@@ -32,6 +32,11 @@ async function temporaryStoreDir(prefix) {
|
|
|
32
32
|
|
|
33
33
|
test.after(() => Promise.all(temporaryStoreDirs.map((storeDir) => fs.rm(storeDir, { recursive: true, force: true }))));
|
|
34
34
|
|
|
35
|
+
// The setup code a production server without accounts asks its first registration for.
|
|
36
|
+
async function firstAccountSetupCode(storeDir) {
|
|
37
|
+
return (await fs.readFile(path.join(storeDir, "first-account-setup-code"), "utf8")).trim();
|
|
38
|
+
}
|
|
39
|
+
|
|
35
40
|
function createReplyFixture() {
|
|
36
41
|
const cookies = {};
|
|
37
42
|
const cookieOptions = {};
|
|
@@ -90,6 +95,7 @@ async function createStartedApp({
|
|
|
90
95
|
profileProjector = null,
|
|
91
96
|
passwordStrategy = null,
|
|
92
97
|
recoverySender = null,
|
|
98
|
+
confirmationSender = null,
|
|
93
99
|
invitationContextResolver = null,
|
|
94
100
|
logger = null,
|
|
95
101
|
configureExtensions = null
|
|
@@ -130,6 +136,8 @@ async function createStartedApp({
|
|
|
130
136
|
AUTH_LOCAL_STORE_DIR: storeDir,
|
|
131
137
|
AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "response",
|
|
132
138
|
APP_PUBLIC_URL: "http://localhost:5173",
|
|
139
|
+
// Registration signs in at once here; the email confirmation tests turn confirmation on.
|
|
140
|
+
AUTH_LOCAL_EMAIL_CONFIRMATION: "false",
|
|
133
141
|
NODE_ENV: "test",
|
|
134
142
|
...env
|
|
135
143
|
},
|
|
@@ -139,6 +147,7 @@ async function createStartedApp({
|
|
|
139
147
|
...(profileProjector ? { "auth.profile.projector": profileProjector } : {}),
|
|
140
148
|
...(passwordStrategy ? { "auth.local.password-strategy": passwordStrategy } : {}),
|
|
141
149
|
...(recoverySender !== null ? { "auth.local.recovery-sender": recoverySender } : {}),
|
|
150
|
+
...(confirmationSender !== null ? { "auth.local.confirmation-sender": confirmationSender } : {}),
|
|
142
151
|
};
|
|
143
152
|
const runtime = createCapabilityRuntime({
|
|
144
153
|
inputs,
|
|
@@ -415,6 +424,7 @@ test("local auth provider rejects dev login-as enablement in production", async
|
|
|
415
424
|
...devAuthEnv(),
|
|
416
425
|
AUTH_LOCAL_FILE_PRODUCTION_ACK: "true",
|
|
417
426
|
AUTH_LOCAL_SESSION_SECRET: "production-session-secret",
|
|
427
|
+
AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "",
|
|
418
428
|
NODE_ENV: "production"
|
|
419
429
|
}
|
|
420
430
|
}),
|
|
@@ -424,6 +434,22 @@ test("local auth provider rejects dev login-as enablement in production", async
|
|
|
424
434
|
);
|
|
425
435
|
});
|
|
426
436
|
|
|
437
|
+
test("a production server with AUTH_LOCAL_RECOVERY_DEV_OUTPUT set refuses to start, saying what to remove", async () => {
|
|
438
|
+
await assert.rejects(
|
|
439
|
+
() => createStartedApp({
|
|
440
|
+
env: {
|
|
441
|
+
AUTH_LOCAL_FILE_PRODUCTION_ACK: "true",
|
|
442
|
+
AUTH_LOCAL_SESSION_SECRET: "production-session-secret",
|
|
443
|
+
AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "log",
|
|
444
|
+
NODE_ENV: "production"
|
|
445
|
+
}
|
|
446
|
+
}),
|
|
447
|
+
(error) => String(error.details?.cause?.message || error.message || "") ===
|
|
448
|
+
"AUTH_LOCAL_RECOVERY_DEV_OUTPUT is for development only and NODE_ENV is production. " +
|
|
449
|
+
"Remove it from the production environment."
|
|
450
|
+
);
|
|
451
|
+
});
|
|
452
|
+
|
|
427
453
|
test("local auth provider applies auth service decorators for blocking and non-blocking hooks", async () => {
|
|
428
454
|
const calls = [];
|
|
429
455
|
const errors = [];
|
|
@@ -745,6 +771,20 @@ test("local auth service accepts a custom stored-password format", async () => {
|
|
|
745
771
|
async consumeForUser() {
|
|
746
772
|
return 0;
|
|
747
773
|
}
|
|
774
|
+
},
|
|
775
|
+
signInFailures: {
|
|
776
|
+
async find() {
|
|
777
|
+
return null;
|
|
778
|
+
},
|
|
779
|
+
async save(record) {
|
|
780
|
+
return record;
|
|
781
|
+
},
|
|
782
|
+
async clear() {
|
|
783
|
+
return 0;
|
|
784
|
+
},
|
|
785
|
+
async deleteBefore() {
|
|
786
|
+
return 0;
|
|
787
|
+
}
|
|
748
788
|
}
|
|
749
789
|
});
|
|
750
790
|
}
|
|
@@ -1218,12 +1258,34 @@ test("local file backend replays a pending multi-file transaction journal before
|
|
|
1218
1258
|
await assert.rejects(() => fs.stat(path.join(storeDir, "transaction.journal")), { code: "ENOENT" });
|
|
1219
1259
|
});
|
|
1220
1260
|
|
|
1261
|
+
test("a production server without accounts refuses a first registration without its setup code", async () => {
|
|
1262
|
+
const app = await createStartedApp({
|
|
1263
|
+
env: { NODE_ENV: "production", AUTH_LOCAL_SESSION_SECRET: "fixture-session-secret", AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "" }
|
|
1264
|
+
});
|
|
1265
|
+
assert.equal(app.authService.getCapabilities().features.firstAccountSetupCode, true);
|
|
1266
|
+
await assert.rejects(
|
|
1267
|
+
() => app.authService.register({ email: "first@example.com", password: "correct horse battery staple" }),
|
|
1268
|
+
{ status: 403, code: "auth.local.setup.codeRequired" }
|
|
1269
|
+
);
|
|
1270
|
+
const owner = await app.authService.register({
|
|
1271
|
+
email: "first@example.com",
|
|
1272
|
+
password: "correct horse battery staple",
|
|
1273
|
+
setupCode: await firstAccountSetupCode(app.storeDir)
|
|
1274
|
+
});
|
|
1275
|
+
assert.equal(owner.actor.email, "first@example.com");
|
|
1276
|
+
assert.equal(app.authService.getCapabilities().features.firstAccountSetupCode, false);
|
|
1277
|
+
});
|
|
1278
|
+
|
|
1221
1279
|
test("production sessions use host-only __Host- cookies and ignore the old names", async (t) => {
|
|
1222
1280
|
const app = await createStartedApp({
|
|
1223
|
-
env: { NODE_ENV: "production", AUTH_LOCAL_SESSION_SECRET: "fixture-session-secret" }
|
|
1281
|
+
env: { NODE_ENV: "production", AUTH_LOCAL_SESSION_SECRET: "fixture-session-secret", AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "" }
|
|
1224
1282
|
});
|
|
1225
1283
|
t.after(() => fs.rm(app.storeDir, { recursive: true, force: true }));
|
|
1226
|
-
const registered = await app.authService.register({
|
|
1284
|
+
const registered = await app.authService.register({
|
|
1285
|
+
email: "host@example.com",
|
|
1286
|
+
password: "correct horse battery staple",
|
|
1287
|
+
setupCode: await firstAccountSetupCode(app.storeDir)
|
|
1288
|
+
});
|
|
1227
1289
|
const reply = createReplyFixture();
|
|
1228
1290
|
app.authService.writeSessionCookies(reply, registered.session);
|
|
1229
1291
|
assert.deepEqual(Object.keys(reply.cookies).sort(), ["__Host-jskit_local_access_token", "__Host-jskit_local_refresh_token"]);
|
|
@@ -1244,12 +1306,16 @@ test("local recovery uses the application sender without returning or logging it
|
|
|
1244
1306
|
const messages = [];
|
|
1245
1307
|
const logs = [];
|
|
1246
1308
|
const app = await createStartedApp({
|
|
1247
|
-
env: { NODE_ENV: "production", AUTH_LOCAL_SESSION_SECRET: "fixture-session-secret" },
|
|
1309
|
+
env: { NODE_ENV: "production", AUTH_LOCAL_SESSION_SECRET: "fixture-session-secret", AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "" },
|
|
1248
1310
|
recoverySender: async (message) => { messages.push(message); },
|
|
1249
1311
|
logger: { info: (...args) => logs.push(args), warn() {}, error() {}, debug() {} }
|
|
1250
1312
|
});
|
|
1251
1313
|
t.after(() => fs.rm(app.storeDir, { recursive: true, force: true }));
|
|
1252
|
-
await app.authService.register({
|
|
1314
|
+
await app.authService.register({
|
|
1315
|
+
email: "sender@example.com",
|
|
1316
|
+
password: "correct horse battery staple",
|
|
1317
|
+
setupCode: await firstAccountSetupCode(app.storeDir)
|
|
1318
|
+
});
|
|
1253
1319
|
assert.equal(app.authService.getCapabilities().features.passwordRecovery.delivery, "email");
|
|
1254
1320
|
const result = await app.authService.requestPasswordReset({ email: "sender@example.com" });
|
|
1255
1321
|
assert.equal(result.recoveryUrl, undefined);
|
|
@@ -1278,3 +1344,73 @@ test("a failing recovery sender does not fall back to development output", async
|
|
|
1278
1344
|
await assert.rejects(app.authService.requestPasswordReset({ email: "failure@example.com" }), failure);
|
|
1279
1345
|
assert.equal(logs.some((args) => JSON.stringify(args).includes("recoveryUrl")), false);
|
|
1280
1346
|
});
|
|
1347
|
+
|
|
1348
|
+
test("in production, email confirmation needs an auth.local.confirmation-sender, or startup stops saying what to do", async () => {
|
|
1349
|
+
const production = {
|
|
1350
|
+
NODE_ENV: "production",
|
|
1351
|
+
AUTH_LOCAL_SESSION_SECRET: "fixture-session-secret",
|
|
1352
|
+
AUTH_LOCAL_FILE_PRODUCTION_ACK: "true",
|
|
1353
|
+
AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "",
|
|
1354
|
+
AUTH_LOCAL_EMAIL_CONFIRMATION: ""
|
|
1355
|
+
};
|
|
1356
|
+
await assert.rejects(
|
|
1357
|
+
() => createStartedApp({ env: production }),
|
|
1358
|
+
(error) => String(error.details?.cause?.message || error.message || "") ===
|
|
1359
|
+
"Local auth confirms each new account's email address in production, and no auth.local.confirmation-sender " +
|
|
1360
|
+
"is installed to email the confirmation links. Install one, or set AUTH_LOCAL_EMAIL_CONFIRMATION=false " +
|
|
1361
|
+
"to let accounts register without confirming their email."
|
|
1362
|
+
);
|
|
1363
|
+
const optedOut = await createStartedApp({ env: { ...production, AUTH_LOCAL_EMAIL_CONFIRMATION: "false" } });
|
|
1364
|
+
assert.equal(optedOut.authService.getCapabilities().features.emailConfirmation, false);
|
|
1365
|
+
});
|
|
1366
|
+
|
|
1367
|
+
test("the confirmation sender emails the link, which is never returned or logged, and the register hook runs on confirming", async (t) => {
|
|
1368
|
+
const messages = [];
|
|
1369
|
+
const logs = [];
|
|
1370
|
+
const hooked = [];
|
|
1371
|
+
const app = await createStartedApp({
|
|
1372
|
+
env: {
|
|
1373
|
+
NODE_ENV: "production",
|
|
1374
|
+
AUTH_LOCAL_SESSION_SECRET: "fixture-session-secret",
|
|
1375
|
+
AUTH_LOCAL_FILE_PRODUCTION_ACK: "true",
|
|
1376
|
+
AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "",
|
|
1377
|
+
AUTH_LOCAL_EMAIL_CONFIRMATION: "",
|
|
1378
|
+
APP_PUBLIC_URL: "https://app.example.test"
|
|
1379
|
+
},
|
|
1380
|
+
confirmationSender: async (message) => { messages.push(message); },
|
|
1381
|
+
logger: { info: (...args) => logs.push(args), warn() {}, error() {}, debug() {} },
|
|
1382
|
+
configureExtensions(extensions, runtimeLogger) {
|
|
1383
|
+
extensions.registerServiceDecorator(createLocalAuthRegisterHookDecorator({
|
|
1384
|
+
logger: runtimeLogger,
|
|
1385
|
+
hook: { hookId: "welcome", blocking: true, async handle({ actor }) { hooked.push(actor.email); } }
|
|
1386
|
+
}));
|
|
1387
|
+
}
|
|
1388
|
+
});
|
|
1389
|
+
t.after(() => fs.rm(app.storeDir, { recursive: true, force: true }));
|
|
1390
|
+
const features = app.authService.getCapabilities().features;
|
|
1391
|
+
assert.deepEqual([features.emailConfirmation, features.emailConfirmationCode], [true, true]);
|
|
1392
|
+
|
|
1393
|
+
const registered = await app.authService.register({
|
|
1394
|
+
email: "mail@example.com",
|
|
1395
|
+
password: "correct horse battery staple",
|
|
1396
|
+
setupCode: await firstAccountSetupCode(app.storeDir)
|
|
1397
|
+
});
|
|
1398
|
+
assert.equal(registered.requiresEmailConfirmation, true);
|
|
1399
|
+
assert.equal(registered.session, null);
|
|
1400
|
+
assert.equal(Object.hasOwn(registered, "confirmationUrl"), false);
|
|
1401
|
+
assert.deepEqual(hooked, []);
|
|
1402
|
+
assert.equal(messages.length, 1);
|
|
1403
|
+
assert.equal(messages[0].email, "mail@example.com");
|
|
1404
|
+
const link = new URL(messages[0].confirmationUrl);
|
|
1405
|
+
assert.equal(`${link.origin}${link.pathname}`, "https://app.example.test/auth/login");
|
|
1406
|
+
assert.equal(JSON.stringify(logs).includes(link.searchParams.get("confirmation_token")), false);
|
|
1407
|
+
|
|
1408
|
+
const confirmed = await app.actionExecutor.execute({
|
|
1409
|
+
actionId: "auth.register.confirm",
|
|
1410
|
+
input: { token: link.searchParams.get("confirmation_token") },
|
|
1411
|
+
context: { channel: "internal" }
|
|
1412
|
+
});
|
|
1413
|
+
assert.equal(confirmed.actor.email, "mail@example.com");
|
|
1414
|
+
assert.ok(confirmed.session.access_token);
|
|
1415
|
+
assert.deepEqual(hooked, ["mail@example.com"]);
|
|
1416
|
+
});
|