@jskit-ai/auth-web 0.2.31 → 0.2.33

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.31",
3
+ "version": "0.2.33",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -28,7 +28,7 @@
28
28
  "@jskit-ai/auth-core": "0.2.21",
29
29
  "@jskit-ai/http-runtime": "0.2.21",
30
30
  "@jskit-ai/kernel": "0.2.21",
31
- "@jskit-ai/shell-web": "0.2.29",
31
+ "@jskit-ai/shell-web": "0.2.30",
32
32
  "@tanstack/vue-query": "^5.90.5",
33
33
  "pinia": "^4.0.3",
34
34
  "vue": "^3.5.44",
@@ -305,6 +305,6 @@
305
305
  }
306
306
  },
307
307
  "devDependencies": {
308
- "@jskit-ai/material-web": "0.1.5"
308
+ "@jskit-ai/material-web": "0.1.6"
309
309
  }
310
310
  }
@@ -76,6 +76,16 @@ managed-preview identity library directly; it does not require a JSKIT CLI. A
76
76
  project without a managed host keeps the executable; it is inert unless both
77
77
  environment values are present.
78
78
 
79
+ An application whose browsers get in another way, so that the development
80
+ login-as route is unreachable (for example one that opens with its own key),
81
+ passes its own `exchange` instead. It receives the operation, the existing
82
+ user a `login-as` names (`{ email }` or `{ userId }`), the checked local target
83
+ origin and the fetch to reach it with, and resolves with the browser's
84
+ Set-Cookie headers and, for `login-as`, the user signed in; a refusal is an
85
+ error with a `code` and `statusCode`. JSKIT still reads and checks the request
86
+ and writes the response, and needs no development values then, so the
87
+ declaration drops the two environment names.
88
+
79
89
  Choose local-auth storage through the installed capability provider. A
80
90
  database-backed application installs `@jskit-ai/auth-provider-local-db-core`,
81
91
  which provides `auth.local.backend`; no environment switch selects it. When no
@@ -269,37 +269,86 @@ async function login(fetchImpl, targetOrigin, identity, secret, session) {
269
269
  if (!fetchResponse.ok || payload?.ok !== true) {
270
270
  throw rejected(payload, fetchResponse, { setCookie, signedOut: true });
271
271
  }
272
+ // readable-check: allow setter-seam - not a slot: setCookie is the preview identity protocol's list of Set-Cookie headers
273
+ return { identity: payload, setCookie };
274
+ }
275
+
276
+ /**
277
+ * JSKIT's development exchange, the default: it signs the preview browser out, and for `login-as` back in through the
278
+ * development login-as route, so it needs both development values in the application's environment.
279
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env
280
+ * @returns {PreviewIdentityExchange}
281
+ */
282
+ function developmentExchange(env) {
283
+ const devAuth = resolveDevAuthPolicyFromEnv(env);
284
+ if (!isDevAuthBootstrapEnabled(devAuth)) {
285
+ throw commandError(
286
+ "Managed preview identity is not enabled.",
287
+ "jskit_managed_preview_identity_disabled",
288
+ { statusCode: 403 }
289
+ );
290
+ }
291
+ if (!devAuth.secret) {
292
+ throw commandError(
293
+ "Managed preview identity secret is unavailable.",
294
+ "jskit_managed_preview_identity_secret_missing",
295
+ { statusCode: 500 }
296
+ );
297
+ }
298
+ return async ({ operation, identity, targetOrigin, fetchImpl }) => {
299
+ const session = await bootstrapSession(fetchImpl, targetOrigin);
300
+ const signedOutSession = await logout(fetchImpl, targetOrigin, session);
301
+ return operation === "logout"
302
+ ? signedOutSession
303
+ : login(fetchImpl, targetOrigin, identity, devAuth.secret, signedOutSession);
304
+ };
305
+ }
306
+
307
+ /**
308
+ * The identity a sign-in reports: what the application answered, else what the request asked for.
309
+ * @param {Record<string, any> | null | undefined} answered
310
+ * @param {{ email?: string, userId?: string }} asked
311
+ */
312
+ function signedInIdentity(answered, asked) {
272
313
  return {
273
- identity: {
274
- displayName: String(payload.displayName || payload.username || "").trim(),
275
- email: String(payload.email || identity.email || "").trim().toLowerCase(),
276
- userId: String(payload.userId || identity.userId || "").trim(),
277
- username: String(payload.username || "").trim()
278
- },
279
- // readable-check: allow setter-seam - not a slot: setCookie is the preview identity protocol's list of Set-Cookie headers
280
- setCookie
314
+ displayName: String(answered?.displayName || answered?.username || "").trim(),
315
+ email: String(answered?.email || asked.email || "").trim().toLowerCase(),
316
+ userId: String(answered?.userId || asked.userId || "").trim(),
317
+ username: String(answered?.username || "").trim()
281
318
  };
282
319
  }
