@jskit-ai/users-core 0.2.3 → 0.2.5

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.
Files changed (53) hide show
  1. package/locales/en.json +1 -7
  2. package/package.json +42 -19
  3. package/patterns/user-administration-server/PATTERN.md +16 -1
  4. package/patterns/user-administration-server/example/packages/users/package.json +3 -2
  5. package/patterns/user-administration-server/example/packages/users/src/server/types.js +5 -0
  6. package/patterns/user-administration-server/example/packages/users-workspace/package.json +4 -3
  7. package/patterns/user-administration-server/example/packages/users-workspace/src/server/UsersWorkspaceFeature.js +2 -9
  8. package/patterns/user-administration-server/example/packages/users-workspace/src/server/types.js +5 -0
  9. package/src/server/UsersFeature.js +26 -78
  10. package/src/server/UsersIdentityProvider.js +11 -22
  11. package/src/server/accountNotifications/accountNotificationsActions.js +28 -41
  12. package/src/server/accountNotifications/{bootAccountNotificationsRoutes.js → accountNotificationsRoutes.js} +1 -4
  13. package/src/server/accountNotifications/accountNotificationsService.js +9 -10
  14. package/src/server/accountPreferences/accountPreferencesActions.js +28 -41
  15. package/src/server/accountPreferences/{bootAccountPreferencesRoutes.js → accountPreferencesRoutes.js} +1 -4
  16. package/src/server/accountPreferences/accountPreferencesService.js +10 -10
  17. package/src/server/accountProfile/accountProfileActions.js +87 -127
  18. package/src/server/accountProfile/{bootAccountProfileRoutes.js → accountProfileRoutes.js} +12 -18
  19. package/src/server/accountProfile/accountProfileService.js +19 -35
  20. package/src/server/accountProfile/avatarService.js +15 -39
  21. package/src/server/accountProfile/avatarStorageService.js +2 -1
  22. package/src/server/accountSecurity/accountSecurityActions.js +100 -148
  23. package/src/server/accountSecurity/{bootAccountSecurityRoutes.js → accountSecurityRoutes.js} +9 -8
  24. package/src/server/accountSecurity/accountSecurityService.js +15 -44
  25. package/src/server/common/formatters/accountAvatarFormatter.js +4 -4
  26. package/src/server/common/formatters/accountSecurityStatusFormatter.js +2 -3
  27. package/src/server/common/formatters/accountSettingsResponseFormatter.js +11 -2
  28. package/src/server/common/repositories/userProfilesRepository.js +31 -55
  29. package/src/server/common/repositories/userSettingsRepository.js +16 -21
  30. package/src/server/common/services/accountContextService.js +9 -7
  31. package/src/server/common/services/authProfileSyncService.js +15 -42
  32. package/src/server/common/support/accountSettingsJsonApiTransport.js +10 -3
  33. package/src/server/common/support/realtimeServiceEvents.js +3 -2
  34. package/src/server/common/support/resolveActionUser.js +9 -2
  35. package/src/server/types.js +29 -0
  36. package/src/server/usersBootstrapContributor.js +60 -84
  37. package/src/server/usersExtensions.js +1 -0
  38. package/src/server/usersIdentity.js +28 -0
  39. package/src/server/usersRuntime.js +61 -0
  40. package/src/shared/operationMessages.js +6 -15
  41. package/src/shared/resources/userProfileResource.js +3 -31
  42. package/src/shared/resources/userProfileValues.js +32 -0
  43. package/src/shared/resources/userSettingsResource.js +2 -4
  44. package/test/accountProfileService.test.js +1 -0
  45. package/test/accountSecurityService.test.js +2 -4
  46. package/test/exportsContract.test.js +2 -0
  47. package/test/featureRuntime.test.js +11 -8
  48. package/test/i18nCodes.test.js +3 -10
  49. package/test/usersBootstrapContributor.test.js +0 -1
  50. package/test/usersPackageScaffoldContract.test.js +3 -5
  51. package/test/usersRouteRequestInputValidator.test.js +4 -4
  52. package/src/server/common/repositories/repositoryUtils.js +0 -44
  53. package/src/server/common/support/deepFreeze.js +0 -1
