@jskit-ai/users-core 0.2.84 → 0.2.86

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 CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - `DELETE /api/account` (`settings.security.account.delete`): the signed-in person deletes their own account after proving it is them (a recent second factor when enrolled, then the provider's proof); `account.deleting` is published before the profile and settings go, and the provider then deletes the sign-in account.
5
6
  - The `users/user-administration-server` pattern gives `@jskit-ai/config-eslint`'s larger file limit: files under 1,200 lines (it said 750); functions stay under 600.
6
7
  - The account settings, profile, avatar, security, preferences and notifications routes name the action they run (`actionId`), so each action's checks come before the route validates what the request sends, and before the avatar upload route reads its file (#497).
7
8
  - The manifest marks `runtime.database`, which its migrations need and no server provider of the package requires, as install-time only (`jskit.capabilities.installRequires`), so an app's start-up no longer logs "Package manifest requires a capability its providers do not." for it.
package/locales/en.json CHANGED
@@ -37,6 +37,10 @@
37
37
  "productUpdatesInvalid": "productUpdates must be a boolean.",
38
38
  "accountActivityInvalid": "accountActivity must be a boolean.",
39
39
  "securityAlertsInvalid": "securityAlerts must be a boolean."
40
+ },
41
+ "account": {
42
+ "deleted": "Account deleted.",
43
+ "deletionUnsupported": "This app's sign-in can't delete accounts."
40
44
  }
41
45
  }
42
46
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/users-core",
3
- "version": "0.2.84",
3
+ "version": "0.2.86",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -19,10 +19,10 @@
19
19
  "./locales/en.json": "./locales/en.json"
20
20
  },
21
21
  "dependencies": {
22
- "@jskit-ai/resource-core": "0.1.232",
23
- "@jskit-ai/resource-crud-core": "0.1.235",
24
- "@jskit-ai/storage-runtime": "0.1.287",
25
- "@jskit-ai/uploads-runtime": "0.2.41",
22
+ "@jskit-ai/resource-core": "0.1.233",
23
+ "@jskit-ai/resource-crud-core": "0.1.236",
24
+ "@jskit-ai/storage-runtime": "0.1.288",
25
+ "@jskit-ai/uploads-runtime": "0.2.42",
26
26
  "json-rest-schema": "^1.0.20"
27
27
  },
28
28
  "description": "Users/account runtime plus HTTP routes for account features.",
@@ -204,10 +204,10 @@
204
204
  }
205
205
  },
206
206
  "peerDependencies": {
207
- "@jskit-ai/auth-core": "0.2.46",
208
- "@jskit-ai/database-runtime": "0.1.299",
209
- "@jskit-ai/http-runtime": "0.2.42",
210
- "@jskit-ai/kernel": "0.2.41",
211
- "@jskit-ai/resource-runtime": "0.2.66"
207
+ "@jskit-ai/auth-core": "0.2.48",
208
+ "@jskit-ai/database-runtime": "0.1.300",
209
+ "@jskit-ai/http-runtime": "0.2.44",
210
+ "@jskit-ai/kernel": "0.2.42",
211
+ "@jskit-ai/resource-runtime": "0.2.67"
212
212
  }
213
213
  }
@@ -10,9 +10,9 @@
10
10
  "./shared": "./src/shared/index.js"
11
11
  },
12
12
  "dependencies": {
13
- "@jskit-ai/crud-core": "0.2.73",
14
- "@jskit-ai/resource-crud-core": "0.1.235",
15
- "@jskit-ai/users-core": "0.2.84"
13
+ "@jskit-ai/crud-core": "0.2.75",
14
+ "@jskit-ai/resource-crud-core": "0.1.236",
15
+ "@jskit-ai/users-core": "0.2.86"
16
16
  },
17
17
  "jskit": {
18
18
  "kind": "runtime",
@@ -10,14 +10,14 @@
10
10
  "./shared": "./src/shared/index.js"
11
11
  },