283
320
 
321
+ /**
322
+ * How the preview browser is signed in or out: given the operation, the existing user a `login-as` names
323
+ * (`{ email }` or `{ userId }`, else null), the checked local target origin and the fetch to reach it with, it resolves
324
+ * with the Set-Cookie headers for the browser and, for `login-as`, what the application says about the user signed
325
+ * in. A refusal is an error whose `code`, `statusCode`, `setCookie` and `signedOut` the response reports.
326
+ * @typedef {(call: { operation: "login-as" | "logout", identity: { email?: string, userId?: string } | null, targetOrigin: string, fetchImpl: typeof fetch }) => Promise<{ setCookie: string[], identity?: Record<string, any> | null }>} PreviewIdentityExchange
327
+ */
328
+
284
329
  /**
285
330
  * Answers one preview identity request: signs the preview browser out, and for
286
331
  * `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
332
+ * exchange, or through the application's own `exchange` when it has another
333
+ * way in. The preview host names the protocol id and any hostnames, besides
288
334
  * loopback, that it serves the application on.
289
335
  * @param {Record<string, any>} value The command's request, which is validated here.
290
336
  * @param {object} options
291
- * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} options.env The application's environment, such as `process.env`.
337
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} [options.env] The application's environment, such as
338
+ * `process.env`, which the development exchange reads; required without `exchange`.
292
339
  * @param {typeof fetch} [options.fetchImpl]
293
340
  * @param {string} [options.protocol] The protocol id requests carry and responses echo.
294
341
  * @param {RegExp[]} [options.localHostnames] Hostnames, besides loopback, the application is served on.
342
+ * @param {PreviewIdentityExchange} [options.exchange] The application's own exchange, in place of the development one.
295
343
  */
