@jskit-ai/auth-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 (38) hide show
  1. package/locales/en.json +0 -1
  2. package/package.json +9 -3
  3. package/src/server/actions/authActions.js +167 -0
  4. package/src/server/authAccess.js +24 -0
  5. package/src/server/authExtensions.js +19 -25
  6. package/src/server/authPolicy.js +57 -0
  7. package/src/server/authPolicyContextResolverRegistry.js +5 -4
  8. package/src/server/authServiceDecoratorRegistry.js +8 -6
  9. package/src/server/deferredAuthService.js +1 -0
  10. package/src/server/devAuth.js +24 -7
  11. package/src/server/lib/actionContextContributor.js +23 -20
  12. package/src/server/lib/authPolicySupport.js +12 -2
  13. package/src/server/lib/errors.js +4 -2
  14. package/src/server/lib/plugin.js +15 -22
  15. package/src/server/lib/routeMeta.js +1 -0
  16. package/src/server/lib/routeVisibilityResolver.js +18 -17
  17. package/src/server/noAppProfiles.js +16 -0
  18. package/src/server/providers/AuthAccessProvider.js +2 -20
  19. package/src/server/providers/AuthFeature.js +5 -2
  20. package/src/server/providers/AuthPolicyProvider.js +10 -38
  21. package/src/server/types.js +103 -0
  22. package/src/server/unsupportedOperation.js +4 -2
  23. package/src/server/utils.js +5 -3
  24. package/src/server/validators.js +2 -3
  25. package/src/shared/authApi.js +85 -49
  26. package/src/shared/authCapabilities.js +9 -3
  27. package/src/shared/authMethods.js +5 -0
  28. package/src/shared/authSecurityStatus.js +1 -0
  29. package/src/shared/commands/authDevLoginAsCommand.js +1 -1
  30. package/src/shared/commands/authLoginOAuthCompleteCommand.js +1 -1
  31. package/src/shared/commands/authLoginOtpVerifyCommand.js +1 -1
  32. package/src/shared/commands/authPasswordRecoveryCompleteCommand.js +1 -1
  33. package/src/shared/index.js +1 -1
  34. package/src/shared/signOutFlow.js +16 -10
  35. package/test/authActions.test.js +11 -7
  36. package/test/devAuth.test.js +2 -1
  37. package/test/providerRuntime.test.js +9 -6
  38. package/src/server/actions/auth.contributor.js +0 -234
@@ -131,6 +131,11 @@ function buildOAuthMethodDefinitions(oauthProviders = []) {
131
131
  return Object.freeze(definitions);
132
132
  }
133
133
 
134
+ /**
135
+ * The sign-in methods: password, OTP and one per OAuth provider.
136
+ * @param {{ oauthProviders?: Array<{ id: string, label?: string }> }} [options]
137
+ */
138
+ // readable-check: allow dependency-default - data: oauthProviders lists provider entries, and an absent list has none
134
139
  function buildAuthMethodDefinitions({ oauthProviders = [] } = {}) {
135
140
  return Object.freeze([...AUTH_METHOD_DEFINITIONS, ...buildOAuthMethodDefinitions(oauthProviders)]);
136
141
  }
@@ -44,6 +44,7 @@ function normalizeSecurityActions(value = {}) {
44
44
  const source = value && typeof value === "object" && !Array.isArray(value) ? value : {};
45
45
  return Object.freeze({
46
46
  changePassword: normalizeBoolean(source.changePassword),
47
+ // readable-check: allow setter-seam - not a slot: setPasswordEnabled says whether the security status offers that action
47
48
  setPasswordEnabled: normalizeBoolean(source.setPasswordEnabled),
48
49
  linkProvider: normalizeBoolean(source.linkProvider),
49
50
  unlinkProvider: normalizeBoolean(source.unlinkProvider),
@@ -32,7 +32,7 @@ const authDevLoginAsBodyValidator = deepFreeze({
32
32
  required: false
33
33
  }
34
34
  }),
35
- mode: "patch",
35
+ mode: "create",
36
36
  messages: {
37
37
  ...AUTH_DEV_LOGIN_AS_MESSAGES,
38
38
  keywords: {
@@ -46,7 +46,7 @@ const authLoginOAuthCompleteBodyValidator = deepFreeze({
46
46
  error_code: { type: "string", required: false, minLength: 1, maxLength: 128 },
47
47
  error_description: { type: "string", required: false, minLength: 1, maxLength: 1024 }
48
48
  }),
49
- mode: "patch",
49
+ mode: "create",
50
50
  messages: AUTH_LOGIN_OAUTH_COMPLETE_MESSAGES
51
51
  });
52
52
 
@@ -47,7 +47,7 @@ const authLoginOtpVerifyBodyValidator = deepFreeze({
47
47
  enum: ["email"]
48
48
  }
49
49
  }),
50
- mode: "patch",
50
+ mode: "create",
51
51
  messages: AUTH_LOGIN_OTP_VERIFY_MESSAGES
52
52
  });
