@oatscenter/trellis 0.100.0-rc.26 → 0.100.0-rc.28

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.
@@ -81,8 +81,25 @@ export declare function connectClient<T extends AppRequestDescriptor>(args: Trel
81
81
  export declare function connectClientWithDeps<T extends AppRequestDescriptor>(args: TrellisClientConnectArgs<T>, deps: {
82
82
  transport?: RuntimeTransport;
83
83
  }): AsyncResult<ConnectedTrellisClient<T>, UnexpectedError | AuthError | TransportError>;
84
+ /** Options for signing a browser app out without connecting it first. */
85
+ export type ClientSignOutArgs = {
86
+ trellisUrl: string;
87
+ auth: Pick<ClientAuthOptions, "clientId" | "credentialHandle">;
88
+ /**
89
+ * Where the Portal returns after ending its login; defaults to the current
90
+ * page. Its origin must be one the app registered a redirect URI on.
91
+ */
92
+ returnTo?: string;
93
+ };
84
94
  /** Public OAuth app connector. Requests choose local surfaces; signed admission owns authority. */
85
95
  export declare class TrellisClient {
86
96
  /** Open a registered browser application using its generated request descriptor. */
87
97
  static connect<const T extends AppRequestDescriptor>(args: TrellisClientConnectArgs<T>): AsyncResult<ConnectedTrellisClient<T>, UnexpectedError | AuthError | TransportError>;
98
+ /**
99
+ * Revoke the app's stored OAuth session and end the Portal login, then
100
+ * navigate back to `returnTo`. Unlike `logout` on a connected client, this
101
+ * works when connecting failed, so a person can start over and sign in
102
+ * again, possibly as someone else.
103
+ */
104
+ static signOut(args: ClientSignOutArgs): AsyncResult<void, AuthError>;
88
105
  }
package/client_connect.js CHANGED
@@ -21,9 +21,11 @@ export function connectClientWithDeps(args, deps) {
21
21
  throw new AuthError({ reason: "InvalidCredential" });
22
22
  // An approval popup ends on the app's callback. The window that opened
23
23
  // it holds the continuation and reads the outcome; this one only
24
- // reports where it landed.
24
+ // reports where it landed. Any other window, opened by the app or
25
+ // not, completes its own sign-in.
25
26
  const landed = new URL(args.auth.currentUrl ?? location.href);
26
- if (landed.searchParams.has("state") && sameOriginOpener()) {
27
+ const state = landed.searchParams.get("state");
28
+ if (state && sameOriginOpener() && approvalPending(state)) {
27
29
  window.opener.postMessage({ type: APPROVAL_MESSAGE, href: landed.href }, location.origin);
28
30
  return Result.err(new AuthError({ reason: "OAuthApprovalWindow" }));
29
31
  }
@@ -103,15 +105,24 @@ export function connectClientWithDeps(args, deps) {
103
105
  let unseen = [];
104
106
  // The optional capabilities the user was shown when approving this grant.
105
107
  let grantAsked = [];
108
+ const requestedOptional = (admission) => {
109
+ const details = admission.authorizationDetails;
110
+ return details?.every((detail) => detail.requested_optional !== undefined)
111
+ ? details.flatMap((detail) => detail.requested_optional ?? [])
112
+ : undefined;
113
+ };
106
114
  const install = async (admission) => {
107
115
  const details = admission.authorizationDetails;
108
- const granted = details?.flatMap((detail) => detail.required);
116
+ // An optional capability the user approved counts once a newer app
117
+ // version requires it: the grant already holds it.
118
+ const granted = details?.flatMap((detail) => [
119
+ ...detail.required,
120
+ ...detail.optional,
121
+ ]);
109
122
  outdated =
110
123
  granted !== undefined &&
111
124
  args.request.requiredCapabilities.some((capability) => !granted.includes(capability));
112
- const requested = details?.every((detail) => detail.requested_optional !== undefined)
113
- ? details.flatMap((detail) => detail.requested_optional ?? [])
114
- : undefined;
125
+ const requested = requestedOptional(admission);
115
126
  grantAsked = requested ?? [];
116
127
  if (!outdated && args.auth.askForNewOptional && requested) {
117
128
  const asked = new Set([...requested, ...askedOptional(oauth)]);
@@ -123,6 +134,9 @@ export function connectClientWithDeps(args, deps) {
123
134
  let resumed = callback
124
135
  ? (await oauth.complete(currentUrl.href)).take()
125
136
  : (await oauth.resume(install)).take();
137
+ // The consent just given is what the grant asked about.
138
+ if (callback && !isErr(resumed) && "value" in resumed)
139
+ grantAsked = requestedOptional(resumed.value) ?? [];
126
140
  // Declining more leaves the app as it was, on the grant already approved.
127
141
  if (callback &&
128
142
  isErr(resumed) &&
@@ -247,6 +261,7 @@ export function connectClientWithDeps(args, deps) {
247
261
  // The popup widens this session's own grant, so the live
248
262
  // connection renews into the approved capabilities in place.
249
263
  const approveInPopup = async (popup) => {
264
+ let state;
250
265
  try {
251
266
  const lease = activeConnection.owner.own();
252
267
  const grant = lease.authority.oauthGrantId;
@@ -258,6 +273,9 @@ export function connectClientWithDeps(args, deps) {
258
273
  })).take();
259
274
  if (isErr(url))
260
275
  return false;
276
+ state = new URL(url).searchParams.get("state") ?? undefined;
277
+ if (state)
278
+ markApproval(state, true);
261
279
  popup.location.href = url;
262
280
  const landed = await approvalCallback(popup, new URL(args.auth.redirectTo).pathname);
263
281
  if (!landed)
@@ -273,6 +291,8 @@ export function connectClientWithDeps(args, deps) {
273
291
  return false;
274
292
  }
275
293
  finally {
294
+ if (state)
295
+ markApproval(state, false);
276
296
  popup.close();
277
297
  }
278
298
  };
@@ -308,10 +328,7 @@ export function connectClientWithDeps(args, deps) {
308
328
  await activeConnection.manager.close();
309
329
  if (!options?.endPortalLogin)
310
330
  return;
311
- const signOut = new URL(oauth.metadata.end_session_endpoint);
312
- signOut.searchParams.set("client_id", args.auth.clientId);
313
- signOut.searchParams.set("post_logout_redirect_uri", options.returnTo ?? location.href);
314
- location.assign(signOut);
331
+ endPortalLogin(oauth, args.auth.clientId, options.returnTo);
315
332
  },
316
333
  }));
317
334
  }
@@ -329,16 +346,73 @@ export function connectClientWithDeps(args, deps) {
329
346
  }
330
347
  })());
331
348
  }