12
12
  "dependencies": {
13
- "@jskit-ai/crud-core": "0.2.73",
14
- "@jskit-ai/resource-crud-core": "0.1.235",
15
- "@jskit-ai/users-core": "0.2.84",
16
- "@jskit-ai/workspaces-core": "0.2.84"
13
+ "@jskit-ai/crud-core": "0.2.75",
14
+ "@jskit-ai/resource-crud-core": "0.1.236",
15
+ "@jskit-ai/users-core": "0.2.86",
16
+ "@jskit-ai/workspaces-core": "0.2.86"
17
17
  },
18
18
  "peerDependencies": {
19
- "@jskit-ai/kernel": "0.2.41",
20
- "@jskit-ai/resource-runtime": "0.2.66"
19
+ "@jskit-ai/kernel": "0.2.42",
20
+ "@jskit-ai/resource-runtime": "0.2.67"
21
21
  },
22
22
  "jskit": {
23
23
  "kind": "runtime",
@@ -16,6 +16,7 @@ const UsersFeature = defineFeature({
16
16
  requires: {
17
17
  authService: "auth.service",
18
18
  bootstrap: "runtime.bootstrap",
19
+ events: "runtime.events",
19
20
  http: "runtime.http",
20
21
  profileProjector: "auth.profile.projector",
21
22
  profiles: "users.profiles",
@@ -30,6 +31,7 @@ const UsersFeature = defineFeature({
30
31
  * @param {object} capabilities
31
32
  * @param {import("@jskit-ai/auth-core/server/types").AuthService} capabilities.authService
32
33
  * @param {import("@jskit-ai/kernel/server/types").RuntimeBootstrap} capabilities.bootstrap
34
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeEvents} capabilities.events
33
35
  * @param {import("@jskit-ai/kernel/server/types").RuntimeHttp} capabilities.http
34
36
  * @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector} capabilities.profileProjector
35
37
  * @param {import("./types.js").UsersProfiles} capabilities.profiles
@@ -37,8 +39,8 @@ const UsersFeature = defineFeature({
37
39
  * @param {import("@jskit-ai/storage-runtime/server/types").RuntimeStorage} capabilities.storage
38
40
  * @param {import("@jskit-ai/uploads-runtime/server/types").RuntimeUploads} capabilities.uploads
39
41
  */
40
- setup({ authService, bootstrap, http, profileProjector, profiles, settings, storage, uploads }) {
41
- const users = createUsersRuntime({ authService, profileProjector, profiles, settings, storage });
42
+ setup({ authService, bootstrap, events, http, profileProjector, profiles, settings, storage, uploads }) {
43
+ const users = createUsersRuntime({ authService, profileProjector, profiles, settings, storage, events });
42
44
  registerAccountProfileRoutes(http.router, {
43
45
  accountProfileService: users.services.accountProfile,
44
46
  authService,
@@ -5,6 +5,21 @@ import { composeSchemaDefinitions } from "@jskit-ai/kernel/shared/validators";
5
5
  import { userSettingsContract } from "../../shared/resources/userSettingsResource.js";
6
6
  import { resolveActionUser } from "../common/support/resolveActionUser.js";
7
7
 
8
+ import { createSchema } from "json-rest-schema";
9
+ import { deepFreeze } from "@jskit-ai/kernel/shared/support/deepFreeze";
10
+
11
+ const ACTION_DELETE_ACCOUNT = "settings.security.account.delete";
12
+
13
+ // The proof a deletion brings: the password of an account that has one, and a fresh Apple authorization code for an
14
+ // account linked to Apple.
15
+ const deleteAccountInputValidator = deepFreeze({
16
+ schema: createSchema({
17
+ password: { type: "string", required: false, maxLength: 1024 },
18
+ appleAuthorizationCode: { type: "string", required: false, maxLength: 4096 }
19
+ }),
20
+ mode: "patch"
21
+ });
22
+
8
23
  const oauthLinkStartInputValidator = composeSchemaDefinitions([
9
24
  userSettingsContract.operations.oauthLinkStart.params,
10
25
  userSettingsContract.operations.oauthLinkStart.query
@@ -16,6 +31,24 @@ const oauthLinkStartInputValidator = composeSchemaDefinitions([
16
31
  /** @param {{ accountSecurityService: import("../types.js").AccountSecurityService }} dependencies */
17
32
  function createAccountSecurityActions({ accountSecurityService }) {
18
33
  return Object.freeze([
34
+ Object.freeze({
35
+ id: ACTION_DELETE_ACCOUNT,
36
+ version: 1,
37
+ kind: "command",
38
+ channels: ["api", "internal"],
39
+ surfaces: ["*"],
40
+ permission: {
41
+ require: "authenticated"
42
+ },
43
+ input: deleteAccountInputValidator,
44
+ output: null,
45
+ extensions: {
46
+ assistant: {
47
+ exclude: "Use the authenticated account security screen; deleting an account is the person's own irreversible decision, and passwords and Apple authorization codes must not enter assistant arguments."
48
+ }
49
+ },
50
+ execute: (input, context) => accountSecurityService.deleteAccount(resolveRequest(context), resolveActionUser(context, input), input)
51
+ }),
19
52
  Object.freeze({
20
53
  id: "settings.security.password.change",
21
54
  version: 1,
@@ -119,4 +152,4 @@ function createAccountSecurityActions({ accountSecurityService }) {
119
152
  ]);
120
153
  }
121
154
 
122
- export { createAccountSecurityActions };
155
+ export { ACTION_DELETE_ACCOUNT, createAccountSecurityActions, deleteAccountInputValidator };
@@ -3,6 +3,7 @@ import { createJsonApiResourceRouteContract } from "@jskit-ai/http-runtime/share
3
3
  import { withStandardErrorResponses } from "@jskit-ai/http-runtime/shared/validators/errorResponses";
4
4
  import { deepFreeze } from "@jskit-ai/kernel/shared/support/deepFreeze";
5
5
  import { userSettingsContract } from "../../shared/resources/userSettingsResource.js";
6
+ import { deleteAccountInputValidator } from "./accountSecurityActions.js";
6
7
  import { resolveAccountSettingsResourceId } from "../common/support/accountSettingsJsonApiTransport.js";
7
8
 
8
9
  const passwordChangeMetaOutputValidator = deepFreeze({
@@ -179,6 +180,34 @@ function registerAccountSecurityRoutes(router, { authService }) {
179
180
  }
180
181
  );
181
182
 
183
+ // Deleting the signed-in person's own account: the proof in the body, the session's cookies cleared after.
184
+ router.register(
185
+ "DELETE",
186
+ "/api/account",
187
+ {
188
+ auth: "required",
189
+ actionId: "settings.security.account.delete",
190
+ meta: {
191
+ tags: ["settings"],
192
+ summary: "Delete the signed-in person's own account and its data"
193
+ },
194
+ body: deleteAccountInputValidator,
195
+ responses: withStandardErrorResponses({ 200: passwordChangeMetaOutputValidator }, { includeValidation400: true }),
196
+ rateLimit: {
197
+ max: 5,
198
+ timeWindow: "1 minute"
199
+ }
200
+ },
201
+ async function deleteAccount(request, reply) {
202
+ const response = await request.executeAction({
203
+ actionId: "settings.security.account.delete",
204
+ input: request.input.body
205
+ });
206
+ authService.clearSessionCookies(reply);
207
+ reply.code(200).send(response);
208
+ }
209
+ );
210
+
182
211
  router.register(
183
212
  "POST",
184
213
  "/api/settings/security/logout-others",
@@ -1,4 +1,5 @@
1
1
  import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
2
+ import { requireSecondFactor } from "@jskit-ai/auth-core/server/secondFactor";
2
3
  import { createValidationError } from "@jskit-ai/kernel/server/runtime";
3
4
  import { returnJsonApiData, returnJsonApiMeta } from "@jskit-ai/http-runtime/shared";
4
5
  import {
@@ -17,8 +18,9 @@ import { accountSecurityStatusFormatter } from "../common/formatters/accountSecu
17
18
  * @param {import("../types.js").UserSettingsRepository} dependencies.userSettingsRepository
18
19
  * @param {import("../types.js").UserProfilesRepository} dependencies.userProfilesRepository
19
20
  * @param {import("@jskit-ai/auth-core/server/types").AuthService} dependencies.authService The installed provider's `auth.service`.
21
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeEvents} dependencies.events Where `account.deleting` is published.
20
22
  */
21
- function createService({ userSettingsRepository, userProfilesRepository, authService }) {
23
+ function createService({ userSettingsRepository, userProfilesRepository, authService, events }) {
22
24
  async function changePassword(request, payload) {
23
25
  if (payload.confirmPassword !== payload.newPassword) {
24
26
  throw createValidationError({
@@ -90,7 +92,47 @@ function createService({ userSettingsRepository, userProfilesRepository, authSer
90
92
  return null;
91
93
  }
92
94
 
95
+ /**
96
+ * Deletes the signed-in person's own account (App Store guideline 5.1.1(v)). An account with a second factor proves
97
+ * it within the last ten minutes; the provider then asks for the password, or a recent sign-in, and for an account
98
+ * linked to Apple a fresh Apple authorization code, which revokes it at Apple. After that proof, and before the
99
+ * account goes, `account.deleting` ({ userId, email }) lets every package and the application delete their records
100
+ * of this user, and the user's profile and settings go.
101
+ * @param {object} request
102
+ * @param {object} user The action's user.
103
+ * @param {{ password?: string, appleAuthorizationCode?: string }} payload
104
+ */
105
+ async function deleteAccount(request, user, payload) {
106
+ const profile = await resolveUserProfile(userProfilesRepository, user);
107
+ if (!profile) {
108
+ throw new AppError(404, "User profile was not found.", { code: "users.profile.notFound" });
109
+ }
110
+ // readable-check: allow method-probe - optional operation: deleteAccount is an optional auth.service operation
111
+ if (typeof authService.deleteAccount !== "function") {
112
+ throw new AppError(501, "This app's sign-in can't delete accounts.", { code: "users.account.deletionUnsupported" });
113
+ }
114
+ const securityStatus = await resolveSecurityStatus(authService, request);
115
+ if (securityStatus?.mfa?.enrolled === true) {
116
+ requireSecondFactor(request, { maxAgeSeconds: 600 });
117
+ }
118
+ await authService.deleteAccount(request, {
119
+ password: String(payload.password || ""),
120
+ appleAuthorizationCode: String(payload.appleAuthorizationCode || "")
121
+ }, {
122
+ beforeDelete: async () => {
123
+ await events.publish({ type: "account.deleting", userId: String(profile.id), email: String(profile.email || "") });
124
+ await userProfilesRepository.deleteWithSettings(profile.id);
125
+ }
126
+ });
127
+ return Object.freeze({
128
+ message: "Account deleted.",
129
+ messageCode: "users.account.deleted",
130
+ messageParams: Object.freeze({})
131
+ });
132
+ }
133
+
93
134
  return Object.freeze({
135
+ deleteAccount,
94
136
  changePassword,
95
137
  // readable-check: allow setter-seam - not a slot: setPasswordMethodEnabled is a service operation
96
138
  setPasswordMethodEnabled,
@@ -489,6 +489,18 @@ function createRepository({ userProfiles, userSettings }) {
489
489
  return ids.length < 1 ? total : total - await countProfiles({ ...filters, id: ids }, options);
490
490
  }
491
491
 
492
+ /** Deletes a user's profile and settings, in one transaction, as their account goes. */
493
+ async function deleteWithSettings(userId, options = {}) {
494
+ const normalizedUserId = normalizeRecordId(userId, { fallback: null });
495
+ if (!normalizedUserId) {
496
+ return;
497
+ }
498
+ await userProfiles.withTransaction(options, async (txOptions) => {
499
+ await userSettings.deleteForUserId(normalizedUserId, txOptions);
500
+ await userProfiles.delete(normalizedUserId, { ...options, ...txOptions, missing: "skip" });
501
+ });
502
+ }
503
+
492
504
  return Object.freeze({
493
505
  withTransaction: userProfiles.withTransaction,
494
506
  // The users as a join source for another owner's report, which reads them in its own statement: the handle's
@@ -509,6 +521,7 @@ function createRepository({ userProfiles, userSettings }) {
509
521
  listByIds,
510
522
  changeUsername,
511
523
  countUsers,
524
+ deleteWithSettings,
512
525
  // The CRUD surface's reads (a CRUD feature serving the users table names this repository as its ownerRepository).
513
526
  query: userProfiles.query,
514
527
  get: userProfiles.get,
@@ -156,6 +156,15 @@ function createRepository({ userSettings }) {
156
156
  return patchUserSettings(userId, { passwordSetupRequired: required }, options);
157
157
  }
158
158
 
159
+ /** Deletes a user's settings, with the account. */
160
+ async function deleteForUserId(userId, options = {}) {
161
+ const normalizedUserId = normalizeRecordId(userId, { fallback: null });
162
+ if (!normalizedUserId) {
163
+ return;
164
+ }
165
+ await userSettings.delete(normalizedUserId, { ...options, missing: "skip" });
166
+ }
167
+
159
168
  return Object.freeze({
160
169
  withTransaction: userSettings.withTransaction,
161
170
  // The users' settings as a join source for another owner's report, which reads them in its own statement: the
@@ -168,7 +177,8 @@ function createRepository({ userSettings }) {
168
177
  updatePreferences,
169
178
  updateNotifications,
170
179
  updatePasswordSignInEnabled,
171
- updatePasswordSetupRequired
180
+ updatePasswordSetupRequired,
181
+ deleteForUserId
172
182
  });
173
183
  }
174
184
 
@@ -21,7 +21,8 @@ function createUsersRuntime({
21
21
  profileProjector,
22
22
  profiles: userProfilesRepository,
23
23
  settings: userSettingsRepository,
24
- storage
24
+ storage,
25
+ events
25
26
  }) {
26
27
  const avatarStorageService = createAvatarStorageService({ storage });
27
28
  const avatarService = createAvatarService({ userProfilesRepository, avatarStorageService });
@@ -44,7 +45,8 @@ function createUsersRuntime({
44
45
  const accountSecurityService = createAccountSecurityService({
45
46
  authService,
46
47
  userProfilesRepository,
47
- userSettingsRepository
48
+ userSettingsRepository,
49
+ events
48
50
  });
49
51
 
50
52
  return Object.freeze({
@@ -0,0 +1,64 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { createService } from "../src/server/accountSecurity/accountSecurityService.js";
4
+ import { createAccountSecurityActions } from "../src/server/accountSecurity/accountSecurityActions.js";
5
+
6
+ const PROFILE = { id: "7", email: "ada@example.com", authProvider: "local", authProviderUserSid: "usr_7" };
7
+
8
+ /** The users' repositories and the provider as recording stand-ins: what the deletion asked of each, in order. */
9
+ function harness({ mfaEnrolled = false, proofRefused = false } = {}) {
10
+ const steps = [];
11
+ const published = [];
12
+ const userProfilesRepository = {
13
+ async findByIdentity() { return PROFILE; },
14
+ async findById() { return PROFILE; },
15
+ async deleteWithSettings(id) { steps.push(["deleteProfile", id]); }
16
+ };
17
+ const authService = {
18
+ getCapabilities: () => ({ features: { securityStatus: true } }),
19
+ async getSecurityStatus() { return { mfa: { enrolled: mfaEnrolled } }; },
20
+ async deleteAccount(_request, input, { beforeDelete }) {
21
+ steps.push(["proof", input.password]);
22
+ if (proofRefused) throw Object.assign(new Error("That password isn't right."), { status: 400 });
23
+ await beforeDelete({ userId: "usr_7", email: PROFILE.email });
24
+ steps.push(["deleteAuthAccount"]);
25
+ return { ok: true, session: null };
26
+ }
27
+ };
28
+ const events = { async publish(event) { published.push(event); steps.push(["event", event.type]); } };
29
+ const service = createService({ userSettingsRepository: {}, userProfilesRepository, authService, events });
30
+ return { service, steps, published };
31
+ }
32
+
33
+ const user = { id: "7", email: "ada@example.com" };
34
+
35
+ test("an account is deleted after its proof: the event first, then the profile, then the sign-in account", async () => {
36
+ const { service, steps, published } = harness();
37
+ const answer = await service.deleteAccount({ secondFactorAt: "" }, user, { password: "pw" });
38
+ assert.deepEqual(answer, { message: "Account deleted.", messageCode: "users.account.deleted", messageParams: {} });
39
+ assert.deepEqual(steps, [["proof", "pw"], ["event", "account.deleting"], ["deleteProfile", "7"], ["deleteAuthAccount"]]);
40
+ assert.deepEqual(published, [{ type: "account.deleting", userId: "7", email: "ada@example.com" }], "announced once");
41
+ });
42
+
43
+ test("a refused proof deletes nothing, and an account with a second factor proves it within ten minutes", async () => {
44
+ const refused = harness({ proofRefused: true });
45
+ await assert.rejects(refused.service.deleteAccount({}, user, { password: "wrong" }), { status: 400 });
46
+ assert.deepEqual(refused.steps, [["proof", "wrong"]]);
47
+ assert.deepEqual(refused.published, []);
48
+
49
+ const withMfa = harness({ mfaEnrolled: true });
50
+ await assert.rejects(withMfa.service.deleteAccount({ secondFactorAt: "" }, user, {}), { code: "auth.secondFactor.required" });
51
+ await assert.rejects(withMfa.service.deleteAccount({ secondFactorAt: new Date(Date.now() - 11 * 60_000).toISOString() }, user, {}), { code: "auth.secondFactor.required" });
52
+ assert.deepEqual(withMfa.steps, []);
53
+ await withMfa.service.deleteAccount({ secondFactorAt: new Date().toISOString() }, user, {});
54
+ assert.equal(withMfa.steps.at(-1)[0], "deleteAuthAccount");
55
+ });
56
+
57
+ test("a provider that cannot delete accounts says so, and the action is the signed-in person's own", async () => {
58
+ const { service } = harness();
59
+ const unsupported = createService({ userSettingsRepository: {}, userProfilesRepository: { findById: async () => PROFILE, findByIdentity: async () => PROFILE }, authService: {}, events: { publish() {} } });
60
+ await assert.rejects(unsupported.deleteAccount({}, user, {}), { status: 501, code: "users.account.deletionUnsupported" });
61
+ const [action] = createAccountSecurityActions({ accountSecurityService: service }).filter((entry) => entry.id === "settings.security.account.delete");
62
+ assert.deepEqual(action.permission, { require: "authenticated" });
63
+ assert.ok(!action.channels.includes("automation"), "only the person's own request deletes an account");
64
+ });
@@ -84,7 +84,8 @@ test("UsersFeature assembles account behavior through explicit capabilities", as
84
84
  assert.equal(typeof users.services.accountProfile.updateProfile, "function");
85
85
  assert.equal(routes.includes("GET /api/settings"), true);
86
86
  assert.equal(routes.includes("POST /api/settings/security/change-password"), true);
87
- assert.equal(actionCatalogue.listDefinitions().length, 11);
87
+ assert.equal(routes.includes("DELETE /api/account"), true);
88
+ assert.equal(actionCatalogue.listDefinitions().length, 12);
88
89
  assert.deepEqual(bootstrap.diagnostics().contributorIds, ["users.bootstrap"]);
89
90
  assert.equal(typeof profileProjector.syncIdentityProfile, "function");
90
91
  assert.equal(typeof profileProjector.findByIdentity, "function");