53
53
 
@@ -53,7 +53,7 @@ const authPasswordRecoveryCompleteBodyValidator = deepFreeze({
53
53
  enum: ["recovery"]
54
54
  }
55
55
  }),
56
- mode: "patch",
56
+ mode: "create",
57
57
  messages: AUTH_PASSWORD_RECOVERY_COMPLETE_MESSAGES
58
58
  });
59
59
 
@@ -10,7 +10,7 @@ export {
10
10
  export { AUTH_PATHS, buildAuthOauthStartPath } from "./authPaths.js";
11
11
  export {
12
12
  AUTH_PASSWORD_RECOVERY_DELIVERIES,
13
- AUTH_OPTIONAL_OPERATION_FEATURES,
13
+ AUTH_OPERATION_FEATURES,
14
14
  normalizeAuthProviderId,
15
15
  normalizeAuthCapabilities,
16
16
  getCapabilityFeature,
@@ -2,26 +2,32 @@ function normalizeAuthApi(authApi) {
2
2
  if (!authApi || typeof authApi !== "object") {
3
3
  throw new TypeError("runAuthSignOutFlow requires authApi.");
4
4
  }
5
+ // readable-check: allow method-probe - input validation: runAuthSignOutFlow checks the authApi an application passes
5
6
  if (typeof authApi.logout !== "function") {
6
7
  throw new TypeError("runAuthSignOutFlow requires authApi.logout().");
7
8
  }
8
9
  return authApi;
9
10
  }
10
11
 
11
- async function runAuthSignOutFlow({ authApi, clearCsrfTokenCache = null, afterSignOut = null } = {}) {
12
- const normalizedAuthApi = normalizeAuthApi(authApi);
13
- const clearFn = typeof clearCsrfTokenCache === "function" ? clearCsrfTokenCache : null;
14
- const afterFn = typeof afterSignOut === "function" ? afterSignOut : null;
12
+ function keepCsrfTokenCache() {}
13
+
14
+ async function doNothingAfterSignOut() {}
15
15
 
16
+ /**
17
+ * Signs out through authApi.logout(), then clears the CSRF token cache and
18
+ * runs afterSignOut, whether or not the logout succeeded.
19
+ * @param {object} options
20
+ * @param {{ logout(): Promise<unknown> }} options.authApi
21
+ * @param {() => void} [options.clearCsrfTokenCache]
22
+ * @param {() => unknown} [options.afterSignOut]
23
+ */
24
+ async function runAuthSignOutFlow({ authApi, clearCsrfTokenCache = keepCsrfTokenCache, afterSignOut = doNothingAfterSignOut } = {}) {
25
+ const normalizedAuthApi = normalizeAuthApi(authApi);
16
26
  try {
17
27
  await normalizedAuthApi.logout();
18
28
  } finally {
19
- if (clearFn) {
20
- clearFn();
21
- }
22
- if (afterFn) {
23
- await afterFn();
24
- }
29
+ clearCsrfTokenCache();
30
+ await afterSignOut();
25
31
  }
26
32
  }
27
33
 
@@ -1,8 +1,10 @@
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 { EventProvider } from "@jskit-ai/kernel/server/runtime";
5
+ import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
4
6
  import { createCapabilityRuntime, defineProvider } from "@jskit-ai/kernel/shared/capabilities";
5
- import { buildAuthActions } from "../src/server/actions/auth.contributor.js";
7
+ import { createAuthActions } from "../src/server/actions/authActions.js";
6
8
  import { AuthFeature } from "../src/server/providers/AuthFeature.js";
7
9
 
8
10
  test("auth logout action delegates directly to the selected auth service", async () => {
@@ -13,7 +15,7 @@ test("auth logout action delegates directly to the selected auth service", async
13
15
  return { ok: true, clearSession: true };
14
16
  }
15
17
  };
16
- const action = buildAuthActions({ authService }).find((definition) => definition.id === "auth.logout");
18
+ const action = createAuthActions({ authService }).find((definition) => definition.id === "auth.logout");
17
19
  const request = { id: "request-1" };
18
20
  assert.deepEqual(await action.execute({}, { requestMeta: { request } }), {
19
21
  ok: true,
@@ -26,9 +28,9 @@ test("shared dev login-as action passes the trusted request to auth.service", as
26
28
  const input = { email: "ada@example.com" };
27
29
  const request = { headers: { "x-jskit-dev-auth-secret": "secret" } };
28
30
  let received = null;
29
- const action = buildAuthActions({
31
+ const action = createAuthActions({
30
32
  authService: {
31
- async devLoginAs(receivedRequest, receivedInput) {
33
+ async devLoginAs(receivedInput, receivedRequest) {
32
34
  received = { input: receivedInput, request: receivedRequest };
33
35
  return { ok: true };
34
36
  }
@@ -65,7 +67,8 @@ test("AuthFeature contributes actions only when auth.service exists", async () =
65
67
  }
66
68
  });
67
69
  const runtime = createCapabilityRuntime({
68
- providers: [createActionProvider(), SelectedAuthProvider, AuthFeature, ProbeProvider]
70
+ inputs: { "runtime.logger": silentLogger },
71
+ providers: [EventProvider, ActionProvider, SelectedAuthProvider, AuthFeature, ProbeProvider]
69
72
  });
70
73
  await runtime.start();
71
74
  assert.equal(actions.listDefinitions().some((definition) => definition.id === "auth.login.password"), true);
@@ -81,7 +84,8 @@ test("AuthFeature contributes actions only when auth.service exists", async () =
81
84
  }
82
85
  });
83
86
  const noAuthRuntime = createCapabilityRuntime({
84
- providers: [createActionProvider(), AuthFeature, EmptyProbe]
87
+ inputs: { "runtime.logger": silentLogger },
88
+ providers: [EventProvider, ActionProvider, AuthFeature, EmptyProbe]
85
89
  });
86
90
  await noAuthRuntime.start();
87
91
  assert.deepEqual(publicActions.listDefinitions(), []);
@@ -112,7 +112,8 @@ test("dev auth refusals carry their own codes", () => {
112
112
  return null;
113
113
  };
114
114
  assert.equal(codeOf(() => ensureDevAuthRuntimeAvailable(resolveDevAuthPolicy(), createRequest())), "auth.dev.unavailable");
115
- assert.equal(codeOf(() => ensureDevAuthRuntimeAvailable(enabledPolicy({ secret: "" }), createRequest())), "auth.dev.secretMissing");
115
+ assert.throws(() => ensureDevAuthRuntimeAvailable(enabledPolicy({ secret: "" }), createRequest()), (error) =>
116
+ error.message === "AUTH_DEV_BYPASS_SECRET is required when AUTH_DEV_BYPASS_ENABLED=true." && error.code === undefined);
116
117
  assert.equal(
117
118
  codeOf(() => ensureDevAuthRuntimeAvailable(enabledPolicy(), createRequest({ host: "example.com" }))),
118
119
  "auth.dev.localhostOnly"
@@ -1,7 +1,9 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
3
  import Fastify from "fastify";
4
- import { createActionProvider } from "@jskit-ai/kernel/server/actions";
4
+ import { ActionProvider } from "@jskit-ai/kernel/server/actions";
5
+ import { EventProvider } from "@jskit-ai/kernel/server/runtime";
6
+ import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
5
7
  import { createCapabilityRuntime, defineProvider } from "@jskit-ai/kernel/shared/capabilities";
6
8
  import { HttpProvider } from "@jskit-ai/kernel/server/http";
7
9
  import { createFakeFastifyPolicyRuntime } from "../../../tooling/testUtils/fakeFastify.mjs";
@@ -19,7 +21,8 @@ function createFastify() {
19
21
  function runtimeInputs(fastify) {
20
22
  return {
21
23
  "runtime.env": { NODE_ENV: "test" },
22
- "runtime.fastify": fastify
24
+ "runtime.fastify": fastify,
25
+ "runtime.logger": silentLogger
23
26
  };
24
27
  }
25
28
 
@@ -28,7 +31,7 @@ test("AuthPolicyProvider installs Fastify policy and explicit action/visibility
28
31
  const runtime = createCapabilityRuntime({
29
32
  inputs: runtimeInputs(fastify),
30
33
  providers: [
31
- createActionProvider(),
34
+ EventProvider, ActionProvider,
32
35
  HttpProvider,
33
36
  AuthExtensionsProvider,
34
37
  AuthFeature,
@@ -80,7 +83,7 @@ test("AuthPolicyProvider resolves registered workspace context without a service
80
83
  const runtime = createCapabilityRuntime({
81
84
  inputs: runtimeInputs(fastify),
82
85
  providers: [
83
- createActionProvider(),
86
+ EventProvider, ActionProvider,
84
87
  HttpProvider,
85
88
  AuthExtensionsProvider,
86
89
  AuthService,
@@ -113,7 +116,7 @@ test("auth policy denies protected routes when no auth service is installed", as
113
116
  const runtime = createCapabilityRuntime({
114
117
  inputs: runtimeInputs(fastify),
115
118
  providers: [
116
- createActionProvider(),
119
+ EventProvider, ActionProvider,
117
120
  HttpProvider,
118
121
  AuthExtensionsProvider,
119
122
  AuthFeature,
@@ -134,7 +137,7 @@ test("AuthPolicyProvider checks CSRF on unsafe methods when AUTH_CSRF_UNSAFE_MET
134
137
  const runtime = createCapabilityRuntime({
135
138
  inputs: runtimeInputs(app),
136
139
  providers: [
137
- createActionProvider(),
140
+ EventProvider, ActionProvider,
138
141
  HttpProvider,
139
142
  AuthExtensionsProvider,
140
143
  AuthFeature,
@@ -1,234 +0,0 @@
1
- import { createSchema } from "json-rest-schema";
2
- import {
3
- emptyInputValidator
4
- } from "@jskit-ai/kernel/server/actions/actionContributorHelpers";
5
- import {
6
- composeSchemaDefinitions
7
- } from "@jskit-ai/kernel/shared/validators";
8
- import { deepFreeze } from "@jskit-ai/kernel/shared/support/deepFreeze";
9
- import {
10
- authRegisterCommand,
11
- authRegisterConfirmationResendCommand,
12
- authLoginPasswordCommand,
13
- authLoginOtpRequestCommand,
14
- authLoginOtpVerifyCommand,
15
- authLoginOAuthStartCommand,
16
- authLoginOAuthCompleteCommand,
17
- authDevLoginAsCommand,
18
- authPasswordResetRequestCommand,
19
- authPasswordRecoveryCompleteCommand,
20
- authPasswordResetCommand
21
- } from "../../shared/commands/index.js";
22
-
23
- const authLoginOAuthStartInput = composeSchemaDefinitions([
24
- authLoginOAuthStartCommand.operation.params,
25
- authLoginOAuthStartCommand.operation.query
26
- ], {
27
- mode: "patch",
28
- context: "authContributor.authLoginOAuthStartInput"
29
- });
30
-
31
- const authLogoutOutput = deepFreeze({
32
- schema: createSchema({
33
- ok: { type: "boolean", required: true },
34
- clearSession: { type: "boolean", required: true }
35
- }),
36
- mode: "replace"
37
- });
38
-
39
- function requireRequestContext(context, actionId) {
40
- const request = context?.requestMeta?.request || null;
41
- if (request) {
42
- return request;
43
- }
44
-
45
- throw new Error(`${actionId} requires request context.`);
46
- }
47
-
48
- const authActionSpecifications = Object.freeze([
49
- {
50
- id: "auth.register",
51
- version: 1,
52
- kind: "command",
53
- channels: ["api", "internal"],
54
- surfacesFrom: "enabled",
55
- input: authRegisterCommand.operation.body,
56
- idempotency: "none",
57
- async run(authService, input) {
58
- return authService.register(input);
59
- }
60
- },
61
- {
62
- id: "auth.register.confirmation.resend",
63
- version: 1,
64
- kind: "command",
65
- channels: ["api", "internal"],
66
- surfacesFrom: "enabled",
67
- input: authRegisterConfirmationResendCommand.operation.body,
68
- idempotency: "none",
69
- async run(authService, input) {
70
- return authService.resendRegisterConfirmation(input);
71
- }
72
- },
73
- {
74
- id: "auth.login.password",
75
- version: 1,
76
- kind: "command",
77
- channels: ["api", "internal"],
78
- surfacesFrom: "enabled",
79
- input: authLoginPasswordCommand.operation.body,
80
- idempotency: "none",
81
- async run(authService, input) {
82
- return authService.login(input);
83
- }
84
- },
85
- {
86
- id: "auth.login.otp.request",
87
- version: 1,
88
- kind: "command",
89
- channels: ["api", "internal"],
90
- surfacesFrom: "enabled",
91
- input: authLoginOtpRequestCommand.operation.body,
92
- idempotency: "none",
93
- async run(authService, input) {
94
- return authService.requestOtpLogin(input);
95
- }
96
- },
97
- {
98
- id: "auth.login.otp.verify",
99
- version: 1,
100
- kind: "command",
101
- channels: ["api", "internal"],
102
- surfacesFrom: "enabled",
103
- input: authLoginOtpVerifyCommand.operation.body,
104
- idempotency: "none",
105
- async run(authService, input) {
106
- return authService.verifyOtpLogin(input);
107
- }
108
- },
109
- {
110
- id: "auth.login.oauth.start",
111
- version: 1,
112
- kind: "command",
113
- channels: ["api", "internal"],
114
- surfacesFrom: "enabled",
115
- input: authLoginOAuthStartInput,
116
- idempotency: "none",
117
- async run(authService, input, context) {
118
- return authService.oauthStart(input, context?.requestMeta?.request || null);
119
- }
120
- },
121
- {
122
- id: "auth.login.oauth.complete",
123
- version: 1,
124
- kind: "command",
125
- channels: ["api", "internal"],
126
- surfacesFrom: "enabled",
127
- input: authLoginOAuthCompleteCommand.operation.body,
128
- idempotency: "none",
129
- async run(authService, input, context) {
130
- return authService.oauthComplete(input, context?.requestMeta?.request || null);
131
- }
132
- },
133
- {
134
- id: "auth.dev.loginAs",
135
- version: 1,
136
- kind: "command",
137
- channels: ["api", "internal"],
138
- surfacesFrom: "enabled",
139
- input: authDevLoginAsCommand.operation.body,
140
- idempotency: "none",
141
- async run(authService, input, context) {
142
- return authService.devLoginAs(
143
- requireRequestContext(context, "auth.dev.loginAs"),
144
- input
145
- );
146
- }
147
- },
148
- {
149
- id: "auth.password.reset.request",
150
- version: 1,
151
- kind: "command",
152
- channels: ["api", "internal"],
153
- surfacesFrom: "enabled",
154
- input: authPasswordResetRequestCommand.operation.body,
155
- idempotency: "none",
156
- async run(authService, input) {
157
- return authService.requestPasswordReset(input);
158
- }
159
- },
160
- {
161
- id: "auth.password.recovery.complete",
162
- version: 1,
163
- kind: "command",
164
- channels: ["api", "internal"],
165
- surfacesFrom: "enabled",
166
- input: authPasswordRecoveryCompleteCommand.operation.body,
167
- idempotency: "none",
168
- async run(authService, input) {
169
- return authService.completePasswordRecovery(input);
170
- }
171
- },
172
- {
173
- id: "auth.password.reset",
174
- version: 1,
175
- kind: "command",
176
- channels: ["api", "internal"],
177
- surfacesFrom: "enabled",
178
- input: authPasswordResetCommand.operation.body,
179
- idempotency: "none",
180
- async run(authService, input, context) {
181
- return authService.resetPassword(requireRequestContext(context, "auth.password.reset"), input);
182
- }
183
- },
184
- {
185
- id: "auth.logout",
186
- version: 1,
187
- kind: "command",
188
- channels: ["api", "automation", "internal"],
189
- surfacesFrom: "enabled",
190
- input: emptyInputValidator,
191
- output: authLogoutOutput,
192
- idempotency: "none",
193
- async run(authService, _input, context) {
194
- let logoutResult = {
195
- ok: true,
196
- clearSession: true
197
- };
198
- if (typeof authService.logout === "function") {
199
- logoutResult = await authService.logout(requireRequestContext(context, "auth.logout"));
200
- }
201
- return {
202
- ok: logoutResult?.ok !== false,
203
- clearSession: logoutResult?.clearSession !== false
204
- };
205
- }
206
- },
207
- {
208
- id: "auth.session.read",
209
- version: 1,
210
- kind: "query",
211
- channels: ["api", "internal"],
212
- surfacesFrom: "enabled",
213
- input: emptyInputValidator,
214
- idempotency: "none",
215
- async run(authService, _input, context) {
216
- return authService.authenticateRequest(requireRequestContext(context, "auth.session.read"));
217
- }
218
- }
219
- ]);
220
-
221
- function buildAuthActions({ authService } = {}) {
222
- if (!authService || typeof authService !== "object") {
223
- throw new TypeError("buildAuthActions requires authService.");
224
- }
225
- return Object.freeze(authActionSpecifications.map(({ run, surfacesFrom: _surfaceSource, ...definition }) => Object.freeze({
226
- ...definition,
227
- surfaces: ["*"],
228
- execute(input, context) {
229
- return run(authService, input, context);
230
- }
231
- })));
232
- }
233
-
234
- export { authActionSpecifications, buildAuthActions, requireRequestContext };