@@ -0,0 +1,32 @@
1
+ import { normalizeLowerText, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
2
+
3
+ // How a user profile's username, avatar key and avatar version are stored:
4
+ // the resource's setters and the profiles repository both normalize with these.
5
+ const USERNAME_MAX_LENGTH = 120;
6
+
7
+ function normalizeUsername(value) {
8
+ const normalized = normalizeLowerText(value)
9
+ .replace(/[^a-z0-9]+/g, "-")
10
+ .replace(/^-+|-+$/g, "")
11
+ .slice(0, USERNAME_MAX_LENGTH);
12
+
13
+ return normalized || "";
14
+ }
15
+
16
+ function normalizeNullableString(value) {
17
+ if (value === null || value === undefined) {
18
+ return null;
19
+ }
20
+
21
+ return normalizeText(value);
22
+ }
23
+
24
+ function normalizeNullableVersion(value) {
25
+ if (value === null || value === undefined || value === "") {
26
+ return null;
27
+ }
28
+
29
+ return String(value);
30
+ }
31
+
32
+ export { USERNAME_MAX_LENGTH, normalizeNullableString, normalizeNullableVersion, normalizeUsername };
@@ -5,7 +5,7 @@ import {
5
5
  createSchemaDefinition
6
6
  } from "@jskit-ai/resource-core/shared/resource";
7
7
  import { defineCrudResource } from "@jskit-ai/resource-crud-core/shared/crudResource";
8
- import { createOperationMessages } from "../operationMessages.js";
8
+ import { OPERATION_MESSAGES } from "../operationMessages.js";
9
9
  import { DEFAULT_USER_SETTINGS, normalizeLocaleCode } from "../settings.js";
10
10
  import {
11
11
  accountSecurityStatusSchema,
@@ -252,8 +252,6 @@ const logoutOtherSessionsOutputSchema = createSchema({
252
252
  ok: { type: "boolean", required: true }
253
253
  });
254
254
 
255
- const USER_SETTINGS_OPERATION_MESSAGES = createOperationMessages();
256
-
257
255
  const userSettingsResource = defineCrudResource({
258
256
  namespace: "userSettings",
259
257
  tableName: "user_settings",
@@ -371,7 +369,7 @@ const userSettingsResource = defineCrudResource({
371
369
  }
372
370
  }
373
371
  },
374
- messages: USER_SETTINGS_OPERATION_MESSAGES,
372
+ messages: OPERATION_MESSAGES,
375
373
  crudOperations: ["view", "list", "create", "replace", "patch"],
376
374
  crud: {
377
375
  output: userSettingsOutputValidator,
@@ -11,6 +11,7 @@ test("profile updates use the auth provider's display-name input contract", asyn
11
11
  userSettingsRepository: { async ensureForUserId(id) { assert.equal(id, 7); return {}; } },
12
12
  avatarService: {},
13
13
  authService: {
14
+ getCapabilities() { return {}; },
14
15
  async updateDisplayName(actualRequest, input) {
15
16
  assert.equal(actualRequest, request);
16
17
  assert.deepEqual(input, { displayName: "After" });
@@ -26,9 +26,7 @@ test("account security service returns no content result for other sessions", as
26
26
  id: "request-1"
27
27
  };
28
28
 
29
- const result = await service.logoutOtherSessions(request, {
30
- id: "user-1"
31
- });
29
+ const result = await service.logoutOtherSessions(request);
32
30
 
33
31
  assert.equal(result, null);
34
32
  assert.deepEqual(calls, [request]);
@@ -59,7 +57,7 @@ test("unlinking returns the security status in the settings output contract", as
59
57
  }
60
58
  }
61
59
  });
62
- const result = await service.unlinkOAuthProvider({}, { id: "user-1" }, { provider: "github" });
60
+ const result = await service.unlinkOAuthProvider({}, { provider: "github" });
63
61
  const output = outputOf(result.value);
64
62
  assert.equal(output.ok, true, JSON.stringify(output.fieldErrors));
65
63
  assert.equal(result.value.securityStatus.authMethods[1].canEnable, true);
@@ -17,6 +17,8 @@ test("users-core exports are explicit and aligned with production/template usage
17
17
  "./server/UsersFeature",
18
18
  "./server/UsersIdentityProvider",
19
19
  "./server/usersExtensions",
20
+ // Features that require this package's capabilities take their types from it.
21
+ "./server/types",
20
22
  // The generated client bootstrap registers the package's English catalog.
21
23
  "./locales/en.json"
22
24
  ]
@@ -1,9 +1,9 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
- import { createActionProvider } from "@jskit-ai/kernel/server/actions";
3
+ import { ActionProvider } from "@jskit-ai/kernel/server/actions";
4
+ import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
4
5
  import { createCapabilityRuntime, defineProvider } from "@jskit-ai/kernel/shared/capabilities";
5
- import { createBootstrapRuntime } from "@jskit-ai/kernel/server/runtime";
6
- import { createAuthExtensions } from "@jskit-ai/auth-core/server/authExtensions";
6
+ import { createBootstrapRuntime, EventProvider } from "@jskit-ai/kernel/server/runtime";
7
7
  import { UsersExtensionsProvider } from "../src/server/UsersExtensionsProvider.js";
8
8
  import { UsersFeature } from "../src/server/UsersFeature.js";
9
9
  import { UsersIdentityProvider } from "../src/server/UsersIdentityProvider.js";
@@ -25,25 +25,27 @@ function createJsonRestApiFixture() {
25
25
  test("UsersFeature assembles account behavior through explicit capabilities", async () => {
26
26
  const routes = [];
27
27
  const bootstrap = createBootstrapRuntime();
28
- const authExtensions = createAuthExtensions();
29
28
  const jsonRestApi = createJsonRestApiFixture();
30
29
  let users = null;
31
30
  let actionCatalogue = null;
31
+ let profileProjector = null;
32
32
  const probe = defineProvider({
33
33
  id: "test.users.probe",
34
34
  requires: {
35
35
  actions: "runtime.actions",
36
+ projector: "auth.profile.projector",
36
37
  usersCapability: "users.core"
37
38
  },
38
- setup({ actions, usersCapability }) {
39
+ setup({ actions, projector, usersCapability }) {
39
40
  actionCatalogue = actions;
41
+ profileProjector = projector;
40
42
  users = usersCapability;
41
43
  return {};
42
44
  }
43
45
  });
44
46
  const runtime = createCapabilityRuntime({
45
47
  inputs: {
46
- "auth.extensions": authExtensions,
48
+ "runtime.logger": silentLogger,
47
49
  "auth.service": {},
48
50
  "runtime.bootstrap": bootstrap,
49
51
  "runtime.http": {
@@ -61,7 +63,7 @@ test("UsersFeature assembles account behavior through explicit capabilities", as
61
63
  },
62
64
  "runtime.uploads": { readSingleMultipartFile() {} }
63
65
  },
64
- providers: [createActionProvider(), UsersExtensionsProvider, UsersIdentityProvider, UsersFeature, probe]
66
+ providers: [EventProvider, ActionProvider, UsersExtensionsProvider, UsersIdentityProvider, UsersFeature, probe]
65
67
  });
66
68
 
67
69
  await runtime.start();
@@ -73,5 +75,6 @@ test("UsersFeature assembles account behavior through explicit capabilities", as
73
75
  assert.equal(routes.includes("POST /api/settings/security/change-password"), true);
74
76
  assert.equal(actionCatalogue.listDefinitions().length, 11);
75
77
  assert.deepEqual(bootstrap.diagnostics().contributorIds, ["users.bootstrap"]);
76
- assert.equal(authExtensions.resolveProfileProjector().projectorId, "users.profile");
78
+ assert.equal(typeof profileProjector.syncIdentityProfile, "function");
79
+ assert.equal(typeof profileProjector.findByIdentity, "function");
77
80
  });
@@ -34,14 +34,7 @@ test("account services throw coded errors whose catalog English matches", async
34
34
  avatarService: { async readForUser() { return null; } }
35
35
  });
36
36
  await assert.rejects(() => profileService.getForUser({}, { id: 7 }), assertCodedError("users.profile.notFound"));
37
- await assert.rejects(() => profileService.readAvatar({}, { id: 7 }), assertCodedError("users.avatar.notFound"));
38
-
39
- const securityService = createAccountSecurityService({ userSettingsRepository: {}, userProfilesRepository: emptyProfiles });
40
- await assert.rejects(() => securityService.changePassword({}, { id: 7 }), assertCodedError("users.security.passwordChangeUnavailable"));
41
- await assert.rejects(() => securityService.setPasswordMethodEnabled({}, { id: 7 }), assertCodedError("users.security.passwordMethodToggleUnavailable"));
42
- await assert.rejects(() => securityService.startOAuthProviderLink({}, { id: 7 }), assertCodedError("users.security.oauthLinkUnavailable"));
43
- await assert.rejects(() => securityService.unlinkOAuthProvider({}, { id: 7 }), assertCodedError("users.security.oauthUnlinkUnavailable"));
44
- await assert.rejects(() => securityService.logoutOtherSessions({}, { id: 7 }), assertCodedError("users.security.logoutOtherSessionsUnavailable"));
37
+ await assert.rejects(() => profileService.readAvatar({ id: 7 }), assertCodedError("users.avatar.notFound"));
45
38
  });
46
39
 
47
40
  test("password change codes its field error and its success message", async () => {
@@ -52,7 +45,7 @@ test("password change codes its field error and its success message", async () =
52
45
  });
53
46
 
54
47
  await assert.rejects(
55
- () => service.changePassword({}, { id: 7 }, { newPassword: "new-password", confirmPassword: "other" }),
48
+ () => service.changePassword({}, { newPassword: "new-password", confirmPassword: "other" }),
56
49
  (error) => {
57
50
  const coded = error.details.fieldErrorCodes.confirmPassword;
58
51
  assert.equal(coded.code, "users.security.passwordConfirmationMismatch");
@@ -61,7 +54,7 @@ test("password change codes its field error and its success message", async () =
61
54
  }
62
55
  );
63
56
 
64
- const { response } = await service.changePassword({}, { id: 7 }, { newPassword: "new-password", confirmPassword: "new-password" });
57
+ const { response } = await service.changePassword({}, { newPassword: "new-password", confirmPassword: "new-password" });
65
58
  assert.deepEqual(response.value, { message: "Password updated.", messageCode: "users.security.passwordUpdated", messageParams: {} });
66
59
  assert.equal(catalogEnglish(response.value.messageCode), response.value.message);
67
60
  });
@@ -82,7 +82,6 @@ test("users bootstrap contributor exposes the generic authenticated bootstrap pa
82
82
  },
83
83
  reply
84
84
  });
85
- assert.equal(contributor.order, 100);
86
85
  assert.equal(writtenSessions.length, 1);
87
86
  assert.equal(writtenSessions[0].reply, reply);
88
87
  assert.deepEqual(writtenSessions[0].session, {
@@ -38,7 +38,7 @@ test("global user administration example is one declarative CRUD feature", async
38
38
  assert.doesNotMatch(feature, /\.make\(|\.singleton\(|containerToken|repositoryToken|serviceToken/);
39
39
  });
40
40
 
41
- test("workspace user administration example makes route and action scope explicit", async () => {
41
+ test("workspace user administration example takes workspaces-core's workspace CRUD scope", async () => {
42
42
  const packageManifest = JSON.parse(await readFile(
43
43
  path.join(patternRoot, "example", "packages", "users-workspace", "package.json"),
44
44
  "utf8"
@@ -60,10 +60,8 @@ test("workspace user administration example makes route and action scope explici
60
60
  assert.equal(packageManifest.jskit?.mutations, undefined);
61
61
  assert.deepEqual(packageManifest.jskit?.capabilities?.provides, ["app.users-workspace"]);
62
62
  assert.match(feature, /ownershipFilter: "workspace"/);
63
- assert.match(feature, /routeBase: "\/w\/:workspaceSlug"/);
64
- assert.match(feature, /actionInputValidator: workspaceSlugParamsValidator/);
65
- assert.match(feature, /inputKeys: \["workspaceSlug"\]/);
66
- assert.match(feature, /buildWorkspaceInputFromRouteParams/);
63
+ assert.match(feature, /import \{ WORKSPACE_CRUD_SCOPE \} from "@jskit-ai\/workspaces-core\/server\/support\/workspaceCrud";/);
64
+ assert.match(feature, /scope: WORKSPACE_CRUD_SCOPE/);
67
65
  assert.doesNotMatch(feature, /\.make\(|\.singleton\(|containerToken|repositoryToken|serviceToken/);
68
66
  });
69
67
 
@@ -4,10 +4,10 @@ import { readSingleMultipartFile } from "@jskit-ai/uploads-runtime/server/multip
4
4
  import { createRouter } from "../../kernel/server/http/lib/router.js";
5
5
  import { validateOperationSection } from "../../http-runtime/src/shared/validators/operationValidation.js";
6
6
  import { userProfileResource } from "../src/shared/resources/userProfileResource.js";
7
- import { registerAccountProfileRoutes } from "../src/server/accountProfile/bootAccountProfileRoutes.js";
8
- import { registerAccountPreferencesRoutes } from "../src/server/accountPreferences/bootAccountPreferencesRoutes.js";
9
- import { registerAccountNotificationsRoutes } from "../src/server/accountNotifications/bootAccountNotificationsRoutes.js";
10
- import { registerAccountSecurityRoutes } from "../src/server/accountSecurity/bootAccountSecurityRoutes.js";
7
+ import { registerAccountProfileRoutes } from "../src/server/accountProfile/accountProfileRoutes.js";
8
+ import { registerAccountPreferencesRoutes } from "../src/server/accountPreferences/accountPreferencesRoutes.js";
9
+ import { registerAccountNotificationsRoutes } from "../src/server/accountNotifications/accountNotificationsRoutes.js";
10
+ import { registerAccountSecurityRoutes } from "../src/server/accountSecurity/accountSecurityRoutes.js";
11
11
 
12
12
  function createReplyDouble() {
13
13
  return {
@@ -1,44 +0,0 @@
1
- import {
2
- normalizeDbRecordId,
3
- retryDeadlocks,
4
- toIsoString
5
- } from "@jskit-ai/database-runtime/shared";
6
- import { findDuplicateEntryError, isDuplicateEntryError } from "@jskit-ai/database-runtime/shared/duplicateEntry";
7
- import { normalizeLowerText, normalizeRecordId, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
8
-
9
- function uniqueSorted(values) {
10
- return [...new Set(values)].sort((left, right) => String(left).localeCompare(String(right)));
11
- }
12
-
13
- function parseJson(value, fallback = {}) {
14
- if (value == null) {
15
- return fallback;
16
- }
17
- if (typeof value === "object") {
18
- return value;
19
- }
20
- try {
21
- return JSON.parse(String(value));
22
- } catch {
23
- return fallback;
24
- }
25
- }
26
-
27
- function toDbJson(value, fallback = {}) {
28
- const source = value && typeof value === "object" ? value : fallback;
29
- return JSON.stringify(source);
30
- }
31
-
32
- export {
33
- toIsoString,
34
- retryDeadlocks,
35
- isDuplicateEntryError,
36
- findDuplicateEntryError,
37
- normalizeText,
38
- normalizeLowerText,
39
- normalizeRecordId,
40
- normalizeDbRecordId,
41
- uniqueSorted,
42
- parseJson,
43
- toDbJson
44
- };
@@ -1 +0,0 @@
1
- export { deepFreeze } from "@jskit-ai/kernel/shared/support/deepFreeze";