@jskit-ai/auth-web 0.2.4 → 0.2.6

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/auth-web",
3
- "version": "0.2.4",
3
+ "version": "0.2.6",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "node --test --test-concurrency=1"
@@ -11,6 +11,7 @@
11
11
  "./server/routes/authRoutes": "./src/server/routes/authRoutes.js",
12
12
  "./server/AuthWebFeature": "./src/server/AuthWebFeature.js",
13
13
  "./server/managedPreviewIdentity": "./src/server/managedPreviewIdentity.js",
14
+ "./server/types": "./src/server/types.js",
14
15
  "./client": "./src/client/index.js",
15
16
  "./client/views/DefaultLoginView": "./src/client/views/DefaultLoginView.vue",
16
17
  "./client/views/DefaultResetPasswordView": "./src/client/views/DefaultResetPasswordView.vue",
@@ -26,10 +27,10 @@
26
27
  "@mdi/js": "^7.4.47"
27
28
  },
28
29
  "peerDependencies": {
29
- "@jskit-ai/auth-core": "0.2.3",
30
- "@jskit-ai/http-runtime": "0.2.3",
31
- "@jskit-ai/kernel": "0.2.3",
32
- "@jskit-ai/shell-web": "0.2.3",
30
+ "@jskit-ai/auth-core": "0.2.4",
31
+ "@jskit-ai/http-runtime": "0.2.4",
32
+ "@jskit-ai/kernel": "0.2.4",
33
+ "@jskit-ai/shell-web": "0.2.4",
33
34
  "@tanstack/vue-query": "^5.90.5",
34
35
  "pinia": "^4.0.3",
35
36
  "vue": "^3.5.44",
@@ -41,8 +42,7 @@
41
42
  "kind": "runtime",
42
43
  "capabilities": {
43
44
  "provides": [
44
- "auth.web",
45
- "auth.web-login"
45
+ "auth.web"
46
46
  ],
47
47
  "requires": [
48
48
  "auth.service",
@@ -88,6 +88,10 @@
88
88
  {
89
89
  "subpath": "./server/managedPreviewIdentity",
90
90
  "summary": "Runs the app-owned managed-preview identity command against JSKIT's development auth routes."
91
+ },
92
+ {
93
+ "subpath": "./server/types",
94
+ "summary": "Type of the auth.web capability, for features that require it."
91
95
  }
92
96
  ],
93
97
  "clientCapabilities": [
@@ -34,14 +34,26 @@ Every application with accounts includes the managed-preview login. It is
34
34
  standard, not optional: adding this pattern adds it, so a managed host's
35
35
  preview can sign its browser in as an existing account without anyone asking
36
36
  for it. Copy the app-owned `tools/preview-identity` executable (keep it
37
- executable) and declare it under `#### Preview identity` in the project's
38
- web-presented Vibe64 `Outputs` target, exactly:
37
+ executable). It passes `runManagedPreviewIdentityCommand` the two facts only
38
+ the preview host knows, as that host documents them:
39
+
40
+ - `protocol`: the protocol id the host's requests carry and the responses
41
+ echo (JSKIT's default is `jskit.preview-identity.command.v1`);
42
+ - `localHostnames`: the hostname patterns, besides loopback, that the host
43
+ serves the preview application on (none by default).
44
+
45
+ It also passes the process environment as `env`, where the host supplies the
46
+ two exchange values per run.
47
+
48
+ Declare the executable to the host in the form the host reads. A host that
49
+ reads the project's web `Outputs` target takes this block, with the same
50
+ protocol id the executable passes:
39
51
 
40
52
  ```markdown
41
53
  #### Preview identity
42
54
 
43
55
  - Command: `tools/preview-identity`
44
- - Protocol: `vibe64.preview-identity.command.v1`
56
+ - Protocol: `<the host's protocol id>`
45
57
  - Identity types: `email` `user-id`
46
58
  - Enabled environment: `AUTH_DEV_BYPASS_ENABLED`
47
59
  - Secret environment: `AUTH_DEV_BYPASS_SECRET`
@@ -52,11 +64,11 @@ The preview host supplies fresh output-run-scoped values for both environment
52
64
  names; users do not set them by hand, and the exchange stays disabled without
53
65
  them. The person using the host chooses which existing accounts the preview may
54
66
  sign in as; the application never creates users for it. JSKIT owns this
55
- executable/library pattern, Vibe64 owns the `Outputs` grammar and runtime
56
- behavior, and Genesis only composes that consumer-owned section as opaque text.
57
- The executable calls the exported managed-preview identity library directly; it
58
- does not require a JSKIT CLI. A project without Genesis or a managed host keeps
59
- the executable; it is inert unless both environment values are present.
67
+ executable/library pattern; the host owns its declaration grammar, its
68
+ protocol id and its runtime behavior. The executable calls the exported
69
+ managed-preview identity library directly; it does not require a JSKIT CLI. A
70
+ project without a managed host keeps the executable; it is inert unless both
71
+ environment values are present.
60
72
 
61
73
  Choose local-auth storage through the installed capability provider. A
62
74
  database-backed application installs `@jskit-ai/auth-provider-local-db-core`,
@@ -69,8 +81,9 @@ a user as a side effect.
69
81
  ## Invariants
70
82
 
71
83
  - Credentials and provider secrets come from environment values.
72
- - An application with accounts ships the executable `tools/preview-identity`
73
- and declares it under `#### Preview identity` in its web `Outputs` target.
84
+ - An application with accounts ships the executable `tools/preview-identity`,
85
+ passes it its preview host's protocol id and hostnames, and declares it to
86
+ that host.
74
87
  - Auth backend selection comes from the installed provider graph, not an
75
88
  `AUTH_LOCAL_BACKEND` environment value.
76
89
  - The selected auth backend and the storage containing the application's users
@@ -107,8 +120,8 @@ Exercise failed and successful login, sign-out, reset, protected navigation,
107
120
  keyboard interaction, warm-cache return navigation, and browser refresh.
108
121
  Open the login route with an existing authenticated session and confirm it
109
122
  returns to the requested screen; repeat signed out and confirm the form remains.
110
- Confirm `tools/preview-identity` is committed as executable and the web
111
- `Outputs` target declares the `#### Preview identity` block above.
123
+ Confirm `tools/preview-identity` is committed as executable, passes the protocol
124
+ id the host's declaration names, and is declared to the host as above.
112
125
 
113
126
  ## Avoid
114
127
 
@@ -2,4 +2,10 @@
2
2
 
3
3
  import { runManagedPreviewIdentityCommand } from "@jskit-ai/auth-web/server/managedPreviewIdentity";
4
4
 
5
- process.exitCode = await runManagedPreviewIdentityCommand();
5
+ // The preview host's protocol id, and the hostnames besides loopback that it
6
+ // serves the application on, as that host documents them.
7
+ process.exitCode = await runManagedPreviewIdentityCommand({
8
+ protocol: "jskit.preview-identity.command.v1",
9
+ localHostnames: [],
10
+ env: process.env
11
+ });
@@ -480,6 +480,22 @@ export function useLoginViewActions({
480
480
  }
481
481
  }
482
482
 
483
+ // A session can start while this page stays open: signed in from another tab,
484
+ // an identity switch, or the page restored from the back-forward cache.
485
+ async function redirectIfSignedIn() {
486
+ if (state.loading.value) {
487
+ return;
488
+ }
489
+ try {
490
+ const session = await refreshSession();
491
+ if (session?.authenticated && typeof window === "object" && window.location) {
492
+ window.location.replace(state.requestedReturnTo.value);
493
+ }
494
+ } catch {
495
+ // Still signed out, or offline: the form stays as it is.
496
+ }
497
+ }
498
+
483
499
  return {
484
500
  submitAuth,
485
501
  requestOtpCode,
@@ -487,6 +503,7 @@ export function useLoginViewActions({
487
503
  oauthProviderButtonLabel,
488
504
  oauthProviderIcon,
489
505
  startOAuthSignIn,
490
- initializeOnMounted
506
+ initializeOnMounted,
507
+ redirectIfSignedIn
491
508
  };
492
509
  }
@@ -0,0 +1,23 @@
1
+ import { onBeforeUnmount, onMounted } from "vue";
2
+
3
+ // Runs recheck whenever the page is shown again: focused, made visible, or
4
+ // restored from the back-forward cache, where nothing mounts again.
5
+ export function useSessionRecheckOnShow(recheck) {
6
+ function recheckWhenShown() {
7
+ if (document.visibilityState === "visible") {
8
+ recheck();
9
+ }
10
+ }
11
+
12
+ onMounted(() => {
13
+ window.addEventListener("focus", recheckWhenShown);
14
+ window.addEventListener("pageshow", recheckWhenShown);
15
+ document.addEventListener("visibilitychange", recheckWhenShown);
16
+ });
17
+
18
+ onBeforeUnmount(() => {
19
+ window.removeEventListener("focus", recheckWhenShown);
20
+ window.removeEventListener("pageshow", recheckWhenShown);
21
+ document.removeEventListener("visibilitychange", recheckWhenShown);
22
+ });
23
+ }
@@ -6,6 +6,7 @@ import { useAuthOAuthLaunchClient } from "./inject.js";
6
6
  import { useLoginViewState } from "../composables/loginView/useLoginViewState.js";
7
7
  import { useLoginViewValidation } from "../composables/loginView/useLoginViewValidation.js";
8
8
  import { useLoginViewActions } from "../composables/loginView/useLoginViewActions.js";
9
+ import { useSessionRecheckOnShow } from "../composables/loginView/useSessionRecheckOnShow.js";
9
10
 
10
11
  function useLoginView() {
11
12
  const { context: placementContext } = useWebPlacementContext();
@@ -26,6 +27,7 @@ function useLoginView() {
26
27
  });
27
28
 
28
29
  onMounted(actions.initializeOnMounted);
30
+ useSessionRecheckOnShow(actions.redirectIfSignedIn);
29
31
 
30
32
  return {
31
33
  authTitle: state.authTitle,
@@ -247,6 +247,7 @@ import { useAuthOAuthLaunchClient } from "../runtime/inject.js";
247
247
  import { useLoginViewState } from "../composables/loginView/useLoginViewState.js";
248
248
  import { useLoginViewValidation } from "../composables/loginView/useLoginViewValidation.js";
249
249
  import { useLoginViewActions } from "../composables/loginView/useLoginViewActions.js";
250
+ import { useSessionRecheckOnShow } from "../composables/loginView/useSessionRecheckOnShow.js";
250
251
  import { useJskitText } from "../i18n.js";
251
252
 
252
253
  const {
@@ -268,6 +269,7 @@ const actions = useLoginViewActions({
268
269
  });
269
270
 
270
271
  onMounted(actions.initializeOnMounted);
272
+ useSessionRecheckOnShow(actions.redirectIfSignedIn);
271
273
 
272
274
  const {
273
275
  authTitle,
@@ -1,13 +1,5 @@
1
- import { resolveDevAuthPolicyFromEnv } from "@jskit-ai/auth-core/server/devAuth";
2
1
  import { defineFeature } from "@jskit-ai/kernel/server/features";
3
- import { AuthController } from "./controllers/AuthController.js";
4
- import { buildRoutes } from "./routes/authRoutes.js";
5
- import { AuthWebService } from "./services/AuthWebService.js";
6
-
7
- function devAuthBootstrapEnabled(env) {
8
- const policy = resolveDevAuthPolicyFromEnv(env);
9
- return policy.enabled && !policy.isProduction;
10
- }
2
+ import { createAuthWeb } from "./authWeb.js";
11
3
 
12
4
  const AuthWebFeature = defineFeature({
13
5
  id: "auth.web",
@@ -20,21 +12,18 @@ const AuthWebFeature = defineFeature({
20
12
  provides: {
21
13
  authWeb: "auth.web"
22
14
  },
15
+ /**
16
+ * @param {object} capabilities
17
+ * @param {import("@jskit-ai/auth-core/server/types").AuthService} capabilities.authService
18
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} capabilities.env
19
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeHttp} capabilities.http
20
+ */
23
21
  setup({ authService, env, http }) {
24
- const service = new AuthWebService({
25
- authService,
26
- devAuthBootstrapEnabled: devAuthBootstrapEnabled(env)
27
- });
28
- const controller = new AuthController({ service });
29
- const routes = buildRoutes(controller, {
30
- includeDevLoginAs: service.isDevLoginAsAvailable()
31
- });
32
- for (const route of routes) {
22
+ const authWeb = createAuthWeb({ authService, env });
23
+ for (const route of authWeb.routes) {
33
24
  http.router.register(route.method, route.path, route, route.handler);
34
25
  }
35
- return {
36
- authWeb: Object.freeze({ controller, routes: Object.freeze(routes), service })
37
- };
26
+ return { authWeb };
38
27
  }
39
28
  });
40
29
 
@@ -0,0 +1,31 @@
1
+ import { isDevAuthBootstrapEnabled, resolveDevAuthPolicyFromEnv } from "@jskit-ai/auth-core/server/devAuth";
2
+ import { AuthController } from "./controllers/AuthController.js";
3
+ import { buildRoutes } from "./routes/authRoutes.js";
4
+ import { AuthWebService } from "./services/AuthWebService.js";
5
+
6
+ /**
7
+ * The auth web routes over the installed auth service: their service,
8
+ * controller and route table. Routes are registered at setup, before the
9
+ * deferred auth service exists, so dev login-as is read from the env with the
10
+ * predicate the auth providers use.
11
+ * @param {object} dependencies
12
+ * @param {import("@jskit-ai/auth-core/server/types").AuthService} dependencies.authService
13
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} dependencies.env
14
+ */
15
+ function createAuthWeb({ authService, env }) {
16
+ const service = new AuthWebService({
17
+ authService,
18
+ devAuthBootstrapEnabled: isDevAuthBootstrapEnabled(resolveDevAuthPolicyFromEnv(env))
19
+ });
20
+ const controller = new AuthController({ service });
21
+ const routes = buildRoutes(controller, {
22
+ includeDevLoginAs: service.isDevLoginAsAvailable()
23
+ });
24
+ return Object.freeze({
25
+ controller,
26
+ routes: Object.freeze(routes),
27
+ service
28
+ });
29
+ }
30
+
31
+ export { createAuthWeb };
@@ -2,13 +2,11 @@ import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
2
2
  import { normalizeAuthDenied } from "@jskit-ai/auth-core/shared/authDenied";
3
3
  import { AUTH_TEXTS, authMessageFields, authText } from "@jskit-ai/auth-core/server/authTexts";
4
4
  import { AUTH_ACTION_IDS } from "../constants/authActionIds.js";
5
- import { AuthWebService } from "../services/AuthWebService.js";
6
5
 
6
+ /** The auth routes' handlers over AuthWebService. */
7
7
  class AuthController {
8
- constructor({ service } = {}) {
9
- if (!service) {
10
- throw new Error("AuthController requires AuthWebService instance.");
11
- }
8
+ /** @param {{ service: import("../services/AuthWebService.js").AuthWebService }} dependencies */
9
+ constructor({ service }) {
12
10
  this.service = service;
13
11
  }
14
12
 
@@ -129,16 +127,16 @@ class AuthController {
129
127
  });
130
128
  }
131
129
 
130
+ /**
131
+ * @param {import("fastify").FastifyRequest} request
132
+ * @param {import("fastify").FastifyReply} reply
133
+ */
132
134
  async logout(request, reply) {
133
135
  let clearSession = true;
134
136
  try {
135
- const result = await this.service.logout(request);
136
- clearSession = result?.clearSession !== false;
137
+ ({ clearSession } = await this.service.logout(request));
137
138
  } catch (error) {
138
- if (request?.log && typeof request.log.warn === "function") {
139
- request.log.warn({ err: error }, "Auth logout fallback: clearing local session cookies.");
140
- }
141
- clearSession = true;
139
+ request.log.warn({ err: error }, "Auth logout fallback: clearing local session cookies.");
142
140
  }
143
141
 
144
142
  if (clearSession) {
@@ -220,14 +218,4 @@ class AuthController {
220
218
  }
221
219
  }
222
220
 
223
- function createController({ service, authService } = {}) {
224
- if (!service) {
225
- if (!authService) {
226
- throw new Error("createController requires either service or authService.");
227
- }
228
- service = new AuthWebService({ authService });
229
- }
230
- return new AuthController({ service });
231
- }
232
-
233
- export { AuthController, AUTH_ACTION_IDS, createController };
221
+ export { AuthController, AUTH_ACTION_IDS };
@@ -1,28 +1,36 @@
1
- import { DEV_AUTH_SECRET_HEADER } from "@jskit-ai/auth-core/server/devAuth";
1
+ import {
2
+ DEV_AUTH_SECRET_HEADER,
3
+ isDevAuthBootstrapEnabled,
4
+ resolveDevAuthPolicyFromEnv
5
+ } from "@jskit-ai/auth-core/server/devAuth";
2
6
  import { AUTH_PATHS } from "@jskit-ai/auth-core/shared/authPaths";
3
7
 
4
- const MANAGED_PREVIEW_IDENTITY_PROTOCOL = "vibe64.preview-identity.command.v1";
5
- const MANAGED_PREVIEW_IDENTITY_ENABLED_ENV = "AUTH_DEV_BYPASS_ENABLED";
6
- const MANAGED_PREVIEW_IDENTITY_SECRET_ENV = "AUTH_DEV_BYPASS_SECRET";
8
+ /**
9
+ * The protocol id the command speaks when the application names none. A preview
10
+ * host that names its own id is configured through the command's `protocol`
11
+ * option.
12
+ */
13
+ const DEFAULT_PREVIEW_IDENTITY_PROTOCOL = "jskit.preview-identity.command.v1";
7
14
  const MAX_MESSAGE_BYTES = 64 * 1024;
8
15
 
9
16
  function commandError(message, code = "jskit_managed_preview_identity_failed", details = {}) {
10
17
  return Object.assign(new Error(message), { code, ...details });
11
18
  }
12
19
 
13
- function response(requestId, values) {
20
+ function response(protocol, requestId, values) {
14
21
  return {
15
- protocol: MANAGED_PREVIEW_IDENTITY_PROTOCOL,
22
+ protocol,
16
23
  requestId: String(requestId || ""),
17
24
  ...values
18
25
  };
19
26
  }
20
27
 
21
- function failure(requestId, error) {
22
- return response(requestId, {
28
+ function failure(protocol, requestId, error) {
29
+ return response(protocol, requestId, {
23
30
  code: String(error?.code || "jskit_managed_preview_identity_failed"),
24
31
  error: String(error?.message || error || "Managed preview identity failed."),
25
32
  ok: false,
33
+ // readable-check: allow setter-seam - not a slot: setCookie is the preview identity protocol's list of Set-Cookie headers
26
34
  setCookie: Array.isArray(error?.setCookie) ? error.setCookie : [],
27
35
  signedOut: error?.signedOut === true,
28
36
  statusCode: Number.isInteger(Number(error?.statusCode)) ? Number(error.statusCode) : 400
@@ -61,7 +69,11 @@ async function readCommandInput(stream) {
61
69
  }
62
70
  }
63
71
 
64
- function localTargetOrigin(value) {
72
+ /**
73
+ * @param {unknown} value
74
+ * @param {RegExp[]} localHostnames
75
+ */
76
+ function localTargetOrigin(value, localHostnames) {
65
77
  let target;
66
78
  try {
67
79
  target = new URL(String(value || ""));
@@ -76,7 +88,7 @@ function localTargetOrigin(value) {
76
88
  hostname.endsWith(".localhost") ||
77
89
  /^127(?:\.\d{1,3}){3}$/u.test(hostname) ||
78
90
  hostname === "::1" ||
79
- /^vibe64-launch-[a-f0-9]{12}$/u.test(hostname);
91
+ localHostnames.some((pattern) => pattern.test(hostname));
80
92
  if (target.protocol !== "http:" || !local) {
81
93
  throw commandError(
82
94
  "Managed preview identity target must be a local application.",
@@ -86,7 +98,11 @@ function localTargetOrigin(value) {
86
98
  return target.origin;
87
99
  }
88
100
 
89
- function normalizeRequest(value) {
101
+ /**
102
+ * @param {unknown} value
103
+ * @param {{ protocol: string, localHostnames: RegExp[] }} host
104
+ */
105
+ function normalizeRequest(value, { protocol, localHostnames }) {
90
106
  if (!value || typeof value !== "object" || Array.isArray(value)) {
91
107
  throw commandError(
92
108
  "Managed preview identity request must be an object.",
@@ -95,7 +111,7 @@ function normalizeRequest(value) {
95
111
  }
96
112
  const requestId = String(value.requestId || "").trim();
97
113
  const operation = String(value.operation || "").trim();
98
- if (value.protocol !== MANAGED_PREVIEW_IDENTITY_PROTOCOL || !requestId) {
114
+ if (value.protocol !== protocol || !requestId) {
99
115
  throw commandError(
100
116
  "Managed preview identity request protocol is invalid.",
101
117
  "jskit_managed_preview_identity_protocol_invalid"
@@ -111,7 +127,7 @@ function normalizeRequest(value) {
111
127
  operation,
112
128
  requestId,
113
129
  subject: value.subject,
114
- targetOrigin: localTargetOrigin(value.target?.origin || value.target?.href)
130
+ targetOrigin: localTargetOrigin(value.target?.origin || value.target?.href, localHostnames)
115
131
  };
116
132
  }
117
133
 
@@ -132,14 +148,6 @@ function identityFromSubject(subject) {
132
148
  );
133
149
  }
134
150
 
135
- function responseCookies(fetchResponse) {
136
- if (typeof fetchResponse?.headers?.getSetCookie === "function") {
137
- return fetchResponse.headers.getSetCookie().map(String).filter(Boolean);
138
- }
139
- const value = String(fetchResponse?.headers?.get?.("set-cookie") || "").trim();
140
- return value ? [value] : [];
141
- }
142
-
143
151
  function cookieHeader(setCookie) {
144
152
  const cookies = new Map();
145
153
  for (const entry of setCookie) {
@@ -152,8 +160,9 @@ function cookieHeader(setCookie) {
152
160
  return [...cookies.values()].join("; ");
153
161
  }
154
162
 
163
+ /** @param {Response} fetchResponse */
155
164
  async function responsePayload(fetchResponse) {
156
- const text = fetchResponse?.body
165
+ const text = fetchResponse.body
157
166
  ? await readBoundedStream(fetchResponse.body, "Managed preview identity response")
158
167
  : "";
159
168
  if (!text) {
@@ -167,6 +176,11 @@ async function responsePayload(fetchResponse) {
167
176
  }
168
177
  }
169
178
 
179
+ /**
180
+ * @param {object | null} payload The response's JSON body, when it has one.
181
+ * @param {Response} fetchResponse
182
+ * @param {object} [details]
183
+ */
170
184
  function rejected(payload, fetchResponse, details = {}) {
171
185
  const fieldErrors = payload?.details?.fieldErrors || payload?.fieldErrors || {};
172
186
  const fieldMessage = Object.values(
@@ -183,7 +197,7 @@ function rejected(payload, fetchResponse, details = {}) {
183
197
  "Managed preview identity exchange failed."
184
198
  ),
185
199
  String(firstError?.code || payload?.code || "jskit_managed_preview_identity_rejected"),
186
- { statusCode: Number(fetchResponse?.status || 502), ...details }
200
+ { statusCode: Number(fetchResponse.status || 502), ...details }
187
201
  );
188
202
  }
189
203
 
@@ -214,7 +228,7 @@ async function bootstrapSession(fetchImpl, targetOrigin) {
214
228
  redirect: "manual"
215
229
  });
216
230
  const payload = await responsePayload(fetchResponse);
217
- const setCookie = responseCookies(fetchResponse);
231
+ const setCookie = fetchResponse.headers.getSetCookie();
218
232
  if (!fetchResponse.ok) {
219
233
  throw rejected(payload, fetchResponse, { setCookie });
220
234
  }
@@ -226,6 +240,7 @@ async function bootstrapSession(fetchImpl, targetOrigin) {
226
240
  { setCookie, statusCode: 502 }
227
241
  );
228
242
  }
243
+ // readable-check: allow setter-seam - not a slot: setCookie is the preview identity protocol's list of Set-Cookie headers
229
244
  return { csrfToken, setCookie };
230
245
  }
231
246
 
@@ -235,10 +250,11 @@ async function logout(fetchImpl, targetOrigin, session) {
235
250
  "csrf-token": session.csrfToken
236
251
  });
237
252
  const payload = await responsePayload(fetchResponse);
238
- const setCookie = [...session.setCookie, ...responseCookies(fetchResponse)];
253
+ const setCookie = [...session.setCookie, ...fetchResponse.headers.getSetCookie()];
239
254
  if (!fetchResponse.ok || payload?.ok !== true) {
240
255
  throw rejected(payload, fetchResponse, { setCookie, signedOut: false });
241
256
  }
257
+ // readable-check: allow setter-seam - not a slot: setCookie is the preview identity protocol's list of Set-Cookie headers
242
258
  return { csrfToken: session.csrfToken, setCookie };
243
259
  }
244
260
 
@@ -249,7 +265,7 @@ async function login(fetchImpl, targetOrigin, identity, secret, session) {
249
265
  [DEV_AUTH_SECRET_HEADER]: secret
250
266
  });
251
267
  const payload = await responsePayload(fetchResponse);
252
- const setCookie = [...session.setCookie, ...responseCookies(fetchResponse)];
268
+ const setCookie = [...session.setCookie, ...fetchResponse.headers.getSetCookie()];
253
269
  if (!fetchResponse.ok || payload?.ok !== true) {
254
270
  throw rejected(payload, fetchResponse, { setCookie, signedOut: true });
255
271
  }
@@ -260,18 +276,37 @@ async function login(fetchImpl, targetOrigin, identity, secret, session) {
260
276
  userId: String(payload.userId || identity.userId || "").trim(),
261
277
  username: String(payload.username || "").trim()
262
278
  },
279
+ // readable-check: allow setter-seam - not a slot: setCookie is the preview identity protocol's list of Set-Cookie headers
263
280
  setCookie
264
281
  };
265
282
  }
266
283
 
284
+ /**
285
+ * Answers one preview identity request: signs the preview browser out, and for
286
+ * `login-as` back in as an existing application user, through the development
287
+ * exchange. The preview host names the protocol id and any hostnames, besides
288
+ * loopback, that it serves the application on.
289
+ * @param {Record<string, any>} value The command's request, which is validated here.
290
+ * @param {object} options
291
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} options.env The application's environment, such as `process.env`.
292
+ * @param {typeof fetch} [options.fetchImpl]
293
+ * @param {string} [options.protocol] The protocol id requests carry and responses echo.
294
+ * @param {RegExp[]} [options.localHostnames] Hostnames, besides loopback, the application is served on.
295
+ */
267
296
  async function executeManagedPreviewIdentityRequest(value, {
268
- env = process.env,
269
- fetchImpl = globalThis.fetch
270
- } = {}) {
297
+ env,
298
+ fetchImpl = globalThis.fetch,
299
+ protocol = DEFAULT_PREVIEW_IDENTITY_PROTOCOL,
300
+ localHostnames = []
301
+ }) {
302
+ if (!env) {
303
+ throw new TypeError("executeManagedPreviewIdentityRequest requires the application's environment, such as process.env.");
304
+ }
271
305
  let requestId = String(value?.requestId || "").trim();
272
306
  try {
273
- const request = normalizeRequest(value);
307
+ const request = normalizeRequest(value, { protocol, localHostnames });
274
308
  requestId = request.requestId;
309
+ // readable-check: allow method-probe - input validation: the fetch an application passes
275
310
  if (typeof fetchImpl !== "function") {
276
311
  throw commandError(
277
312
  "Managed preview identity requires fetch support.",
@@ -279,15 +314,15 @@ async function executeManagedPreviewIdentityRequest(value, {
279
314
  { statusCode: 500 }
280
315
  );
281
316
  }
282
- if (String(env[MANAGED_PREVIEW_IDENTITY_ENABLED_ENV] || "").trim().toLowerCase() !== "true") {
317
+ const devAuth = resolveDevAuthPolicyFromEnv(env);
318
+ if (!isDevAuthBootstrapEnabled(devAuth)) {
283
319
  throw commandError(
284
320
  "Managed preview identity is not enabled.",
285
321
  "jskit_managed_preview_identity_disabled",
286
322
  { statusCode: 403 }
287
323
  );
288
324
  }
289
- const secret = String(env[MANAGED_PREVIEW_IDENTITY_SECRET_ENV] || "").trim();
290
- if (!/^[a-f0-9]{64}$/u.test(secret)) {
325
+ if (!devAuth.secret) {
291
326
  throw commandError(
292
327
  "Managed preview identity secret is unavailable.",
293
328
  "jskit_managed_preview_identity_secret_missing",
@@ -300,45 +335,59 @@ async function executeManagedPreviewIdentityRequest(value, {
300
335
  const session = await bootstrapSession(fetchImpl, request.targetOrigin);
301
336
  const signedOutSession = await logout(fetchImpl, request.targetOrigin, session);
302
337
  if (request.operation === "logout") {
303
- return response(requestId, {
338
+ return response(protocol, requestId, {
304
339
  identity: null,
305
340
  ok: true,
341
+ // readable-check: allow setter-seam - not a slot: setCookie is the preview identity protocol's list of Set-Cookie headers
306
342
  setCookie: signedOutSession.setCookie,
307
343
  signedOut: true
308
344
  });
309
345
  }
310
- const result = await login(fetchImpl, request.targetOrigin, identity, secret, signedOutSession);
311
- return response(requestId, {
346
+ const result = await login(fetchImpl, request.targetOrigin, identity, devAuth.secret, signedOutSession);
347
+ return response(protocol, requestId, {
312
348
  identity: result.identity,
313
349
  ok: true,
350
+ // readable-check: allow setter-seam - not a slot: setCookie is the preview identity protocol's list of Set-Cookie headers
314
351
  setCookie: result.setCookie,
315
352
  signedOut: false
316
353
  });
317
354
  } catch (error) {
318
- return failure(requestId, error);
355
+ return failure(protocol, requestId, error);
319
356
  }
320
357
  }
321
358
 
359
+ /**
360
+ * Reads one request from stdin and writes its response to stdout.
361
+ * @param {object} options
362
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} options.env The application's environment, such as `process.env`.
363
+ * @param {typeof fetch} [options.fetchImpl]
364
+ * @param {AsyncIterable<string | Buffer>} [options.stdin]
365
+ * @param {{ write(text: string): unknown }} [options.stdout]
366
+ * @param {string} [options.protocol] The protocol id requests carry and responses echo.
367
+ * @param {RegExp[]} [options.localHostnames] Hostnames, besides loopback, the application is served on.
368
+ */
322
369
  async function runManagedPreviewIdentityCommand({
323
- env = process.env,
370
+ env,
324
371
  fetchImpl = globalThis.fetch,
325
372
  stdin = process.stdin,
326
- stdout = process.stdout
327
- } = {}) {
373
+ stdout = process.stdout,
374
+ protocol = DEFAULT_PREVIEW_IDENTITY_PROTOCOL,
375
+ localHostnames = []
376
+ }) {
328
377
  let request;
329
378
  try {
330
379
  request = await readCommandInput(stdin);
331
380
  } catch (error) {
332
- stdout.write(`${JSON.stringify(failure("", error))}\n`);
381
+ stdout.write(`${JSON.stringify(failure(protocol, "", error))}\n`);
333
382
  return 0;
334
383
  }
335
- const result = await executeManagedPreviewIdentityRequest(request, { env, fetchImpl });
384
+ const result = await executeManagedPreviewIdentityRequest(request, { env, fetchImpl, protocol, localHostnames });
336
385
  stdout.write(`${JSON.stringify(result)}\n`);
337
386
  return 0;
338
387
  }
339
388
 
340
389
  export {
341
- MANAGED_PREVIEW_IDENTITY_PROTOCOL,
390
+ DEFAULT_PREVIEW_IDENTITY_PROTOCOL,
342
391
  executeManagedPreviewIdentityRequest,
343
392
  runManagedPreviewIdentityCommand
344
393
  };