349
+ /** Navigate through the Portal's sign-out, which returns to `returnTo`. */
350
+ function endPortalLogin(oauth, clientId, returnTo = location.href) {
351
+ const signOut = new URL(oauth.metadata.end_session_endpoint);
352
+ signOut.searchParams.set("client_id", clientId);
353
+ signOut.searchParams.set("post_logout_redirect_uri", returnTo);
354
+ location.assign(signOut);
355
+ }
332
356
  /** Public OAuth app connector. Requests choose local surfaces; signed admission owns authority. */
333
357
  export class TrellisClient {
334
358
  /** Open a registered browser application using its generated request descriptor. */
335
359
  static connect(args) {
336
360
  return connectClient(args);
337
361
  }
362
+ /**
363
+ * Revoke the app's stored OAuth session and end the Portal login, then
364
+ * navigate back to `returnTo`. Unlike `logout` on a connected client, this
365
+ * works when connecting failed, so a person can start over and sign in
366
+ * again, possibly as someone else.
367
+ */
368
+ static signOut(args) {
369
+ return AsyncResult.from((async () => {
370
+ const opened = (await BrowserOAuthClient.open({
371
+ issuer: args.trellisUrl,
372
+ clientId: args.auth.clientId,
373
+ credentialHandle: args.auth.credentialHandle ?? args.auth.clientId,
374
+ })).take();
375
+ if (isErr(opened))
376
+ return Result.err(opened.error);
377
+ const revoked = await opened.revoke();
378
+ if (revoked.isErr()) {
379
+ // A missing or unusable credential has no session left to revoke;
380
+ // dropping it locally is enough.
381
+ if (!["InvalidCredential", "OAuthRecoveryRequired"].includes(revoked.error.reason))
382
+ return Result.err(revoked.error);
383
+ await opened.store.clear();
384
+ }
385
+ endPortalLogin(opened, args.auth.clientId, args.returnTo);
386
+ return Result.ok(undefined);
387
+ })());
388
+ }
338
389
  }
