@proteinjs/user-server 1.27.0 → 1.28.1
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 +23 -0
- package/dist/generated/index.d.ts.map +1 -1
- package/dist/generated/index.js +3 -1
- package/dist/generated/index.js.map +1 -1
- package/dist/src/authentication/EmailVerificationToken.d.ts +23 -0
- package/dist/src/authentication/EmailVerificationToken.d.ts.map +1 -0
- package/dist/src/authentication/EmailVerificationToken.js +90 -0
- package/dist/src/authentication/EmailVerificationToken.js.map +1 -0
- package/dist/src/authentication/MailedToken.d.ts +91 -0
- package/dist/src/authentication/MailedToken.d.ts.map +1 -0
- package/dist/src/authentication/MailedToken.js +221 -0
- package/dist/src/authentication/MailedToken.js.map +1 -0
- package/dist/src/authentication/PasswordResetToken.d.ts +7 -61
- package/dist/src/authentication/PasswordResetToken.d.ts.map +1 -1
- package/dist/src/authentication/PasswordResetToken.js +25 -140
- package/dist/src/authentication/PasswordResetToken.js.map +1 -1
- package/dist/src/routes/verifyEmail.d.ts +21 -0
- package/dist/src/routes/verifyEmail.d.ts.map +1 -0
- package/dist/src/routes/verifyEmail.js +107 -0
- package/dist/src/routes/verifyEmail.js.map +1 -0
- package/dist/src/services/Signup.d.ts +27 -1
- package/dist/src/services/Signup.d.ts.map +1 -1
- package/dist/src/services/Signup.js +166 -30
- package/dist/src/services/Signup.js.map +1 -1
- package/dist/test/EmailVerification.test.d.ts +2 -0
- package/dist/test/EmailVerification.test.d.ts.map +1 -0
- package/dist/test/EmailVerification.test.js +451 -0
- package/dist/test/EmailVerification.test.js.map +1 -0
- package/dist/test/MachineAccounts.integration.test.js +98 -15
- package/dist/test/MachineAccounts.integration.test.js.map +1 -1
- package/dist/test/NoAddressesInLogs.integration.test.js +2 -1
- package/dist/test/NoAddressesInLogs.integration.test.js.map +1 -1
- package/dist/test/Signup.test.js +8 -0
- package/dist/test/Signup.test.js.map +1 -1
- package/dist/test/UpdateUserInfoAvatar.test.js +21 -15
- package/dist/test/UpdateUserInfoAvatar.test.js.map +1 -1
- package/generated/index.ts +3 -1
- package/package.json +15 -15
- package/src/authentication/EmailVerificationToken.ts +32 -0
- package/src/authentication/MailedToken.ts +171 -0
- package/src/authentication/PasswordResetToken.ts +13 -131
- package/src/routes/verifyEmail.ts +64 -0
- package/src/services/Signup.ts +111 -10
- package/test/EmailVerification.test.ts +297 -0
- package/test/MachineAccounts.integration.test.ts +52 -11
- package/test/NoAddressesInLogs.integration.test.ts +2 -1
- package/test/Signup.test.ts +11 -1
- package/test/UpdateUserInfoAvatar.test.ts +7 -2
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
import { createHash } from 'crypto';
|
|
2
|
+
import moment from 'moment';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Email verification after sign-up — the library half, outcomes only, against the Spanner
|
|
6
|
+
* emulator (rows written, the context the config was handed, the mails sent, the states
|
|
7
|
+
* answered):
|
|
8
|
+
* - a plain sign-up's account works at once; its row stores the verification pair (the token's
|
|
9
|
+
* digest, an expiry a week out) and the welcome mail's config is handed the link that carries
|
|
10
|
+
* the token — the digest never rides the mail;
|
|
11
|
+
* - an invited sign-up stores no pair and the config is handed no context: the invite mail proved
|
|
12
|
+
* the address (the regression guard on the invite road);
|
|
13
|
+
* - `GET /user/verify-email?token=` spends the link once: 'confirmed' with `emailVerified` set
|
|
14
|
+
* and the pair cleared; the same token again is 'invalid' (cleared is unknown); a lapsed link
|
|
15
|
+
* is 'expired' with the flag unchanged; an unknown, malformed or missing token is 'invalid';
|
|
16
|
+
* no answer names an address;
|
|
17
|
+
* - the signed-in account's re-send mints a fresh pair (the earlier link stops working) and sends
|
|
18
|
+
* one mail; inside the gap it sends nothing and the pair stands; a verified account gets
|
|
19
|
+
* `{ sent: false }` and no mail.
|
|
20
|
+
* The mail transport and the config are doubled at the module boundary (SignupRoute.test.ts
|
|
21
|
+
* pattern) — the config double records every context it is handed; the db stays real.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
const sendEmail = jest.fn();
|
|
25
|
+
/** Every context `getNewUserEmailContent` was handed, in call order — `undefined` when none. */
|
|
26
|
+
const newUserContexts: unknown[] = [];
|
|
27
|
+
|
|
28
|
+
jest.mock('@proteinjs/email-server', () => ({
|
|
29
|
+
EmailSender: jest.fn().mockImplementation(() => ({ sendEmail })),
|
|
30
|
+
getDefaultInviteEmailConfigFactory: () => ({
|
|
31
|
+
getConfig: () => ({ getEmailContent: () => ({ text: 'invite', html: '<p>invite</p>' }) }),
|
|
32
|
+
}),
|
|
33
|
+
getDefaultSignupConfirmationEmailConfigFactory: () => ({
|
|
34
|
+
getConfig: () => ({
|
|
35
|
+
newUserSubject: 'Welcome aboard',
|
|
36
|
+
getNewUserEmailContent: (context?: { verifyEmailLink?: string }) => {
|
|
37
|
+
newUserContexts.push(context);
|
|
38
|
+
const confirm = context?.verifyEmailLink ? ` Confirm: https://app.test/${context.verifyEmailLink}` : '';
|
|
39
|
+
return { text: `welcome${confirm}`, html: '<p>welcome</p>' };
|
|
40
|
+
},
|
|
41
|
+
}),
|
|
42
|
+
}),
|
|
43
|
+
}));
|
|
44
|
+
|
|
45
|
+
import { getDbAsSystem, Reference } from '@proteinjs/db';
|
|
46
|
+
import { SourceRepository } from '@proteinjs/reflection';
|
|
47
|
+
import { tables, uiRoutes, User } from '@proteinjs/user';
|
|
48
|
+
import { EmailVerificationToken } from '../src/authentication/EmailVerificationToken';
|
|
49
|
+
import { verifyEmail } from '../src/routes/verifyEmail';
|
|
50
|
+
import { EMAIL_VERIFICATION_RESEND_GAP_MINUTES, Signup } from '../src/services/Signup';
|
|
51
|
+
import { UserServerTestEnvironment } from './UserServerTestEnvironment';
|
|
52
|
+
|
|
53
|
+
const testEnv = new UserServerTestEnvironment();
|
|
54
|
+
|
|
55
|
+
type ObjectCache = { objectCache: Record<string, unknown[]> };
|
|
56
|
+
type RouteOutcome = { status?: number; body?: { state?: string } };
|
|
57
|
+
|
|
58
|
+
const TOKEN_SHAPE = /^[0-9a-f]{64}$/;
|
|
59
|
+
const EXPECTED_LIFETIME_DAYS = 7;
|
|
60
|
+
/** Tolerance for the clock advancing between the mint and the assertion. */
|
|
61
|
+
const CLOCK_SKEW_TOLERANCE_SECONDS = 60;
|
|
62
|
+
|
|
63
|
+
const sha256Hex = (value: string) => createHash('sha256').update(value).digest('hex');
|
|
64
|
+
|
|
65
|
+
/** The same `moment().add(days, 'days')` arithmetic the mint uses, so a DST boundary inside the week cancels out. */
|
|
66
|
+
const secondsFromExpectedLifetime = (expiration: unknown, days: number) =>
|
|
67
|
+
Math.abs(moment(expiration as moment.MomentInput).diff(moment().add(days, 'days'), 'seconds'));
|
|
68
|
+
|
|
69
|
+
const userRow = async (email: string): Promise<User> => await getDbAsSystem().get(tables.User, { email });
|
|
70
|
+
|
|
71
|
+
/** The token a verify-email link carries. */
|
|
72
|
+
const tokenIn = (link: string | undefined): string => {
|
|
73
|
+
const token = /[?&]token=([0-9a-f]{64})$/.exec(link ?? '')?.[1];
|
|
74
|
+
if (!token) {
|
|
75
|
+
throw new Error('The link carries no verification token');
|
|
76
|
+
}
|
|
77
|
+
return token;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
/** The link the newest welcome mail's config was handed. */
|
|
81
|
+
const latestLink = (): string | undefined =>
|
|
82
|
+
(newUserContexts[newUserContexts.length - 1] as { verifyEmailLink?: string } | undefined)?.verifyEmailLink;
|
|
83
|
+
|
|
84
|
+
/** The token in the newest mail's text — what the account's inbox actually holds. */
|
|
85
|
+
const mailedToken = (): string =>
|
|
86
|
+
tokenIn(/https:\/\/app\.test\/(\S+)/.exec(sendEmail.mock.lastCall?.[0]?.text ?? '')?.[1]);
|
|
87
|
+
|
|
88
|
+
/** A plain (no-invite) sign-up; answers the row and the token its welcome mail carried. */
|
|
89
|
+
const signUp = async (email: string): Promise<{ user: User; token: string }> => {
|
|
90
|
+
const result = await new Signup().createUser({ name: 'Plain Signup', email, password: 'a password' });
|
|
91
|
+
expect(result.outcome).toBe('created');
|
|
92
|
+
return { user: await userRow(email), token: mailedToken() };
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
const invokeVerify = async (query: Record<string, unknown>): Promise<RouteOutcome> => {
|
|
96
|
+
const outcome: RouteOutcome = {};
|
|
97
|
+
const response = {
|
|
98
|
+
status(code: number) {
|
|
99
|
+
outcome.status = code;
|
|
100
|
+
return this;
|
|
101
|
+
},
|
|
102
|
+
send(body?: unknown) {
|
|
103
|
+
outcome.body = body as RouteOutcome['body'];
|
|
104
|
+
},
|
|
105
|
+
};
|
|
106
|
+
await verifyEmail.onRequest({ query } as never, response as never);
|
|
107
|
+
return outcome;
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
/** Moves an account's last mint back past the re-send gap, so only the flag can refuse. */
|
|
111
|
+
const ageLastMint = async (user: User) => {
|
|
112
|
+
await getDbAsSystem().update(tables.User, {
|
|
113
|
+
id: user.id,
|
|
114
|
+
emailVerificationTokenExpiration: moment()
|
|
115
|
+
.add(EXPECTED_LIFETIME_DAYS, 'days')
|
|
116
|
+
.subtract(EMAIL_VERIFICATION_RESEND_GAP_MINUTES + 1, 'minutes'),
|
|
117
|
+
});
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
describe('email verification after sign-up', () => {
|
|
121
|
+
beforeAll(async () => {
|
|
122
|
+
await testEnv.beforeAll();
|
|
123
|
+
// Invite optional (the library's default): the no-invite road is open.
|
|
124
|
+
(SourceRepository.get() as unknown as ObjectCache).objectCache[
|
|
125
|
+
'@proteinjs/user-server/DefaultInviteConfigFactory'
|
|
126
|
+
] = [];
|
|
127
|
+
}, 120000);
|
|
128
|
+
|
|
129
|
+
afterAll(async () => {
|
|
130
|
+
await testEnv.afterAll();
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
beforeEach(() => {
|
|
134
|
+
sendEmail.mockClear();
|
|
135
|
+
newUserContexts.length = 0;
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
it('a plain sign-up stores the pair — the digest, a week out — and hands the config the link carrying the token', async () => {
|
|
139
|
+
const email = 'plain@test.local';
|
|
140
|
+
|
|
141
|
+
const result = await new Signup().createUser({ name: 'Plain Signup', email, password: 'a password' });
|
|
142
|
+
|
|
143
|
+
expect(result.outcome).toBe('created');
|
|
144
|
+
const row = await userRow(email);
|
|
145
|
+
expect(row.emailVerified).toBe(false);
|
|
146
|
+
expect(row.emailVerificationToken).toMatch(TOKEN_SHAPE);
|
|
147
|
+
expect(EmailVerificationToken.LIFETIME_DAYS).toBe(EXPECTED_LIFETIME_DAYS);
|
|
148
|
+
expect(secondsFromExpectedLifetime(row.emailVerificationTokenExpiration, EXPECTED_LIFETIME_DAYS)).toBeLessThan(
|
|
149
|
+
CLOCK_SKEW_TOLERANCE_SECONDS
|
|
150
|
+
);
|
|
151
|
+
|
|
152
|
+
// The context: the verify page's path carrying the token whose DIGEST the row holds.
|
|
153
|
+
expect(newUserContexts).toHaveLength(1);
|
|
154
|
+
const link = latestLink();
|
|
155
|
+
expect(link).toMatch(new RegExp(`^${uiRoutes.account.verifyEmail}\\?token=[0-9a-f]{64}$`));
|
|
156
|
+
expect(sha256Hex(tokenIn(link))).toBe(row.emailVerificationToken);
|
|
157
|
+
expect(link).not.toContain(row.emailVerificationToken);
|
|
158
|
+
|
|
159
|
+
// One mail: the welcome, under the config's new-user subject, carrying the link.
|
|
160
|
+
expect(sendEmail).toHaveBeenCalledTimes(1);
|
|
161
|
+
expect(sendEmail.mock.calls[0][0]).toMatchObject({ to: email, subject: 'Welcome aboard' });
|
|
162
|
+
expect(sendEmail.mock.calls[0][0].text).toContain(link);
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
it('an invited sign-up stores no pair and the config is handed no context (the invite proved the address)', async () => {
|
|
166
|
+
const inviter = await testEnv.createUser({ name: 'Inviter', email: 'inviter@test.local' });
|
|
167
|
+
const email = 'invited@test.local';
|
|
168
|
+
await getDbAsSystem().insert(tables.Invite, {
|
|
169
|
+
email,
|
|
170
|
+
token: 'invite-token-verify-1',
|
|
171
|
+
tokenExpiresAt: moment().add(1, 'day'),
|
|
172
|
+
invitedBy: new Reference(tables.User.name, inviter.id),
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
const result = await new Signup().createUser(
|
|
176
|
+
{ name: 'Invited Signup', password: 'a password' },
|
|
177
|
+
'invite-token-verify-1'
|
|
178
|
+
);
|
|
179
|
+
|
|
180
|
+
expect(result.outcome).toBe('created');
|
|
181
|
+
const row = await userRow(email);
|
|
182
|
+
expect(row.emailVerified).toBe(true);
|
|
183
|
+
expect(row.emailVerificationToken ?? null).toBeNull();
|
|
184
|
+
expect(row.emailVerificationTokenExpiration ?? null).toBeNull();
|
|
185
|
+
expect(newUserContexts).toEqual([undefined]);
|
|
186
|
+
expect(sendEmail).toHaveBeenCalledTimes(1);
|
|
187
|
+
expect(sendEmail.mock.calls[0][0].text).not.toContain('token=');
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
it('the mailed token confirms the address once: emailVerified set, the pair cleared, confirmed answered; again is invalid', async () => {
|
|
191
|
+
const { user, token } = await signUp('confirm@test.local');
|
|
192
|
+
|
|
193
|
+
const first = await invokeVerify({ token });
|
|
194
|
+
|
|
195
|
+
expect(first).toEqual({ status: 200, body: { state: 'confirmed' } });
|
|
196
|
+
const confirmed = await userRow(user.email);
|
|
197
|
+
expect(confirmed.emailVerified).toBe(true);
|
|
198
|
+
expect(confirmed.emailVerificationToken).toBeNull();
|
|
199
|
+
expect(confirmed.emailVerificationTokenExpiration).toBeNull();
|
|
200
|
+
|
|
201
|
+
// Spent: the cleared row no longer answers to the token, so the same link reads as unknown.
|
|
202
|
+
const again = await invokeVerify({ token });
|
|
203
|
+
expect(again).toEqual({ status: 200, body: { state: 'invalid' } });
|
|
204
|
+
expect((await userRow(user.email)).emailVerified).toBe(true);
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
it('a lapsed link answers expired and leaves the flag and the pair as they were', async () => {
|
|
208
|
+
const { user, token } = await signUp('lapsed@test.local');
|
|
209
|
+
const lapsed = moment().subtract(1, 'minute');
|
|
210
|
+
await getDbAsSystem().update(tables.User, { id: user.id, emailVerificationTokenExpiration: lapsed });
|
|
211
|
+
|
|
212
|
+
const outcome = await invokeVerify({ token });
|
|
213
|
+
|
|
214
|
+
expect(outcome).toEqual({ status: 200, body: { state: 'expired' } });
|
|
215
|
+
const row = await userRow(user.email);
|
|
216
|
+
expect(row.emailVerified).toBe(false);
|
|
217
|
+
expect(row.emailVerificationToken).toBe(sha256Hex(token));
|
|
218
|
+
expect(moment(row.emailVerificationTokenExpiration as moment.MomentInput).isSame(lapsed)).toBe(true);
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
it('an unknown, malformed or missing token is invalid, and no answer names an address', async () => {
|
|
222
|
+
const { user, token } = await signUp('unknown@test.local');
|
|
223
|
+
|
|
224
|
+
const unissued = await invokeVerify({ token: sha256Hex(`never issued ${Math.random()}`) });
|
|
225
|
+
const digestAsToken = await invokeVerify({ token: sha256Hex(token) });
|
|
226
|
+
const malformed = await invokeVerify({ token: 'not-a-token' });
|
|
227
|
+
const missing = await invokeVerify({});
|
|
228
|
+
const confirmed = await invokeVerify({ token });
|
|
229
|
+
|
|
230
|
+
expect(unissued).toEqual({ status: 200, body: { state: 'invalid' } });
|
|
231
|
+
expect(digestAsToken).toEqual({ status: 200, body: { state: 'invalid' } });
|
|
232
|
+
expect(malformed).toEqual({ status: 200, body: { state: 'invalid' } });
|
|
233
|
+
expect(missing).toEqual({ status: 400, body: { state: 'invalid' } });
|
|
234
|
+
expect(confirmed).toEqual({ status: 200, body: { state: 'confirmed' } });
|
|
235
|
+
for (const outcome of [unissued, digestAsToken, malformed, missing, confirmed]) {
|
|
236
|
+
expect(JSON.stringify(outcome.body)).not.toContain(user.email);
|
|
237
|
+
}
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
it('the signed-in account re-sends: a fresh pair (the earlier link stops working) and one mail; inside the gap nothing; verified nothing', async () => {
|
|
241
|
+
const { user, token: first } = await signUp('resend@test.local');
|
|
242
|
+
testEnv.actAs(user);
|
|
243
|
+
|
|
244
|
+
// Inside the gap: no mail, the pair stands.
|
|
245
|
+
const tooSoon = await new Signup().resendEmailVerification();
|
|
246
|
+
expect(tooSoon).toEqual({ sent: false });
|
|
247
|
+
expect(sendEmail).toHaveBeenCalledTimes(1);
|
|
248
|
+
expect((await userRow(user.email)).emailVerificationToken).toBe(sha256Hex(first));
|
|
249
|
+
|
|
250
|
+
await ageLastMint(user);
|
|
251
|
+
const resent = await new Signup().resendEmailVerification();
|
|
252
|
+
|
|
253
|
+
expect(resent).toEqual({ sent: true });
|
|
254
|
+
expect(sendEmail).toHaveBeenCalledTimes(2);
|
|
255
|
+
expect(sendEmail.mock.calls[1][0]).toMatchObject({ to: user.email, subject: 'Welcome aboard' });
|
|
256
|
+
const second = mailedToken();
|
|
257
|
+
expect(second).not.toBe(first);
|
|
258
|
+
const row = await userRow(user.email);
|
|
259
|
+
expect(row.emailVerificationToken).toBe(sha256Hex(second));
|
|
260
|
+
expect(secondsFromExpectedLifetime(row.emailVerificationTokenExpiration, EXPECTED_LIFETIME_DAYS)).toBeLessThan(
|
|
261
|
+
CLOCK_SKEW_TOLERANCE_SECONDS
|
|
262
|
+
);
|
|
263
|
+
expect(newUserContexts).toEqual([
|
|
264
|
+
{ verifyEmailLink: `${uiRoutes.account.verifyEmail}?token=${first}` },
|
|
265
|
+
{ verifyEmailLink: `${uiRoutes.account.verifyEmail}?token=${second}` },
|
|
266
|
+
]);
|
|
267
|
+
|
|
268
|
+
// The earlier link is dead; the fresh one confirms.
|
|
269
|
+
expect(await invokeVerify({ token: first })).toEqual({ status: 200, body: { state: 'invalid' } });
|
|
270
|
+
expect(await invokeVerify({ token: second })).toEqual({ status: 200, body: { state: 'confirmed' } });
|
|
271
|
+
|
|
272
|
+
// Verified now: the re-send refuses without a word and sends nothing.
|
|
273
|
+
const verified = await new Signup().resendEmailVerification();
|
|
274
|
+
expect(verified).toEqual({ sent: false });
|
|
275
|
+
expect(sendEmail).toHaveBeenCalledTimes(2);
|
|
276
|
+
expect((await userRow(user.email)).emailVerificationToken).toBeNull();
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
it('a re-send whose mail fails withdraws the token, so the next tap is not held by the gap', async () => {
|
|
280
|
+
const { user, token: first } = await signUp('resend-fails@test.local');
|
|
281
|
+
testEnv.actAs(user);
|
|
282
|
+
await ageLastMint(user);
|
|
283
|
+
sendEmail.mockRejectedValueOnce(new Error('transport refused'));
|
|
284
|
+
|
|
285
|
+
const failed = await new Signup().resendEmailVerification();
|
|
286
|
+
|
|
287
|
+
expect(failed).toEqual({ sent: false });
|
|
288
|
+
const withdrawn = await userRow(user.email);
|
|
289
|
+
expect(withdrawn.emailVerificationToken).toBeNull();
|
|
290
|
+
expect(withdrawn.emailVerified).toBe(false);
|
|
291
|
+
expect(await invokeVerify({ token: first })).toEqual({ status: 200, body: { state: 'invalid' } });
|
|
292
|
+
|
|
293
|
+
const retried = await new Signup().resendEmailVerification();
|
|
294
|
+
expect(retried).toEqual({ sent: true });
|
|
295
|
+
expect(await invokeVerify({ token: mailedToken() })).toEqual({ status: 200, body: { state: 'confirmed' } });
|
|
296
|
+
});
|
|
297
|
+
});
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import sha256 from 'crypto-js/sha256';
|
|
2
|
-
import {
|
|
2
|
+
import { getDbAsSystem } from '@proteinjs/db';
|
|
3
|
+
import { SourceRecordSyncRunner } from '@proteinjs/db/source';
|
|
3
4
|
import { SourceRepository } from '@proteinjs/reflection';
|
|
4
5
|
// Deep import (test-only): ServiceAuth is the real RPC door but is not index-exported by
|
|
5
6
|
// @proteinjs/service — the door test below runs the actual gate rather than pinning metadata.
|
|
@@ -21,6 +22,12 @@ class OpsRole implements RoleCatalogEntry {
|
|
|
21
22
|
description = 'Operational machinery';
|
|
22
23
|
}
|
|
23
24
|
|
|
25
|
+
/** A second catalog role, so a declaration can come to equal a runtime-edited roles column. */
|
|
26
|
+
class AuditRole implements RoleCatalogEntry {
|
|
27
|
+
role = 'audit';
|
|
28
|
+
description = 'Audit reads';
|
|
29
|
+
}
|
|
30
|
+
|
|
24
31
|
class TestOpsMachineAccount extends MachineAccount {
|
|
25
32
|
id = 'machine-test-ops';
|
|
26
33
|
email = 'machine-ops@test.local';
|
|
@@ -68,10 +75,10 @@ describe('Machine accounts as source records', () => {
|
|
|
68
75
|
}));
|
|
69
76
|
};
|
|
70
77
|
|
|
71
|
-
/** One boot of Db.init's source-record leg with these MachineAccount declarations. */
|
|
78
|
+
/** One boot of Db.init's source-record leg with these MachineAccount declarations — what it did, per table. */
|
|
72
79
|
const boot = async (declarations: MachineAccount[]) => {
|
|
73
80
|
seedLoaders(declarations);
|
|
74
|
-
await new SourceRecordSyncRunner().load();
|
|
81
|
+
return await new SourceRecordSyncRunner().load();
|
|
75
82
|
};
|
|
76
83
|
|
|
77
84
|
const machineRow = async () => await getDbAsSystem().get(tables.User, { email: 'machine-ops@test.local' });
|
|
@@ -92,7 +99,7 @@ describe('Machine accounts as source records', () => {
|
|
|
92
99
|
(SourceRepository.get() as unknown as SourceRepositoryInternals).objectCache[
|
|
93
100
|
'@proteinjs/user-auth/AuthenticatedUserRepo'
|
|
94
101
|
] = [new UserRepo()];
|
|
95
|
-
objectCache()['@proteinjs/user/RoleCatalogEntry'] = [new OpsRole()];
|
|
102
|
+
objectCache()['@proteinjs/user/RoleCatalogEntry'] = [new OpsRole(), new AuditRole()];
|
|
96
103
|
// The two session watchers a real server registers, rebuilt from the seeded cache — and no
|
|
97
104
|
// socket server exists in this process: the shape of a boot's sync (and of a migration Job,
|
|
98
105
|
// which never starts one), where deactivations delete sessions before the server is up.
|
|
@@ -288,12 +295,11 @@ describe('Machine accounts as source records', () => {
|
|
|
288
295
|
// re-declare-after-removal under a changed natural key) must adopt the row by its stable
|
|
289
296
|
// declared id instead of INSERTing into a PK collision.
|
|
290
297
|
await boot([new TestOpsMachineAccount()]);
|
|
291
|
-
//
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
});
|
|
298
|
+
// The runtime-owned credential on the row: `password` is a column no declaration covers, so
|
|
299
|
+
// the write leaves the row the sync's. (A DECLARED column written at runtime makes the row
|
|
300
|
+
// the product's — @proteinjs/db's authorship precedence, pinned by the next test — and a
|
|
301
|
+
// declaration never adopts a row that is the product's.)
|
|
302
|
+
await getDbAsSystem().update(tables.User, { id: 'machine-test-ops', password: sha256('cred').toString() });
|
|
297
303
|
await insertSession('machine-session', 'machine-ops@test.local');
|
|
298
304
|
|
|
299
305
|
class RenamedOps extends TestOpsMachineAccount {
|
|
@@ -302,7 +308,7 @@ describe('Machine accounts as source records', () => {
|
|
|
302
308
|
await boot([new RenamedOps()]);
|
|
303
309
|
|
|
304
310
|
// One row, adopted in place: id kept (references + credential survive), email re-derived,
|
|
305
|
-
// reactivated, grants exactly the declaration's
|
|
311
|
+
// reactivated, grants exactly the declaration's.
|
|
306
312
|
expect(await getDbAsSystem().query(tables.User, {})).toHaveLength(1);
|
|
307
313
|
expect(await getDbAsSystem().get(tables.User, { email: 'machine-ops@test.local' })).toBeUndefined();
|
|
308
314
|
const adopted = await getDbAsSystem().get(tables.User, { email: 'machine-ops-renamed@test.local' });
|
|
@@ -320,6 +326,41 @@ describe('Machine accounts as source records', () => {
|
|
|
320
326
|
expect(await authenticate('machine-ops-renamed@test.local', 'cred')).toBe(true);
|
|
321
327
|
});
|
|
322
328
|
|
|
329
|
+
it(`a declared column written at runtime makes the row the product's: the next boot leaves it as it is — never brought back, never a failed boot — and the declaration coming to equal it re-adopts it`, async () => {
|
|
330
|
+
// @proteinjs/db's authorship precedence: the sync stamps the declared columns it writes, and
|
|
331
|
+
// a row whose declared columns moved since is the product's until the declaration equals it
|
|
332
|
+
// again. The Roles service refuses machine targets, so the one road to a machine row's roles
|
|
333
|
+
// at runtime is a hand edit — the system write here.
|
|
334
|
+
await boot([new TestOpsMachineAccount()]);
|
|
335
|
+
await getDbAsSystem().update(tables.User, { id: 'machine-test-ops', roles: ['ops', 'audit'] });
|
|
336
|
+
const edited = await machineRow();
|
|
337
|
+
|
|
338
|
+
// The declaration stands still: the row is kept exactly as it is, nothing written.
|
|
339
|
+
expect((await boot([new TestOpsMachineAccount()]))[tables.User.name]).toMatchObject({
|
|
340
|
+
kept: 1,
|
|
341
|
+
updates: 0,
|
|
342
|
+
inserts: 0,
|
|
343
|
+
});
|
|
344
|
+
const kept = await machineRow();
|
|
345
|
+
expect(kept).toMatchObject({
|
|
346
|
+
id: 'machine-test-ops',
|
|
347
|
+
roles: ['ops', 'audit'],
|
|
348
|
+
status: 'active',
|
|
349
|
+
isLoadedFromSource: true,
|
|
350
|
+
});
|
|
351
|
+
expect(kept.updated.valueOf()).toBe(edited.updated.valueOf());
|
|
352
|
+
|
|
353
|
+
// The declaration comes to equal the row: re-adopted (its stamp written, nothing else)...
|
|
354
|
+
class OpsAndAudit extends TestOpsMachineAccount {
|
|
355
|
+
roles = ['ops', 'audit'];
|
|
356
|
+
}
|
|
357
|
+
expect((await boot([new OpsAndAudit()]))[tables.User.name]).toMatchObject({ adopted: 1, kept: 0 });
|
|
358
|
+
expect((await machineRow()).roles).toEqual(['ops', 'audit']);
|
|
359
|
+
// ...and from there the declaration moving again lands as before.
|
|
360
|
+
expect((await boot([new TestOpsMachineAccount()]))[tables.User.name]).toMatchObject({ updates: 1, kept: 0 });
|
|
361
|
+
expect((await machineRow()).roles).toEqual(['ops']);
|
|
362
|
+
});
|
|
363
|
+
|
|
323
364
|
it(`the staff toggle rides the same watcher: SetUserStatus deactivation kills the target's sessions`, async () => {
|
|
324
365
|
const admin = await testEnv.createUser({ name: 'Admin', email: 'admin@test.local', roles: ['admin'] });
|
|
325
366
|
const target = await testEnv.createUser({ name: 'Target', email: 'target@test.local' });
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import moment from 'moment';
|
|
2
2
|
import sha256 from 'crypto-js/sha256';
|
|
3
|
-
import {
|
|
3
|
+
import { getDbAsSystem } from '@proteinjs/db';
|
|
4
|
+
import { SourceRecordSyncRunner } from '@proteinjs/db/source';
|
|
4
5
|
import { EmailSender, MailSink } from '@proteinjs/email-server';
|
|
5
6
|
import { SourceRepository } from '@proteinjs/reflection';
|
|
6
7
|
import { MachineAccount, RoleCatalogEntry, UserRepo, tables } from '@proteinjs/user';
|
package/test/Signup.test.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { UserAuth } from '@proteinjs/user';
|
|
1
|
+
import { guestUser, UserAuth } from '@proteinjs/user';
|
|
2
2
|
import { Signup } from '../src/services/Signup';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -68,4 +68,14 @@ describe('Signup service auth', () => {
|
|
|
68
68
|
setUser([]);
|
|
69
69
|
expect(canAccess('initializeSignup')).toBe(true);
|
|
70
70
|
});
|
|
71
|
+
|
|
72
|
+
it(`admits resendEmailVerification for any signed-in account and refuses it to the guest (it mails the session's own account)`, () => {
|
|
73
|
+
setUser([]);
|
|
74
|
+
expect(canAccess('resendEmailVerification')).toBe(true);
|
|
75
|
+
|
|
76
|
+
(UserAuth as unknown as UserAuthInternals).userRepo = {
|
|
77
|
+
getUser: () => ({ email: guestUser.email, roles: [] }),
|
|
78
|
+
};
|
|
79
|
+
expect(canAccess('resendEmailVerification')).toBe(false);
|
|
80
|
+
});
|
|
71
81
|
});
|
|
@@ -80,9 +80,14 @@ describe('UpdateUserInfo avatar mutations', () => {
|
|
|
80
80
|
expect(second.avatarFileId).not.toBe(first.avatarFileId);
|
|
81
81
|
|
|
82
82
|
// The prior file is gone — row and bytes (the byte store checked directly through the
|
|
83
|
-
// driver: the gated service read
|
|
83
|
+
// driver: the gated service read refuses ids with no readable row by design, and the driver's
|
|
84
|
+
// one answer for bytes that are not there is its not-found error — @proteinjs/db-file's
|
|
85
|
+
// FileStorageError, read by shape).
|
|
84
86
|
expect(await getFileRow(first.avatarFileId!)).toBeFalsy();
|
|
85
|
-
expect(
|
|
87
|
+
await expect(FileStorage.getDriver().getFileData(first.avatarFileId!)).rejects.toMatchObject({
|
|
88
|
+
name: 'FileStorageError',
|
|
89
|
+
code: 'not-found',
|
|
90
|
+
});
|
|
86
91
|
// The new one is intact.
|
|
87
92
|
expect(await getFileRow(second.avatarFileId!)).toBeTruthy();
|
|
88
93
|
});
|