@oatscenter/trellis 0.100.0-rc.23 → 0.100.0-rc.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/auth/browser/oauth.d.ts +16 -2
  2. package/auth/browser/oauth.js +36 -2
  3. package/auth/connection.d.ts +4 -0
  4. package/auth/connection.js +2 -0
  5. package/auth/session_auth.d.ts +5 -0
  6. package/auth/session_auth.js +1 -0
  7. package/caller.d.ts +13 -2
  8. package/caller.js +31 -28
  9. package/client_connect.d.ts +15 -0
  10. package/client_connect.js +205 -6
  11. package/connection.d.ts +6 -1
  12. package/connection.js +2 -0
  13. package/internal_sdk/generated/apis/auth/mod.d.ts +13 -1
  14. package/internal_sdk/generated/apis/auth/mod.js +19 -5
  15. package/internal_sdk/generated/apis/core/mod.js +4 -4
  16. package/internal_sdk/generated/apis/events/mod.js +4 -4
  17. package/internal_sdk/generated/apis/health/mod.js +4 -4
  18. package/internal_sdk/generated/apis/jobs/mod.js +4 -4
  19. package/internal_sdk/generated/apis/state/mod.js +4 -4
  20. package/internal_sdk/generated/apps/cli/mod.d.ts +5 -0
  21. package/internal_sdk/generated/apps/cli/mod.js +6 -0
  22. package/internal_sdk/generated/apps/console/mod.d.ts +5 -0
  23. package/internal_sdk/generated/apps/console/mod.js +6 -0
  24. package/internal_sdk/generated/package.json +2 -2
  25. package/internal_sdk/generated/participants/eventsRuntime/mod.d.ts +1 -0
  26. package/internal_sdk/generated/participants/eventsRuntime/mod.js +5 -4
  27. package/internal_sdk/generated/participants/healthRuntime/mod.js +4 -4
  28. package/internal_sdk/generated/participants/jobsRuntime/mod.d.ts +1 -0
  29. package/internal_sdk/generated/participants/jobsRuntime/mod.js +5 -4
  30. package/internal_sdk/generated/participants/platform/mod.d.ts +2 -1
  31. package/internal_sdk/generated/participants/platform/mod.js +7 -6
  32. package/internal_sdk/generated/types/_internal/p0.d.ts +35 -0
  33. package/internal_sdk/generated/types/_internal/p0.js +13 -0
  34. package/internal_sdk/generated/types/index.d.ts +8 -0
  35. package/internal_sdk/generated/types/index.js +4 -0
  36. package/native/connection.d.ts +2 -0
  37. package/native/connection.js +6 -0
  38. package/native/discovery.d.ts +2 -0
  39. package/native/discovery.js +2 -0
  40. package/package.json +2 -2
  41. package/participant_runtime/participant.js +1 -0
  42. package/runtime_transport.js +8 -1
  43. package/service/runtime/service.js +1 -0
  44. package/transport/generations.js +13 -0
@@ -17,6 +17,7 @@ declare const metadataSchema: z.ZodObject<{
17
17
  audienceNatsAccount: z.ZodString;
18
18
  rotationSequence: z.ZodString;
19
19
  natsEndpoints: z.ZodArray<z.ZodString>;
20
+ natsSentinel: z.ZodString;
20
21
  issuers: z.ZodArray<z.ZodObject<{
21
22
  keyId: z.ZodString;
22
23
  publicKey: z.ZodString;
@@ -38,6 +39,7 @@ declare const tokenSchema: z.ZodObject<{
38
39
  type: z.ZodLiteral<"trellis_capabilities">;
39
40
  required: z.ZodArray<z.ZodString>;
40
41
  optional: z.ZodArray<z.ZodString>;
42
+ requested_optional: z.ZodOptional<z.ZodArray<z.ZodString>>;
41
43
  }, z.core.$strip>>>;
42
44
  }, z.core.$strip>;
43
45
  /** HTTPS-authenticated discovery scoped to the user's selected server. */
@@ -74,13 +76,25 @@ export declare class BrowserOAuthClient {
74
76
  }): Promise<Result<BrowserOAuthClient, AuthError>>;
75
77
  /** Revoke this app's refresh family and clear custody; does not log out of the Portal. */
76
78
  revoke(): Promise<Result<void, AuthError>>;