296
344
  async function executeManagedPreviewIdentityRequest(value, {
297
345
  env,
298
346
  fetchImpl = globalThis.fetch,
299
347
  protocol = DEFAULT_PREVIEW_IDENTITY_PROTOCOL,
300
- localHostnames = []
348
+ localHostnames = [],
349
+ exchange
301
350
  }) {
302
- if (!env) {
351
+ if (!env && !exchange) {
303
352
  throw new TypeError("executeManagedPreviewIdentityRequest requires the application's environment, such as process.env.");
304
353
  }
305
354
  let requestId = String(value?.requestId || "").trim();
@@ -314,42 +363,25 @@ async function executeManagedPreviewIdentityRequest(value, {
314
363
  { statusCode: 500 }
315
364
  );
316
365
  }
317
- const devAuth = resolveDevAuthPolicyFromEnv(env);
318
- if (!isDevAuthBootstrapEnabled(devAuth)) {
319
- throw commandError(
320
- "Managed preview identity is not enabled.",
321
- "jskit_managed_preview_identity_disabled",
322
- { statusCode: 403 }
323
- );
324
- }
325
- if (!devAuth.secret) {
326
- throw commandError(
327
- "Managed preview identity secret is unavailable.",
328
- "jskit_managed_preview_identity_secret_missing",
329
- { statusCode: 500 }
330
- );
331
- }
366
+ const run = exchange || developmentExchange(env);
332
367
  const identity = request.operation === "login-as"
333
368
  ? identityFromSubject(request.subject)
334
369
  : null;
335
- const session = await bootstrapSession(fetchImpl, request.targetOrigin);
336
- const signedOutSession = await logout(fetchImpl, request.targetOrigin, session);
337
- if (request.operation === "logout") {
338
- return response(protocol, requestId, {
339
- identity: null,
340
- ok: true,
341
- // readable-check: allow setter-seam - not a slot: setCookie is the preview identity protocol's list of Set-Cookie headers
342
- setCookie: signedOutSession.setCookie,
343
- signedOut: true
344
- });
370
+ const result = await run({ operation: request.operation, identity, targetOrigin: request.targetOrigin, fetchImpl });
371
+ if (!Array.isArray(result?.setCookie)) {
372
+ throw commandError(
373
+ "Managed preview identity exchange returned no cookie list.",
374
+ "jskit_managed_preview_identity_exchange_invalid",
375
+ { statusCode: 502 }
376
+ );
345
377
  }
346
- const result = await login(fetchImpl, request.targetOrigin, identity, devAuth.secret, signedOutSession);
378
+ const signedOut = request.operation === "logout";
347
379
  return response(protocol, requestId, {
348
- identity: result.identity,
380
+ identity: signedOut ? null : signedInIdentity(result.identity, identity),
349
381
  ok: true,
350
382
  // readable-check: allow setter-seam - not a slot: setCookie is the preview identity protocol's list of Set-Cookie headers
351
383
  setCookie: result.setCookie,
352
- signedOut: false
384
+ signedOut
353
385
  });
354
386
  } catch (error) {
355
387
  return failure(protocol, requestId, error);
@@ -359,12 +391,14 @@ async function executeManagedPreviewIdentityRequest(value, {
359
391
  /**
360
392
  * Reads one request from stdin and writes its response to stdout.
361
393
  * @param {object} options
362
- * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} options.env The application's environment, such as `process.env`.
394
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} [options.env] The application's environment, such as
395
+ * `process.env`, which the development exchange reads; required without `exchange`.
363
396
  * @param {typeof fetch} [options.fetchImpl]
364
397
  * @param {AsyncIterable<string | Buffer>} [options.stdin]
365
398
  * @param {{ write(text: string): unknown }} [options.stdout]
366
399
  * @param {string} [options.protocol] The protocol id requests carry and responses echo.
367
400
  * @param {RegExp[]} [options.localHostnames] Hostnames, besides loopback, the application is served on.
401
+ * @param {PreviewIdentityExchange} [options.exchange] The application's own exchange, in place of the development one.
368
402
  */
369
403
  async function runManagedPreviewIdentityCommand({
370
404
  env,
@@ -372,7 +406,8 @@ async function runManagedPreviewIdentityCommand({
372
406
  stdin = process.stdin,
373
407
  stdout = process.stdout,
374
408
  protocol = DEFAULT_PREVIEW_IDENTITY_PROTOCOL,
375
- localHostnames = []
409
+ localHostnames = [],
410
+ exchange
376
411
  }) {
377
412
  let request;
378
413
  try {
@@ -381,7 +416,7 @@ async function runManagedPreviewIdentityCommand({
381
416
  stdout.write(`${JSON.stringify(failure(protocol, "", error))}\n`);
382
417
  return 0;
383
418
  }
384
- const result = await executeManagedPreviewIdentityRequest(request, { env, fetchImpl, protocol, localHostnames });
419
+ const result = await executeManagedPreviewIdentityRequest(request, { env, fetchImpl, protocol, localHostnames, exchange });
385
420
  stdout.write(`${JSON.stringify(result)}\n`);
386
421
  return 0;
387
422
  }
@@ -4,7 +4,8 @@ import test from "node:test";
4
4
 
5
5
  import {
6
6
  DEFAULT_PREVIEW_IDENTITY_PROTOCOL,
7
- executeManagedPreviewIdentityRequest
7
+ executeManagedPreviewIdentityRequest,
8
+ runManagedPreviewIdentityCommand
8
9
  } from "../src/server/managedPreviewIdentity.js";
9
10
 
10
11
  const SECRET = "a".repeat(64);
@@ -196,3 +197,99 @@ test("the auth surface pattern ships the managed-preview login as standard", ()
196
197
  "- Runtimes: `nodejs`"
197
198
  ].join("\n")));
198
199
  });
200
+
201
+ test("an application's own exchange signs the preview in instead of the development exchange", async () => {
202
+ const exchanged = [];
203
+ const request = {
204
+ operation: "login-as",
205
+ protocol: HOST_PROTOCOL,
206
+ requestId: "request-own",
207
+ subject: { kind: "selector", selector: { type: "email", value: "you@example.com" } },
208
+ target: { origin: "http://127.0.0.1:3000" }
209
+ };
210
+ const fetchImpl = async () => assert.fail("JSKIT's development exchange must not run");
211
+ const exchange = async (call) => {
212
+ exchanged.push(call);
213
+ return call.operation === "logout"
214
+ ? { setCookie: ["key=; Max-Age=0; Path=/"] }
215
+ : { identity: { displayName: "You", email: "You@Example.com" }, setCookie: ["key=k; Path=/; HttpOnly", "session=s; Path=/"] };
216
+ };
217
+
218
+ // No development exchange is enabled, and none is needed.
219
+ const signedIn = await executeManagedPreviewIdentityRequest(request, { ...HOST_OPTIONS, fetchImpl, exchange });
220
+ assert.equal(signedIn.ok, true);
221
+ assert.equal(signedIn.protocol, HOST_PROTOCOL);
222
+ assert.equal(signedIn.requestId, "request-own");
223
+ assert.equal(signedIn.signedOut, false);
224
+ assert.deepEqual(signedIn.identity, { displayName: "You", email: "you@example.com", userId: "", username: "" });
225
+ assert.deepEqual(signedIn.setCookie, ["key=k; Path=/; HttpOnly", "session=s; Path=/"]);
226
+ assert.deepEqual(exchanged[0], {
227
+ operation: "login-as",
228
+ identity: { email: "you@example.com" },
229
+ targetOrigin: "http://127.0.0.1:3000",
230
+ fetchImpl
231
+ });
232
+
233
+ const signedOut = await executeManagedPreviewIdentityRequest({ ...request, operation: "logout", subject: undefined }, {
234
+ ...HOST_OPTIONS,
235
+ fetchImpl,
236
+ exchange
237
+ });
238
+ assert.equal(signedOut.ok, true);
239
+ assert.equal(signedOut.signedOut, true);
240
+ assert.equal(signedOut.identity, null);
241
+ assert.deepEqual(signedOut.setCookie, ["key=; Max-Age=0; Path=/"]);
242
+ assert.equal(exchanged[1].identity, null);
243
+
244
+ // The request is checked before the exchange runs.
245
+ const remote = await executeManagedPreviewIdentityRequest({ ...request, target: { origin: "https://example.com" } }, {
246
+ ...HOST_OPTIONS,
247
+ exchange: async () => assert.fail("the exchange must not run")
248
+ });
249
+ assert.equal(remote.code, "jskit_managed_preview_identity_target_invalid");
250
+ });
251
+
252
+ test("an application's own exchange refuses with its own error, and must return its cookies", async () => {
253
+ const request = {
254
+ operation: "login-as",
255
+ protocol: HOST_PROTOCOL,
256
+ requestId: "request-refused",
257
+ subject: { kind: "selector", selector: { type: "email", value: "someone@example.com" } },
258
+ target: { origin: "http://localhost:3000" }
259
+ };
260
+ const refused = await executeManagedPreviewIdentityRequest(request, {
261
+ ...HOST_OPTIONS,
262
+ exchange: async () => {
263
+ throw Object.assign(new Error("This application has one person."), { code: "one_person", statusCode: 404 });
264
+ }
265
+ });
266
+ assert.deepEqual(
267
+ [refused.ok, refused.code, refused.error, refused.statusCode, refused.setCookie],
268
+ [false, "one_person", "This application has one person.", 404, []]
269
+ );
270
+
271
+ const cookieless = await executeManagedPreviewIdentityRequest(request, {
272
+ ...HOST_OPTIONS,
273
+ exchange: async () => ({ identity: { email: "someone@example.com" } })
274
+ });
275
+ assert.equal(cookieless.ok, false);
276
+ assert.equal(cookieless.code, "jskit_managed_preview_identity_exchange_invalid");
277
+ });
278
+
279
+ test("the preview identity command hands an application's exchange the request it reads", async () => {
280
+ const written = [];
281
+ const exitCode = await runManagedPreviewIdentityCommand({
282
+ protocol: HOST_PROTOCOL,
283
+ stdin: [Buffer.from(JSON.stringify({
284
+ operation: "logout",
285
+ protocol: HOST_PROTOCOL,
286
+ requestId: "request-command",
287
+ target: { origin: "http://localhost:3000" }
288
+ }))],
289
+ stdout: { write: (text) => written.push(text) },
290
+ exchange: async ({ operation }) => ({ setCookie: [`${operation}=done; Path=/`] })
291
+ });
292
+ assert.equal(exitCode, 0);
293
+ const answer = JSON.parse(written.join(""));
294
+ assert.deepEqual([answer.ok, answer.signedOut, answer.setCookie], [true, true, ["logout=done; Path=/"]]);
295
+ });