@jskit-ai/auth-web 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/auth-web",
3
- "version": "0.2.3",
3
+ "version": "0.2.5",
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.2",
30
- "@jskit-ai/http-runtime": "0.2.2",
31
- "@jskit-ai/kernel": "0.2.2",
32
- "@jskit-ai/shell-web": "0.2.2",
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
  };
@@ -16,13 +16,11 @@ import {
16
16
  } from "@jskit-ai/auth-core/shared/commands";
17
17
  import { AUTH_PATHS } from "@jskit-ai/auth-core/shared/authPaths";
18
18
 
19
+ /**
20
+ * @param {import("../controllers/AuthController.js").AuthController} controller
21
+ * @param {{ includeDevLoginAs?: boolean }} [options]
22
+ */
19
23
  function buildRoutes(controller, { includeDevLoginAs = false } = {}) {
20
- if (!controller) {
21
- throw new Error("Auth routes require a controller instance.");
22
- }
23
-
24
- const handler = (methodName) => controller[methodName].bind(controller);
25
-
26
24
  return [
27
25
  {
28
26
  path: AUTH_PATHS.REGISTER,
@@ -43,7 +41,7 @@ function buildRoutes(controller, { includeDevLoginAs = false } = {}) {
43
41
  max: 10,
44
42
  timeWindow: "1 minute"
45
43
  },
46
- handler: handler("register")
44
+ handler: (request, reply) => controller.register(request, reply)
47
45
  },
48
46
  {
49
47
  path: AUTH_PATHS.REGISTER_CONFIRMATION_RESEND,
@@ -64,7 +62,7 @@ function buildRoutes(controller, { includeDevLoginAs = false } = {}) {
64
62
  max: 5,
65
63
  timeWindow: "1 minute"
66
64
  },
67
- handler: handler("resendRegisterConfirmation")
65
+ handler: (request, reply) => controller.resendRegisterConfirmation(request, reply)
68
66
  },
69
67
  {
70
68
  path: AUTH_PATHS.LOGIN,
@@ -85,7 +83,7 @@ function buildRoutes(controller, { includeDevLoginAs = false } = {}) {
85
83
  max: 10,
86
84
  timeWindow: "1 minute"
87
85
  },
88
- handler: handler("login")
86
+ handler: (request, reply) => controller.login(request, reply)
89
87
  },
90
88
  {
91
89
  path: AUTH_PATHS.LOGIN_OTP_REQUEST,
@@ -106,7 +104,7 @@ function buildRoutes(controller, { includeDevLoginAs = false } = {}) {
106
104
  max: 10,
107
105
  timeWindow: "1 minute"
108
106
  },
109
- handler: handler("requestOtpLogin")
107
+ handler: (request, reply) => controller.requestOtpLogin(request, reply)
110
108
  },
111
109
  {
112
110
  path: AUTH_PATHS.LOGIN_OTP_VERIFY,
@@ -127,7 +125,7 @@ function buildRoutes(controller, { includeDevLoginAs = false } = {}) {
127
125
  max: 10,
128
126
  timeWindow: "1 minute"
129
127
  },
130
- handler: handler("verifyOtpLogin")
128
+ handler: (request, reply) => controller.verifyOtpLogin(request, reply)
131
129
  },
132
130
  {
133
131
  path: AUTH_PATHS.OAUTH_START_TEMPLATE,
@@ -150,7 +148,7 @@ function buildRoutes(controller, { includeDevLoginAs = false } = {}) {
150
148
  max: 20,
151
149
  timeWindow: "1 minute"
152
150
  },
153
- handler: handler("oauthStart")
151
+ handler: (request, reply) => controller.oauthStart(request, reply)
154
152
  },
155
153
  {
156
154
  path: AUTH_PATHS.OAUTH_COMPLETE,
@@ -171,7 +169,7 @@ function buildRoutes(controller, { includeDevLoginAs = false } = {}) {
171
169
  max: 20,
172
170
  timeWindow: "1 minute"
173
171
  },
174
- handler: handler("oauthComplete")
172
+ handler: (request, reply) => controller.oauthComplete(request, reply)
175
173
  },
176
174
  ...(includeDevLoginAs ? [{
177
175
  path: AUTH_PATHS.DEV_LOGIN_AS,
@@ -192,7 +190,7 @@ function buildRoutes(controller, { includeDevLoginAs = false } = {}) {
192
190
  max: 30,
193
191
  timeWindow: "1 minute"
194
192
  },
195
- handler: handler("devLoginAs")
193
+ handler: (request, reply) => controller.devLoginAs(request, reply)
196
194
  }] : []),
197
195
  {
198
196
  path: AUTH_PATHS.PASSWORD_FORGOT,
@@ -213,7 +211,7 @@ function buildRoutes(controller, { includeDevLoginAs = false } = {}) {
213
211
  max: 5,
214
212
  timeWindow: "1 minute"
215
213
  },
216
- handler: handler("requestPasswordReset")
214
+ handler: (request, reply) => controller.requestPasswordReset(request, reply)
217
215
  },
218
216
  {
219
217
  path: AUTH_PATHS.PASSWORD_RECOVERY,
@@ -234,7 +232,7 @@ function buildRoutes(controller, { includeDevLoginAs = false } = {}) {
234
232
  max: 20,
235
233
  timeWindow: "1 minute"
236
234
  },
237
- handler: handler("completePasswordRecovery")
235
+ handler: (request, reply) => controller.completePasswordRecovery(request, reply)
238
236
  },
239
237
  {
240
238
  path: AUTH_PATHS.PASSWORD_RESET,
@@ -255,7 +253,7 @@ function buildRoutes(controller, { includeDevLoginAs = false } = {}) {
255
253
  max: 20,
256
254
  timeWindow: "1 minute"
257
255
  },
258
- handler: handler("resetPassword")
256
+ handler: (request, reply) => controller.resetPassword(request, reply)
259
257
  },
260
258
  {
261
259
  path: AUTH_PATHS.LOGOUT,
@@ -268,7 +266,7 @@ function buildRoutes(controller, { includeDevLoginAs = false } = {}) {
268
266
  responses: withStandardErrorResponses({
269
267
  200: authLogoutCommand.operation.response
270
268
  }),
271
- handler: handler("logout")
269
+ handler: (request, reply) => controller.logout(request, reply)
272
270
  },
273
271
  {
274
272
  path: AUTH_PATHS.SESSION,
@@ -282,7 +280,7 @@ function buildRoutes(controller, { includeDevLoginAs = false } = {}) {
282
280
  200: authSessionReadCommand.operation.response,
283
281
  503: authSessionReadCommand.operation.unavailableResponse
284
282
  }),
285
- handler: handler("session")
283
+ handler: (request, reply) => controller.session(request, reply)
286
284
  }
287
285
  ];
288
286
  }