77
- /** Build a PKCE authorization URL and retain only this tab's continuation. */
78
- authorize(redirectUri: string, capabilities: BrowserCapabilityRequest): Promise<Result<string, AuthError>>;
79
+ /**
80
+ * Build a PKCE authorization URL and retain only this tab's continuation.
81
+ * With `extendGrant`, approval widens that grant of this app instead of
82
+ * creating another, so its live session gains what the user approves.
83
+ */
84
+ authorize(redirectUri: string, capabilities: BrowserCapabilityRequest, options?: {
85
+ extendGrant?: string;
86
+ }): Promise<Result<string, AuthError>>;
79
87
  /** Consume this tab's exact callback once; install signed authority before remembering its grant. */
80
88
  complete(callback?: string): Promise<Result<{
81
89
  value: BrowserOAuthAdmission;
82
90
  refreshToken: string;
83
91
  }, AuthError>>;
92
+ /**
93
+ * Whether the user approved an extension whose callback reached another
94
+ * window, checked against this tab's continuation like {@link complete}.
95
+ * The code is not exchanged: the extended grant already holds the approval.
96
+ */
97
+ approvalOutcome(callback: string): Result<boolean, AuthError>;
84
98
  /** Serialize refresh across tabs and atomically commit rotation; reload makes a fresh runtime key. */
85
99
  resume(install?: (admission: BrowserOAuthAdmission) => Promise<void>): Promise<Result<BrowserOAuthAdmission, AuthError>>;
86
100
  /** Bind the authenticated connection to the retained credential trust root. */
@@ -20,6 +20,7 @@ const metadataSchema = z.object({
20
20
  audienceNatsAccount: z.string().min(1),
21
21
  rotationSequence: z.string().regex(/^(0|[1-9][0-9]*)$/),
22
22
  natsEndpoints: z.array(z.string().min(1)).min(1),
23
+ natsSentinel: z.string().min(1),
23
24
  issuers: z
24
25
  .array(z.object({
25
26
  keyId: z.string().min(1),
@@ -40,6 +41,8 @@ const tokenSchema = z.object({
40
41
  type: z.literal("trellis_capabilities"),
41
42
  required: z.array(z.string()),
42
43
  optional: z.array(z.string()),
44
+ /** Every optional capability the grant asked for, declined ones too. */
45
+ requested_optional: z.array(z.string()).optional(),
43
46
  }))
44
47
  .optional(),
45
48
  });
@@ -144,8 +147,12 @@ export class BrowserOAuthClient {
144
147
  }
145
148
  });
146
149
  }
147
- /** Build a PKCE authorization URL and retain only this tab's continuation. */
148
- async authorize(redirectUri, capabilities) {
150
+ /**
151
+ * Build a PKCE authorization URL and retain only this tab's continuation.
152
+ * With `extendGrant`, approval widens that grant of this app instead of
153
+ * creating another, so its live session gains what the user approves.
154
+ */
155
+ async authorize(redirectUri, capabilities, options = {}) {
149
156
  try {
150
157
  const redirect = new URL(redirectUri);
151
158
  if (redirect.origin !== location.origin ||
@@ -184,6 +191,7 @@ export class BrowserOAuthClient {
184
191
  optional: capabilities.optional,
185
192
  },
186
193
  ]),
194
+ ...(options.extendGrant ? { trellis_grant: options.extendGrant } : {}),
187
195
  }).toString();
188
196
  return ok(url.href);
189
197
  }
@@ -231,6 +239,32 @@ export class BrowserOAuthClient {
231
239
  return err(new AuthError({ reason: "OAuthRecoveryRequired" }));
232
240
  }
233
241
  }