339
390
  /** Names the approval popup and the message it sends its opener. */
340
391
  const APPROVAL_MESSAGE = "trellis.approval";
341
392
  const POPUP_FEATURES = "popup,width=520,height=720";
393
+ /** The OAuth states of the approvals this window has sent popups to. */
394
+ const pendingApprovals = new Set();
395
+ function markApproval(state, pending) {
396
+ if (pending)
397
+ pendingApprovals.add(state);
398
+ else
399
+ pendingApprovals.delete(state);
400
+ // The popup asks this window directly, so no storage has to work.
401
+ if (!Object.hasOwn(window, APPROVAL_MESSAGE))
402
+ Object.defineProperty(window, APPROVAL_MESSAGE, {
403
+ value: (asked) => typeof asked === "string" && pendingApprovals.has(asked),
404
+ });
405
+ }
406
+ /** Whether the same-origin opener sent this window to approve `state`. */
407
+ function approvalPending(state) {
408
+ try {
409
+ const pending = window.opener[APPROVAL_MESSAGE];
410
+ return typeof pending === "function" && pending(state) === true;
411
+ }
412
+ catch {
413
+ return false;
414
+ }
415
+ }
342
416
  /** Whether this window was opened by another window of this app's origin. */
343
417
  function sameOriginOpener() {
344
418
  try {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "dependencies": {
3
- "@oatscenter/trellis": "^0.100.0-rc.26"
3
+ "@oatscenter/trellis": "^0.100.0-rc.28"
4
4
  },
5
5
  "description": "Generated Trellis APIs and participants.",
6
6
  "exports": {
package/package.json CHANGED
@@ -51,7 +51,7 @@
51
51
  "@nats-io/obj": "^3.4.0",
52
52
  "@nats-io/transport-node": "^3.4.0",
53
53
  "@noble/hashes": "1.8.0",
54
- "@oatscenter/result": "0.100.0-rc.26",
54
+ "@oatscenter/result": "0.100.0-rc.28",
55
55
  "@opentelemetry/api": "^1.9.1",
56
56
  "@opentelemetry/context-async-hooks": "~2.11.0",
57
57
  "@opentelemetry/core": "~2.11.0",
@@ -71,7 +71,7 @@
71
71
  "uqr": "0.1.3",
72
72
  "zod": "^4.3.6"
73
73
  },
74
- "version": "0.100.0-rc.26",
74
+ "version": "0.100.0-rc.28",
75
75
  "type": "module",
76
76
  "license": "Apache-2.0",
77
77
  "publishConfig": {
package/portable.d.ts CHANGED
@@ -15,7 +15,7 @@ export { PaginationError } from "./pagination.ts";
15
15
  export { decodePaginationCursor, encodePaginationCursor, paginationQueryDigest, } from "./auth/protocol_wasm.ts";
16
16
  export type { PaginationErrorData } from "./pagination.ts";
17
17
  export type { CallerUser } from "./auth/protocol_wasm.ts";
18
- export type { ClientAuthContinuation, ClientAuthOptions, ClientAuthRequiredContext, ClientLogoutOptions, ClientResourceMigrations, ConnectedTrellisClient, TrellisClientConnectArgs, } from "./client_connect.ts";
18
+ export type { ClientAuthContinuation, ClientAuthOptions, ClientAuthRequiredContext, ClientLogoutOptions, ClientSignOutArgs, ClientResourceMigrations, ConnectedTrellisClient, TrellisClientConnectArgs, } from "./client_connect.ts";
19
19
  export { TrellisClient } from "./client_connect.ts";
20
20
  export type { OwnAuthorityView, OwnAuthoritySnapshot, OwnAuthorizedAction, } from "./own_authority.ts";
21
21
  export type { AppRequestDescriptor } from "./generated_support.ts";