@@ -1,14 +1,19 @@
1
1
  import { normalizeAuthCapabilities } from "@jskit-ai/auth-core/shared/authCapabilities";
2
2
  import { AUTH_ACTION_IDS } from "../constants/authActionIds.js";
3
3
 
4
+ /**
5
+ * The auth routes' service: it runs the auth actions for a request and
6
+ * writes the installed auth service's cookies.
7
+ */
4
8
  class AuthWebService {
5
- constructor({ authService, devAuthBootstrapEnabled } = {}) {
6
- if (!authService || typeof authService !== "object") {
7
- throw new Error("authService is required.");
8
- }
9
+ /**
10
+ * @param {object} dependencies
11
+ * @param {import("@jskit-ai/auth-core/server/types").AuthService} dependencies.authService
12
+ * @param {boolean} dependencies.devAuthBootstrapEnabled Whether dev login-as is offered.
13
+ */
14
+ constructor({ authService, devAuthBootstrapEnabled }) {
9
15
  this.authService = authService;
10
- this.devAuthBootstrapEnabled =
11
- typeof devAuthBootstrapEnabled === "boolean" ? devAuthBootstrapEnabled : null;
16
+ this.devAuthBootstrapEnabled = devAuthBootstrapEnabled;
12
17
  }
13
18
 
14
19
  static get actionIds() {
@@ -71,18 +76,8 @@ class AuthWebService {
71
76
  });
72
77
  }
73
78
 
74
- resolveAuthService() {
75
- return this.authService;
76
- }
77
-
78
79
  isDevLoginAsAvailable() {
79
- if (this.devAuthBootstrapEnabled != null) {
80
- return this.devAuthBootstrapEnabled === true;
81
- }
82
- const authService = this.resolveAuthService();
83
- return typeof authService?.isDevAuthBootstrapEnabled === "function"
84
- ? authService.isDevAuthBootstrapEnabled()
85
- : false;
80
+ return this.devAuthBootstrapEnabled;
86
81
  }
87
82
 
88
83
  async logout(request) {
@@ -120,21 +115,25 @@ class AuthWebService {
120
115
 
121
116
  writeSessionCookies(reply, session) {
122
117
  if (session && reply) {
123
- this.resolveAuthService().writeSessionCookies(reply, session);
118
+ this.authService.writeSessionCookies(reply, session);
124
119
  }
125
120
  }
126
121
 
127
- // Providers that bind an OAuth attempt to the browser (state, nonce, PKCE)
128
- // keep it in their own short-lived cookie; others need no hook.
122
+ /**
123
+ * Providers that bind an OAuth attempt to the browser (state, nonce, PKCE)
124
+ * keep it in their own short-lived cookie; others need no hook.
125
+ */
129
126
  writeOAuthStartCookies(reply, result) {
130
- const authService = this.resolveAuthService();
127
+ const { authService } = this;
128
+ // readable-check: allow method-probe - optional operation: writeOAuthStartCookies is an optional auth.service operation
131
129
  if (reply && typeof authService.writeOAuthStartCookies === "function") {
132
130
  authService.writeOAuthStartCookies(reply, result);
133
131
  }
134
132
  }
135
133
 
136
134
  clearOAuthStartCookies(reply) {
137
- const authService = this.resolveAuthService();
135
+ const { authService } = this;
136
+ // readable-check: allow method-probe - optional operation: clearOAuthStartCookies is an optional auth.service operation
138
137
  if (reply && typeof authService.clearOAuthStartCookies === "function") {
139
138
  authService.clearOAuthStartCookies(reply);
140
139
  }
@@ -142,51 +141,17 @@ class AuthWebService {
142
141
 
143
142
  clearSessionCookies(reply) {
144
143
  if (reply) {
145
- this.resolveAuthService().clearSessionCookies(reply);
144
+ this.authService.clearSessionCookies(reply);
146
145
  }
147
146
  }
148
147
 
149
148
  getOAuthProviderCatalogPayload() {
150
- const authService = this.resolveAuthService();
151
- if (typeof authService.getCapabilities === "function") {
152
- const capabilities = normalizeAuthCapabilities(authService.getCapabilities());
153
- const oauth = capabilities.features.oauthLogin;
154
- return {
155
- authCapabilities: capabilities,
156
- oauthProviders: oauth.enabled ? oauth.providers : [],
157
- oauthDefaultProvider: oauth.enabled ? oauth.defaultProvider : null
158
- };
159
- }
160
- const catalog =
161
- typeof authService.getOAuthProviderCatalog === "function"
162
- ? authService.getOAuthProviderCatalog()
163
- : null;
164
- const providers = Array.isArray(catalog?.providers)
165
- ? catalog.providers
166
- .map((provider) => ({
167
- id: String(provider?.id || "").trim().toLowerCase(),
168
- label: String(provider?.label || "").trim()
169
- }))
170
- .filter((provider) => provider.id && provider.label)
171
- : [];
172
- const defaultProvider = String(catalog?.defaultProvider || "").trim().toLowerCase();
173
- const normalizedDefaultProvider = providers.some((provider) => provider.id === defaultProvider)
174
- ? defaultProvider
175
- : null;
176
- const fallbackCapabilities = normalizeAuthCapabilities({
177
- features: {
178
- oauthLogin: {
179
- enabled: providers.length > 0,
180
- providers,
181
- defaultProvider: normalizedDefaultProvider
182
- }
183
- }
184
- });
185
-
149
+ const capabilities = normalizeAuthCapabilities(this.authService.getCapabilities());
150
+ const oauth = capabilities.features.oauthLogin;
186
151
  return {
187
- authCapabilities: fallbackCapabilities,
188
- oauthProviders: providers,
189
- oauthDefaultProvider: normalizedDefaultProvider
152
+ authCapabilities: capabilities,
153
+ oauthProviders: oauth.enabled ? oauth.providers : [],
154
+ oauthDefaultProvider: oauth.enabled ? oauth.defaultProvider : null
190
155
  };
191
156
  }
192
157
  }
@@ -0,0 +1,5 @@
1
+ // The type of the `auth.web` capability, for features that require it.
2
+
3
+ /** @typedef {ReturnType<typeof import("./authWeb.js").createAuthWeb>} AuthWeb */
4
+
5
+ export {};
@@ -93,6 +93,52 @@ for (const authenticated of [true, false]) {
93
93
  });
94
94
  }
95
95
 
96
+ test("an open sign-in page forwards once a session starts elsewhere", async (t) => {
97
+ const state = createMinimalLoginViewState("/w/acme/bookings?date=2026-09-16");
98
+ const destinations = [];
99
+ const originalWindow = globalThis.window;
100
+ globalThis.window = {
101
+ location: {
102
+ href: "https://example.com/auth/login",
103
+ replace: (path) => destinations.push(path)
104
+ }
105
+ };
106
+ t.after(() => {
107
+ if (originalWindow === undefined) delete globalThis.window;
108
+ else globalThis.window = originalWindow;
109
+ clearAuthCsrfTokenCache();
110
+ });
111
+ const sessions = [
112
+ () => createJsonResponse({ authenticated: false, csrfToken: "csrf-signed-out" }),
113
+ () => {
114
+ throw new TypeError("Failed to fetch");
115
+ },
116
+ () => createJsonResponse({ authenticated: true, csrfToken: "csrf-signed-in" })
117
+ ];
118
+ const fetch = t.mock.method(globalThis, "fetch", async () => sessions.shift()());
119
+ const actions = useLoginViewActions({
120
+ state,
121
+ validation: {},
122
+ queryClient: {
123
+ fetchQuery: ({ queryFn }) => queryFn()
124
+ },
125
+ errorRuntime: { report: (entry) => assert.fail(entry.message) }
126
+ });
127
+
128
+ await actions.redirectIfSignedIn();
129
+ await actions.redirectIfSignedIn();
130
+ assert.deepEqual(destinations, [], "a signed-out or offline check keeps the form");
131
+
132
+ state.loading.value = true;
133
+ await actions.redirectIfSignedIn();
134
+ assert.equal(fetch.mock.callCount(), 2, "no check runs while a sign-in is in progress");
135
+
136
+ state.loading.value = false;
137
+ await actions.redirectIfSignedIn();
138
+ assert.deepEqual(destinations, [state.requestedReturnTo.value]);
139
+ assert.equal(state.errorMessage.value, "");
140
+ });
141
+
96
142
  test("useLoginViewActions preserves the intended destination when starting OAuth sign-in", () => {
97
143
  const state = createMinimalLoginViewState("/w/acme/workouts/2026-05-07?tab=chart");
98
144
  const assignedTargets = [];
@@ -3,11 +3,13 @@ import { readFileSync, statSync } from "node:fs";
3
3
  import test from "node:test";
4
4
 
5
5
  import {
6
- MANAGED_PREVIEW_IDENTITY_PROTOCOL,
6
+ DEFAULT_PREVIEW_IDENTITY_PROTOCOL,
7
7
  executeManagedPreviewIdentityRequest
8
8
  } from "../src/server/managedPreviewIdentity.js";
9
9
 
10
10
  const SECRET = "a".repeat(64);
11
+ const HOST_PROTOCOL = "example-host.preview-identity.command.v1";
12
+ const HOST_OPTIONS = Object.freeze({ protocol: HOST_PROTOCOL, localHostnames: [/^preview-[a-f0-9]{12}$/u] });
11
13
 
12
14
  function jsonResponse(payload, { cookie = "", status = 200 } = {}) {
13
15
  return new Response(JSON.stringify(payload), {
@@ -19,22 +21,35 @@ function jsonResponse(payload, { cookie = "", status = 200 } = {}) {
19
21
  });
20
22
  }
21
23
 
22
- test("managed preview identity uses only the Vibe64-owned command protocol", async () => {
23
- assert.equal(MANAGED_PREVIEW_IDENTITY_PROTOCOL, "vibe64.preview-identity.command.v1");
24
+ test("managed preview identity answers only the protocol id its host names", async () => {
25
+ assert.equal(DEFAULT_PREVIEW_IDENTITY_PROTOCOL, "jskit.preview-identity.command.v1");
24
26
 
25
27
  const result = await executeManagedPreviewIdentityRequest({
26
28
  operation: "logout",
27
- protocol: "genesis.preview-identity.command.v1",
29
+ protocol: "retired.preview-identity.command.v1",
28
30
  requestId: "retired-protocol",
29
31
  target: { origin: "http://localhost:3000" }
30
32
  }, {
33
+ ...HOST_OPTIONS,
31
34
  env: {},
32
35
  fetchImpl: async () => assert.fail("fetch must not run")
33
36
  });
34
37
 
35
38
  assert.equal(result.ok, false);
36
- assert.equal(result.protocol, MANAGED_PREVIEW_IDENTITY_PROTOCOL);
39
+ assert.equal(result.protocol, HOST_PROTOCOL);
37
40
  assert.equal(result.code, "jskit_managed_preview_identity_protocol_invalid");
41
+
42
+ const unnamed = await executeManagedPreviewIdentityRequest({
43
+ operation: "logout",
44
+ protocol: HOST_PROTOCOL,
45
+ requestId: "default-protocol",
46
+ target: { origin: "http://localhost:3000" }
47
+ }, {
48
+ env: {},
49
+ fetchImpl: async () => assert.fail("fetch must not run")
50
+ });
51
+ assert.equal(unnamed.protocol, DEFAULT_PREVIEW_IDENTITY_PROTOCOL);
52
+ assert.equal(unnamed.code, "jskit_managed_preview_identity_protocol_invalid");
38
53
  });
39
54
 
40
55
  test("managed preview identity signs out before selecting an existing application user", async () => {
@@ -51,14 +66,15 @@ test("managed preview identity signs out before selecting an existing applicatio
51
66
  ];
52
67
  const result = await executeManagedPreviewIdentityRequest({
53
68
  operation: "login-as",
54
- protocol: MANAGED_PREVIEW_IDENTITY_PROTOCOL,
69
+ protocol: HOST_PROTOCOL,
55
70
  requestId: "request-1",
56
71
  subject: {
57
72
  kind: "selector",
58
73
  selector: { type: "email", value: "ada@example.com" }
59
74
  },
60
- target: { origin: "http://vibe64-launch-deadbeefcafe" }
75
+ target: { origin: "http://preview-deadbeefcafe" }
61
76
  }, {
77
+ ...HOST_OPTIONS,
62
78
  env: {
63
79
  AUTH_DEV_BYPASS_ENABLED: "true",
64
80
  AUTH_DEV_BYPASS_SECRET: SECRET
@@ -70,6 +86,7 @@ test("managed preview identity signs out before selecting an existing applicatio
70
86
  });
71
87
 
72
88
  assert.equal(result.ok, true);
89
+ assert.equal(result.protocol, HOST_PROTOCOL);
73
90
  assert.equal(result.identity.email, "ada@example.com");
74
91
  assert.equal(result.signedOut, false);
75
92
  assert.deepEqual(calls.map(({ href }) => new URL(href).pathname), [
@@ -81,22 +98,32 @@ test("managed preview identity signs out before selecting an existing applicatio
81
98
  assert.equal(JSON.parse(calls[2].options.body).email, "ada@example.com");
82
99
  });
83
100
 
101
+ test("managed preview identity requires the application's environment instead of reporting a disabled exchange", async () => {
102
+ await assert.rejects(executeManagedPreviewIdentityRequest({
103
+ operation: "logout",
104
+ protocol: HOST_PROTOCOL,
105
+ requestId: "request-env",
106
+ target: { origin: "http://localhost:3000" }
107
+ }, { ...HOST_OPTIONS, fetchImpl: async () => assert.fail("fetch must not run") }), /requires the application's environment/u);
108
+ });
109
+
84
110
  test("managed preview identity rejects a disabled or non-local exchange", async () => {
85
111
  const disabled = await executeManagedPreviewIdentityRequest({
86
112
  operation: "logout",
87
- protocol: MANAGED_PREVIEW_IDENTITY_PROTOCOL,
113
+ protocol: HOST_PROTOCOL,
88
114
  requestId: "request-2",
89
115
  target: { origin: "http://localhost:3000" }
90
- }, { env: {}, fetchImpl: async () => assert.fail("fetch must not run") });
116
+ }, { ...HOST_OPTIONS, env: {}, fetchImpl: async () => assert.fail("fetch must not run") });
91
117
  assert.equal(disabled.ok, false);
92
118
  assert.equal(disabled.code, "jskit_managed_preview_identity_disabled");
93
119
 
94
120
  const remote = await executeManagedPreviewIdentityRequest({
95
121
  operation: "logout",
96
- protocol: MANAGED_PREVIEW_IDENTITY_PROTOCOL,
122
+ protocol: HOST_PROTOCOL,
97
123
  requestId: "request-3",
98
124
  target: { origin: "https://example.com" }
99
125
  }, {
126
+ ...HOST_OPTIONS,
100
127
  env: {
101
128
  AUTH_DEV_BYPASS_ENABLED: "true",
102
129
  AUTH_DEV_BYPASS_SECRET: SECRET
@@ -105,6 +132,48 @@ test("managed preview identity rejects a disabled or non-local exchange", async
105
132
  });
106
133
  assert.equal(remote.ok, false);
107
134
  assert.equal(remote.code, "jskit_managed_preview_identity_target_invalid");
135
+
136
+ const unlisted = await executeManagedPreviewIdentityRequest({
137
+ operation: "logout",
138
+ protocol: DEFAULT_PREVIEW_IDENTITY_PROTOCOL,
139
+ requestId: "request-4",
140
+ target: { origin: "http://preview-deadbeefcafe" }
141
+ }, {
142
+ env: {
143
+ AUTH_DEV_BYPASS_ENABLED: "true",
144
+ AUTH_DEV_BYPASS_SECRET: SECRET
145
+ },
146
+ fetchImpl: async () => assert.fail("fetch must not run")
147
+ });
148
+ assert.equal(unlisted.code, "jskit_managed_preview_identity_target_invalid",
149
+ "a hostname the application does not list is not local");
150
+ });
151
+
152
+ test("managed preview identity accepts the dev auth secret auth-core accepts", async () => {
153
+ const request = {
154
+ operation: "logout",
155
+ protocol: HOST_PROTOCOL,
156
+ requestId: "request-5",
157
+ target: { origin: "http://localhost:3000" }
158
+ };
159
+ const missing = await executeManagedPreviewIdentityRequest(request, {
160
+ ...HOST_OPTIONS,
161
+ env: { AUTH_DEV_BYPASS_ENABLED: "true", AUTH_DEV_BYPASS_SECRET: " " },
162
+ fetchImpl: async () => assert.fail("fetch must not run")
163
+ });
164
+ assert.equal(missing.code, "jskit_managed_preview_identity_secret_missing");
165
+
166
+ const responses = [
167
+ jsonResponse({ csrfToken: "csrf-token" }, { cookie: "session=initial; Path=/" }),
168
+ jsonResponse({ ok: true }, { cookie: "session=; Max-Age=0; Path=/" })
169
+ ];
170
+ const signedOut = await executeManagedPreviewIdentityRequest(request, {
171
+ ...HOST_OPTIONS,
172
+ env: { AUTH_DEV_BYPASS_ENABLED: "true", AUTH_DEV_BYPASS_SECRET: " any-local-secret " },
173
+ fetchImpl: async () => responses.shift()
174
+ });
175
+ assert.equal(signedOut.ok, true);
176
+ assert.deepEqual(signedOut.setCookie, ["session=initial; Path=/", "session=; Max-Age=0; Path=/"]);
108
177
  });
109
178
 
110
179
  test("the auth surface pattern ships the managed-preview login as standard", () => {
@@ -112,13 +181,15 @@ test("the auth surface pattern ships the managed-preview login as standard", ()
112
181
  const executable = new URL("../patterns/auth-surface/example/tools/preview-identity", import.meta.url);
113
182
 
114
183
  assert.equal(statSync(executable).mode & 0o111, 0o111);
115
- assert.match(readFileSync(executable, "utf8"), /runManagedPreviewIdentityCommand/u);
184
+ const source = readFileSync(executable, "utf8");
185
+ assert.match(source, /runManagedPreviewIdentityCommand\(\{\n {2}protocol: /u);
186
+ assert.match(source, /localHostnames: /u);
116
187
  assert.match(pattern, /standard, not optional/u);
117
188
  assert.ok(pattern.includes([
118
189
  "#### Preview identity",
119
190
  "",
120
191
  "- Command: `tools/preview-identity`",
121
- `- Protocol: \`${MANAGED_PREVIEW_IDENTITY_PROTOCOL}\``,
192
+ "- Protocol: `<the host's protocol id>`",
122
193
  "- Identity types: `email` `user-id`",
123
194
  "- Enabled environment: `AUTH_DEV_BYPASS_ENABLED`",
124
195
  "- Secret environment: `AUTH_DEV_BYPASS_SECRET`",
@@ -1,6 +1,8 @@
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 } from "@jskit-ai/kernel/shared/capabilities";
5
7
  import { AuthFeature } from "@jskit-ai/auth-core/server/providers/AuthFeature";
6
8
  import { HttpProvider } from "@jskit-ai/kernel/server/http";
@@ -61,7 +63,7 @@ function createAuthService(events = []) {
61
63
  actor: { displayName: "Ada", email: "ada@example.com" }
62
64
  };
63
65
  },
64
- async devLoginAs(_request, input) {
66
+ async devLoginAs(input) {
65
67
  return {
66
68
  session: { access_token: "dev-a", refresh_token: "dev-r" },
67
69
  actor: { id: input.userId || "7", displayName: "Dev Ada", email: "ada@example.com" }
@@ -104,11 +106,12 @@ async function startAuthWeb({ env = {}, authService = null } = {}) {
104
106
  const fastify = createFastifyStub();
105
107
  const runtime = createCapabilityRuntime({
106
108
  inputs: {
109
+ "runtime.logger": silentLogger,
107
110
  "auth.service": authService || createAuthService(),
108
111
  "runtime.env": { NODE_ENV: "test", ...env },
109
112
  "runtime.fastify": fastify
110
113
  },
111
- providers: [createActionProvider(), HttpProvider, AuthFeature, AuthWebFeature]
114
+ providers: [EventProvider, ActionProvider, HttpProvider, AuthFeature, AuthWebFeature]
112
115
  });
113
116
  await runtime.start();
114
117
  return { fastify, runtime };
@@ -0,0 +1,83 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { createRenderer, defineComponent } from "vue";
4
+ import { useSessionRecheckOnShow } from "../src/client/composables/loginView/useSessionRecheckOnShow.js";
5
+
6
+ function node(type) {
7
+ return { type, children: [], parent: null };
8
+ }
9
+
10
+ const renderer = createRenderer({
11
+ createElement: node,
12
+ createText: () => node("text"),
13
+ createComment: () => node("comment"),
14
+ setText() {},
15
+ setElementText() {},
16
+ patchProp() {},
17
+ parentNode: (item) => item.parent,
18
+ nextSibling: () => null,
19
+ insert(item, parent) {
20
+ item.parent = parent;
21
+ parent.children.push(item);
22
+ },
23
+ remove(item) {
24
+ item.parent?.children.splice(item.parent.children.indexOf(item), 1);
25
+ }
26
+ });
27
+
28
+ function createEventTarget() {
29
+ const listeners = new Map();
30
+ return {
31
+ listeners,
32
+ addEventListener(type, handler) {
33
+ listeners.set(type, handler);
34
+ },
35
+ removeEventListener(type, handler) {
36
+ if (listeners.get(type) === handler) {
37
+ listeners.delete(type);
38
+ }
39
+ },
40
+ dispatch(type) {
41
+ listeners.get(type)?.();
42
+ }
43
+ };
44
+ }
45
+
46
+ test("the sign-in page rechecks its session each time it is shown while mounted", (t) => {
47
+ const originalWindow = globalThis.window;
48
+ const originalDocument = globalThis.document;
49
+ const page = createEventTarget();
50
+ const pageDocument = Object.assign(createEventTarget(), { visibilityState: "visible" });
51
+ globalThis.window = page;
52
+ globalThis.document = pageDocument;
53
+ t.after(() => {
54
+ if (originalWindow === undefined) delete globalThis.window;
55
+ else globalThis.window = originalWindow;
56
+ if (originalDocument === undefined) delete globalThis.document;
57
+ else globalThis.document = originalDocument;
58
+ });
59
+
60
+ let rechecks = 0;
61
+ const app = renderer.createApp(defineComponent({
62
+ setup() {
63
+ useSessionRecheckOnShow(() => {
64
+ rechecks += 1;
65
+ });
66
+ return () => null;
67
+ }
68
+ }));
69
+ app.mount(node("root"));
70
+
71
+ page.dispatch("focus");
72
+ page.dispatch("pageshow");
73
+ pageDocument.dispatch("visibilitychange");
74
+ assert.equal(rechecks, 3);
75
+
76
+ pageDocument.visibilityState = "hidden";
77
+ pageDocument.dispatch("visibilitychange");
78
+ assert.equal(rechecks, 3, "a hidden page does not check");
79
+
80
+ app.unmount();
81
+ assert.equal(page.listeners.size, 0);
82
+ assert.equal(pageDocument.listeners.size, 0);
83
+ });