242
+ /**
243
+ * Whether the user approved an extension whose callback reached another
244
+ * window, checked against this tab's continuation like {@link complete}.
245
+ * The code is not exchanged: the extended grant already holds the approval.
246
+ */
247
+ approvalOutcome(callback) {
248
+ try {
249
+ const raw = sessionStorage.getItem(this.#pendingKey());
250
+ if (!raw)
251
+ return err(new AuthError({ reason: "OAuthRecoveryRequired" }));
252
+ const pending = pendingSchema.parse(JSON.parse(raw));
253
+ const url = new URL(callback);
254
+ const redirect = new URL(pending.redirectUri);
255
+ if (Date.now() - pending.createdAt > 600_000 ||
256
+ url.origin !== redirect.origin ||
257
+ url.pathname !== redirect.pathname ||
258
+ url.searchParams.getAll("state").length !== 1 ||
259
+ url.searchParams.get("state") !== pending.state)
260
+ return err(new AuthError({ reason: "InvalidOAuthCallback" }));
261
+ sessionStorage.removeItem(this.#pendingKey());
262
+ return ok(url.searchParams.has("code") && !url.searchParams.has("error"));
263
+ }
264
+ catch {
265
+ return err(new AuthError({ reason: "InvalidOAuthCallback" }));
266
+ }
267
+ }
234
268
  /** Serialize refresh across tabs and atomically commit rotation; reload makes a fresh runtime key. */
235
269
  async resume(install) {
236
270
  if (!install && !this.#owner)
@@ -9,6 +9,8 @@ export type ProvisionedConnectionOptions = {
9
9
  trellisInstanceId: string;
10
10
  audienceNatsAccount: string;
11
11
  issuers: readonly AuthorityIssuerKey[];
12
+ /** Sentinel user JWT from the installation's metadata. */
13
+ natsSentinel: string;
12
14
  seed: string;
13
15
  timeout?: number;
14
16
  signal?: AbortSignal;
@@ -32,6 +34,8 @@ export declare function connectAdmitted(options: {
32
34
  audienceNatsAccount: string;
33
35
  issuers: readonly AuthorityIssuerKey[];
34
36
  rotationSequence?: string;
37
+ /** Sentinel user JWT from the installation's metadata. */
38
+ natsSentinel: string;
35
39
  auth: TrellisAuth;
36
40
  runtimeId: string;
37
41
  kind: "user" | "service" | "device";
@@ -261,6 +261,7 @@ export async function connectAdmitted(options) {
261
261
  const connect = await options.auth.natsConnectOptions({
262
262
  inboxPrefix,
263
263
  admission,
264
+ natsSentinel: options.natsSentinel,
264
265
  });
265
266
  const prepared = {
266
267
  policy,
@@ -484,6 +485,7 @@ export async function connectAdmitted(options) {
484
485
  const authOptions = await options.auth.natsConnectOptions({
485
486
  inboxPrefix,
486
487
  admission: credential,
488
+ natsSentinel: options.natsSentinel,
487
489
  });
488
490
  nc = await transport.connect({
489
491
  servers: options.servers,
@@ -26,6 +26,11 @@ export type TrellisAuth = {
26
26
  /** Fresh signed admission for this exact ephemeral key, never a refresh token. */
27
27
  admission: string | (() => string);
28
28
  authorizationUsable?: () => boolean;
29
+ /**
30
+ * The installation's sentinel user JWT. Presenting it hands the
31
+ * connection to Trellis's auth callout, which decides who connected.
32
+ */
33
+ natsSentinel: string;
29
34
  }) => Promise<NatsConnectOptions>;
30
35
  };
31
36
  export declare function createAuth(opts: {
@@ -43,6 +43,7 @@ export async function createAuth(opts) {
43
43
  return Promise.resolve({
44
44
  authenticator: [
45
45
  nkeyAuthenticator(encodedSeed),
46
+ () => ({ jwt: options.natsSentinel }),
46
47
  (nonce) => {
47
48
  if (options.authorizationUsable?.() === false) {
48
49
  throw new Error("authorization context is suspended");
package/caller.d.ts CHANGED
@@ -164,11 +164,22 @@ type OptionalResource<TContract extends GeneratedCaller> = {
164
164
  }[keyof CallerResources<TContract>];
165
165
  type ParticipantAvailability<TContract extends GeneratedCaller> = Readonly<{
166
166
  capabilities: Readonly<Record<OptionalCapability<TContract>, boolean>>;
167
+ /** Asked about and not approved; another ask takes the person's own action. */
168
+ declined: Readonly<Record<OptionalCapability<TContract>, boolean>>;
167
169
  resources: Readonly<Record<OptionalResource<TContract>, boolean>>;
168
170
  }>;
169
- /** Projects a private Trellis session into the selected flat caller vocabulary. */
171
+ /**
172
+ * Asks the user to approve optional capabilities an action needs, resolving
173
+ * true once the session holds them. Undefined when it can't ask.
174
+ */
175
+ export type CallerApproval = (capabilities: readonly string[]) => Promise<boolean> | undefined;
176
+ /**
177
+ * Projects a private Trellis session into the selected flat caller
178
+ * vocabulary. `asked` lists the optional capabilities the user has been
179
+ * asked about, which availability reports as declined while unheld.
180
+ */
170
181
  export declare function createCallerRuntime<TContract extends GeneratedCaller>(session: object, contract: TContract, resources?: {
171
182
  kv?: object;
172
183
  store?: object;
173
- }): CallerRuntime<TContract>;
184
+ }, requestApproval?: CallerApproval, asked?: () => readonly string[]): CallerRuntime<TContract>;
174
185
  export {};
package/caller.js CHANGED
@@ -20,8 +20,12 @@ function isGroup(id) {
20
20
  const name = id.slice(id.lastIndexOf(":") + 1);
21
21
  return !name.includes(".") && name !== "public";
22
22
  }
23
- /** Projects a private Trellis session into the selected flat caller vocabulary. */
24
- export function createCallerRuntime(session, contract, resources = {}) {
23
+ /**
24
+ * Projects a private Trellis session into the selected flat caller
25
+ * vocabulary. `asked` lists the optional capabilities the user has been
26
+ * asked about, which availability reports as declined while unheld.
27
+ */
28
+ export function createCallerRuntime(session, contract, resources = {}, requestApproval, asked = () => []) {
25
29
  const runtime = session;
26
30
  const selections = getCallerRuntime(contract).actions;
27
31
  if (runtime.ownAuthority)
@@ -49,8 +53,13 @@ export function createCallerRuntime(session, contract, resources = {}) {
49
53
  allowed.action.direction === action.direction));
50
54
  }
51
55
  }
56
+ const askedAbout = new Set(asked());
52
57
  return {
53
58
  capabilities,
59
+ declined: Object.fromEntries(Object.entries(capabilities).map(([capability, held]) => [
60
+ capability,
61
+ !held && askedAbout.has(capability),
62
+ ])),
54
63
  resources: Object.fromEntries(Object.entries(installed.resources).map(([name, available]) => [
55
64
  name,
56
65
  snapshot !== undefined && available,
@@ -70,18 +79,27 @@ export function createCallerRuntime(session, contract, resources = {}) {
70
79
  };
71
80
  for (const action of selections) {
72
81
  const unavailable = () => selectedActionAvailabilityError(runtime.connection, action);
82
+ // An action needing an optional capability the user hasn't approved asks
83
+ // for it when the app has a way to, then runs once the session holds it.
84
+ // Nothing was sent before the ask, so running it then is not a retry.
85
+ const available = (run) => {
86
+ const error = unavailable();
87
+ if (!error)
88
+ return run();
89
+ const asked = requestApproval?.(action.optionalCapabilities);
90
+ if (!asked)
91
+ return AsyncResult.from(Promise.resolve(err(error)));
92
+ return AsyncResult.from(asked.then(async (granted) => granted && !unavailable() ? await run() : err(error)));
93
+ };
73
94
  switch (action.descriptor.kind) {
74
95
  case "rpc":
75
96
  {
76
- const request = (input, opts) => {
77
- const error = unavailable();
78
- if (error)
79
- return AsyncResult.from(Promise.resolve(err(error)));
97
+ const request = (input, opts) => available(() => {
80
98
  const response = runtime.request(action.name, input, opts);
81
99
  return action.descriptor.download
82
100
  ? AsyncResult.from(response.then(withReceiveGrant))
83
101
  : response;
84
- };
102
+ });
85
103
  if (action.descriptor.pagination === "cursor") {
86
104
  request.pages = (input, opts) => cursorPages(request, input, opts);
87
105
  request.items = (input, opts) => cursorItems(request, input, opts);
@@ -98,34 +116,19 @@ export function createCallerRuntime(session, contract, resources = {}) {
98
116
  }
99
117
  break;
100
118
  case "live":
101
- caller[action.connectedName] = (input, opts) => {
102
- const error = unavailable();
103
- return error
104
- ? AsyncResult.from(Promise.resolve(err(error)))
105
- : runtime.liveHandle(action.name).input(input).subscribe(opts);
106
- };
119
+ caller[action.connectedName] = (input, opts) => available(() => runtime.liveHandle(action.name).input(input).subscribe(opts));
107
120
  break;
108
121
  case "event":
109
122
  if (action.direction === "publish") {
110
- const publish = (event) => {
111
- const error = unavailable();
112
- return error
113
- ? AsyncResult.from(Promise.resolve(err(error)))
114
- : runtime.publish(action.name, event);
115
- };
123
+ const publish = (event) => available(() => runtime.publish(action.name, event));
116
124
  publish.prepare = (event) => runtime.prepare(action.name, event);
117
125
  caller[action.connectedName] = publish;
118
126
  }
119
127
  else {
120
- caller[action.connectedName] = (handler, opts) => {
121
- const error = unavailable();
122
- return error
123
- ? AsyncResult.from(Promise.resolve(err(error)))
124
- : runtime.listenEvent(action.name, {}, async (event, context) => {
125
- await handler(event, context);
126
- return ok(undefined);
127
- }, opts);
128
- };
128
+ caller[action.connectedName] = (handler, opts) => available(() => runtime.listenEvent(action.name, {}, async (event, context) => {
129
+ await handler(event, context);
130
+ return ok(undefined);
131
+ }, opts));
129
132
  }
130
133
  break;
131
134
  }
@@ -14,6 +14,21 @@ export type ClientAuthOptions = {
14
14
  credentialHandle?: string;
15
15
  redirectTo: string;
16
16
  currentUrl?: string;
17
+ /**
18
+ * Ask the user to approve an optional capability when they use it: leave
19
+ * for the approval page and come back (`"redirect"`), or open it in a popup
20
+ * and carry on with the call once approved (`"popup"`). Only calls made in
21
+ * response to the user's click or key press ask; calls the app makes on its
22
+ * own, such as loading a page, fail with `ActionUnavailable`. Unset, no call
23
+ * asks. A blocked popup falls back to a redirect.
24
+ */
25
+ approval?: "redirect" | "popup";
26
+ /**
27
+ * On page load, ask about optional capabilities the app requests that the
28
+ * user has never been asked about, such as ones a new version added. Off,
29
+ * they are asked for when the app first uses them.
30
+ */
31
+ askForNewOptional?: boolean;
17
32
  };
18
33
  /** Required authorization redirect, returned to the application's own navigation owner. */
19
34
  export type ClientAuthRequiredContext = {
package/client_connect.js CHANGED
@@ -5,7 +5,7 @@ import { initializeProtocolWasm, verifyOAuthAdmissionWasm, } from "./auth/protoc
5
5
  import { utf8 } from "./auth/utils.js";
6
6
  import { observeTrellisConnection, transitionConnectionAvailability, } from "./connection.js";
7
7
  import { getCallerRuntime } from "./participant_runtime/participant.js";
8
- import { createCallerRuntime } from "./caller.js";
8
+ import { createCallerRuntime, } from "./caller.js";
9
9
  import { Trellis, } from "./session.js";
10
10
  import { AuthError } from "./errors/AuthError.js";
11
11
  import { TransportError } from "./errors/TransportError.js";
@@ -19,6 +19,14 @@ export function connectClientWithDeps(args, deps) {
19
19
  try {
20
20
  if (args.request.kind !== "browser")
21
21
  throw new AuthError({ reason: "InvalidCredential" });
22
+ // An approval popup ends on the app's callback. The window that opened
23
+ // it holds the continuation and reads the outcome; this one only
24
+ // reports where it landed.
25
+ const landed = new URL(args.auth.currentUrl ?? location.href);
26
+ if (landed.searchParams.has("state") && sameOriginOpener()) {
27
+ window.opener.postMessage({ type: APPROVAL_MESSAGE, href: landed.href }, location.origin);
28
+ return Result.err(new AuthError({ reason: "OAuthApprovalWindow" }));
29
+ }
22
30
  await initializeProtocolWasm();
23
31
  const opened = (await BrowserOAuthClient.open({
24
32
  issuer: args.trellisUrl,
@@ -40,6 +48,7 @@ export function connectClientWithDeps(args, deps) {
40
48
  audienceNatsAccount: admission.trust.account,
41
49
  issuers: [admission.trust.issuer],
42
50
  rotationSequence: admission.trust.rotationSequence,
51
+ natsSentinel: admission.metadata.trellis.natsSentinel,
43
52
  auth: admission.auth,
44
53
  runtimeId: admission.runtimeId,
45
54
  kind: "user",
@@ -86,13 +95,55 @@ export function connectClientWithDeps(args, deps) {
86
95
  const callback = currentUrl.searchParams.has("state") &&
87
96
  (currentUrl.searchParams.has("code") ||
88
97
  currentUrl.searchParams.has("error"));
89
- const resumed = callback
98
+ // A grant keeps the capabilities approved for it, so refreshing one
99
+ // that lacks a capability the app now requires never adds it. Such a
100
+ // grant is revoked and the user approves again; the approval screen
101
+ // keeps their earlier choices and asks only about what is new.
102
+ let outdated = false;
103
+ let unseen = [];
104
+ // The optional capabilities the user was shown when approving this grant.
105
+ let grantAsked = [];
106
+ const install = async (admission) => {
107
+ const details = admission.authorizationDetails;
108
+ const granted = details?.flatMap((detail) => detail.required);
109
+ outdated =
110
+ granted !== undefined &&
111
+ 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;
115
+ grantAsked = requested ?? [];
116
+ if (!outdated && args.auth.askForNewOptional && requested) {
117
+ const asked = new Set([...requested, ...askedOptional(oauth)]);
118
+ unseen = args.request.optionalCapabilities.filter((capability) => !asked.has(capability));
119
+ }
120
+ if (!outdated && unseen.length === 0)
121
+ await connectOAuth(admission);
122
+ };
123
+ let resumed = callback
90
124
  ? (await oauth.complete(currentUrl.href)).take()
91
- : (await oauth.resume(connectOAuth)).take();
92
- if (isErr(resumed)) {
125
+ : (await oauth.resume(install)).take();
126
+ // Declining more leaves the app as it was, on the grant already approved.
127
+ if (callback &&
128
+ isErr(resumed) &&
129
+ resumed.error.reason === "OAuthAuthorizationDenied") {
130
+ const kept = (await oauth.resume(install)).take();
131
+ if (!isErr(kept))
132
+ resumed = kept;
133
+ }
134
+ if (!isErr(resumed) && outdated) {
135
+ const revoked = await oauth.revoke();
136
+ if (revoked.isErr())
137
+ return Result.err(revoked.error);
138
+ }
139
+ if (isErr(resumed) || outdated || unseen.length > 0) {
93
140
  await connected?.manager.close();
94
- if (resumed.error.reason !== "OAuthRecoveryRequired")
141
+ if (isErr(resumed) &&
142
+ resumed.error.reason !== "OAuthRecoveryRequired")
95
143
  return Result.err(resumed.error);
144
+ // Asked once: declining leaves them unapproved without asking again.
145
+ if (unseen.length > 0)
146
+ rememberAsked(oauth, unseen);
96
147
  const authorization = (await oauth.authorize(args.auth.redirectTo, {
97
148
  required: args.request.requiredCapabilities,
98
149
  optional: args.request.optionalCapabilities,
@@ -180,7 +231,75 @@ export function connectClientWithDeps(args, deps) {
180
231
  await ownAuthority.refresh();
181
232
  if (!ownAuthority.current)
182
233
  throw new AuthError({ reason: "Unavailable" });
183
- return Result.ok(Object.assign(createCallerRuntime(trellis, args.request), {
234
+ const request = {
235
+ required: args.request.requiredCapabilities,
236
+ optional: args.request.optionalCapabilities,
237
+ };
238
+ const redirectForApproval = async () => {
239
+ const url = (await oauth.authorize(args.auth.redirectTo, request)).take();
240
+ if (isErr(url))
241
+ return;
242
+ if (args.onAuthRequired)
243
+ await args.onAuthRequired({ loginUrl: url, mode: "browser" });
244
+ else
245
+ location.assign(url);
246
+ };
247
+ // The popup widens this session's own grant, so the live
248
+ // connection renews into the approved capabilities in place.
249
+ const approveInPopup = async (popup) => {
250
+ try {
251
+ const lease = activeConnection.owner.own();
252
+ const grant = lease.authority.oauthGrantId;
253
+ lease.release();
254
+ if (!grant)
255
+ return false;
256
+ const url = (await oauth.authorize(args.auth.redirectTo, request, {
257
+ extendGrant: grant,
258
+ })).take();
259
+ if (isErr(url))
260
+ return false;
261
+ popup.location.href = url;
262
+ const landed = await approvalCallback(popup, new URL(args.auth.redirectTo).pathname);
263
+ if (!landed)
264
+ return false;
265
+ const approved = oauth.approvalOutcome(landed).take();
266
+ if (isErr(approved) || !approved)
267
+ return false;
268
+ await activeConnection.refreshAuthority();
269
+ await ownAuthority.refresh();
270
+ return true;
271
+ }
272
+ catch {
273
+ return false;
274
+ }
275
+ finally {
276
+ popup.close();
277
+ }
278
+ };
279
+ let asking;
280
+ const requestApproval = (capabilities) => {
281
+ // Only a person's action asks. A call the app makes by itself
282
+ // would ask again on every load, even for a capability the user
283
+ // can never hold.
284
+ if (!args.auth.approval || !navigator.userActivation?.isActive)
285
+ return undefined;
286
+ if (asking)
287
+ return asking;
288
+ // A popup only opens in the same turn as the user's action.
289
+ const popup = args.auth.approval === "popup"
290
+ ? window.open("about:blank", APPROVAL_MESSAGE, POPUP_FEATURES)
291
+ : null;
292
+ rememberAsked(oauth, [...capabilities]);
293
+ if (!popup) {
294
+ void redirectForApproval();
295
+ return Promise.resolve(false);
296
+ }
297
+ asking = approveInPopup(popup).finally(() => {
298
+ asking = undefined;
299
+ });
300
+ return asking;
301
+ };
302
+ return Result.ok(Object.assign(createCallerRuntime(trellis, args.request, {}, requestApproval, () => [...grantAsked, ...askedOptional(oauth)]), {
184
303
  ownAuthority,
185
304
  async logout(options) {
186
305
  const revoked = await oauth.revoke();
@@ -217,3 +336,83 @@ export class TrellisClient {
217
336
  return connectClient(args);
218
337
  }
219
338
  }
339
+ /** Names the approval popup and the message it sends its opener. */
340
+ const APPROVAL_MESSAGE = "trellis.approval";
341
+ const POPUP_FEATURES = "popup,width=520,height=720";
342
+ /** Whether this window was opened by another window of this app's origin. */
343
+ function sameOriginOpener() {
344
+ try {
345
+ return (window.opener !== null &&
346
+ window.opener !== window &&
347
+ window.opener.location.origin === location.origin);
348
+ }
349
+ catch {
350
+ return false;
351
+ }
352
+ }
353
+ /**
354
+ * Resolves with the app callback URL `popup` reaches, from its message or by
355
+ * watching it arrive, or undefined once the popup closes or the approval's
356
+ * ten minutes run out.
357
+ */
358
+ function approvalCallback(popup, path) {
359
+ return new Promise((resolve) => {
360
+ const deadline = Date.now() + 600_000;
361
+ const finish = (href) => {
362
+ clearInterval(timer);
363
+ removeEventListener("message", onMessage);
364
+ resolve(href);
365
+ };
366
+ const onMessage = (event) => {
367
+ const data = event.data;
368
+ if (event.source === popup &&
369
+ event.origin === location.origin &&
370
+ typeof data === "object" &&
371
+ data !== null &&
372
+ "type" in data &&
373
+ data.type === APPROVAL_MESSAGE &&
374
+ "href" in data &&
375
+ typeof data.href === "string")
376
+ finish(data.href);
377
+ };
378
+ addEventListener("message", onMessage);
379
+ const timer = setInterval(() => {
380
+ if (popup.closed || Date.now() > deadline)
381
+ return finish(undefined);
382
+ try {
383
+ const at = new URL(popup.location.href);
384
+ if (at.origin === location.origin &&
385
+ at.pathname === path &&
386
+ at.searchParams.has("state"))
387
+ finish(at.href);
388
+ }
389
+ catch {
390
+ // Still on the approval page, another origin.
391
+ }
392
+ }, 200);
393
+ });
394
+ }
395
+ /** Where this app remembers the optional capabilities it has asked about. */
396
+ function askedKey(oauth) {
397
+ const { issuer, clientId, credentialHandle } = oauth.scope;
398
+ return `trellis.askedOptional:${JSON.stringify([issuer, clientId, credentialHandle])}`;
399
+ }
400
+ function askedOptional(oauth) {
401
+ try {
402
+ const value = JSON.parse(localStorage.getItem(askedKey(oauth)) ?? "[]");
403
+ return Array.isArray(value)
404
+ ? value.filter((item) => typeof item === "string")
405
+ : [];
406
+ }
407
+ catch {
408
+ return [];
409
+ }
410
+ }
411
+ function rememberAsked(oauth, asked) {
412
+ try {
413
+ localStorage.setItem(askedKey(oauth), JSON.stringify([...new Set([...askedOptional(oauth), ...asked])]));
414
+ }
415
+ catch {
416
+ // Without storage the app asks again on its next load.
417
+ }
418
+ }
package/connection.d.ts CHANGED
@@ -72,9 +72,14 @@ export type TrellisConnectionLifecycleLogOptions = {
72
72
  log: LoggerLike;
73
73
  context: Record<string, unknown>;
74
74
  };
75
- /** Immutable installed availability for optional participant surfaces. */
75
+ /**
76
+ * Immutable installed availability for optional participant surfaces.
77
+ * `declined` marks each optional capability the user was asked about and
78
+ * didn't approve; asking again takes the person's own action, such as a click.
79
+ */
76
80
  export type TrellisAvailability = Readonly<{
77
81
  capabilities: Readonly<Record<string, boolean>>;
82
+ declined: Readonly<Record<string, boolean>>;
78
83
  resources: Readonly<Record<string, boolean>>;
79
84
  }>;
80
85
  declare const installAvailability: unique symbol;
package/connection.js CHANGED
@@ -3,6 +3,7 @@ import { LiveSessionManager } from "./live/manager.js";
3
3
  import { trackConnection } from "./telemetry/lifecycle.js";
4
4
  const EMPTY_AVAILABILITY = Object.freeze({
5
5
  capabilities: Object.freeze({}),
6
+ declined: Object.freeze({}),
6
7
  resources: Object.freeze({}),
7
8
  });
8
9
  const installAvailability = Symbol("installAvailability");
@@ -28,6 +29,7 @@ export function startConnectionTelemetry(kind) {
28
29
  function immutableAvailability(availability) {
29
30
  return Object.freeze({
30
31
  capabilities: Object.freeze({ ...availability.capabilities }),
32
+ declined: Object.freeze({ ...availability.declined }),
31
33
  resources: Object.freeze({ ...availability.resources }),
32
34
  });
33
35
  }
@@ -221,6 +221,8 @@ export type UsersCreateInput = Types0.AuthUserCreateRequest;
221
221
  export type UsersCreateOutput = Types0.AuthUserGetResponse;
222
222
  export type UsersDeleteInput = Types0.AuthUserDeleteRequest;
223
223
  export type UsersDeleteOutput = Types0.AuthMutationResult;
224
+ export type UsersFindInput = Types0.AuthUserFindRequest;
225
+ export type UsersFindOutput = Types0.AuthUserFindResponse;
224
226
  export type UsersGetInput = Types0.AuthUserGetRequest;
225
227
  export type UsersGetOutput = Types0.AuthUserGetResponse;
226
228
  export type UsersIdentityLinkCreateInput = Types0.AuthIdentityLinkCreateRequest;
@@ -1146,6 +1148,16 @@ declare const __api: {
1146
1148
  readonly download: false;
1147
1149
  readonly pagination: undefined;
1148
1150
  };
1151
+ readonly "rpc:Users.Find": {
1152
+ readonly kind: "rpc";
1153
+ readonly descriptorName: "rpc:Users.Find";
1154
+ readonly subject: "rpc.v1.auth.Users.Find";
1155
+ readonly input: typeof Types0.AuthUserFindRequestCodec;
1156
+ readonly output: typeof Types0.AuthUserFindResponseCodec;
1157
+ readonly errors: readonly [typeof AuthError, typeof UnexpectedError, typeof ValidationError];
1158
+ readonly download: false;
1159
+ readonly pagination: undefined;
1160
+ };
1149
1161
  readonly "rpc:Users.Get": {
1150
1162
  readonly kind: "rpc";
1151
1163
  readonly descriptorName: "rpc:Users.Get";
@@ -1272,5 +1284,5 @@ declare const __api: {
1272
1284
  readonly packageEvidence: unknown;
1273
1285
  };
1274
1286
  export declare const API: typeof __api;
1275
- export declare const API_DIGEST: "q4mGqO6Iv7Gh1OQpvhRVYEXqsNecVXpHIIiTzlmCWok";
1287
+ export declare const API_DIGEST: "Yf8elMDpll_uQ3ryrAechnp3ofe6TonR4Wymn0_3s-k";
1276
1288
  export {};