@oatscenter/trellis 0.100.0-rc.24 → 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.
- package/auth/browser/oauth.d.ts +16 -2
- package/auth/browser/oauth.js +36 -2
- package/auth/connection.d.ts +4 -0
- package/auth/connection.js +2 -0
- package/auth/session_auth.d.ts +5 -0
- package/auth/session_auth.js +1 -0
- package/caller.d.ts +13 -2
- package/caller.js +31 -28
- package/client_connect.d.ts +15 -0
- package/client_connect.js +205 -6
- package/connection.d.ts +6 -1
- package/connection.js +2 -0
- package/internal_sdk/generated/package.json +1 -1
- package/native/connection.d.ts +2 -0
- package/native/connection.js +6 -0
- package/native/discovery.d.ts +2 -0
- package/native/discovery.js +2 -0
- package/package.json +2 -2
- package/participant_runtime/participant.js +1 -0
- package/runtime_transport.js +8 -1
- package/service/runtime/service.js +1 -0
- package/transport/generations.js +13 -0
package/auth/browser/oauth.d.ts
CHANGED
|
@@ -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
|
-
/**
|
|
78
|
-
|
|
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. */
|
package/auth/browser/oauth.js
CHANGED
|
@@ -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
|
-
/**
|
|
148
|
-
|
|
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)
|
package/auth/connection.d.ts
CHANGED
|
@@ -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";
|
package/auth/connection.js
CHANGED
|
@@ -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,
|
package/auth/session_auth.d.ts
CHANGED
|
@@ -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: {
|
package/auth/session_auth.js
CHANGED
|
@@ -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
|
-
/**
|
|
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
|
-
/**
|
|
24
|
-
|
|
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
|
-
|
|
122
|
-
return
|
|
123
|
-
|
|
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
|
}
|
package/client_connect.d.ts
CHANGED
|
@@ -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
|
-
|
|
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(
|
|
92
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
/**
|
|
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
|
}
|
package/native/connection.d.ts
CHANGED
|
@@ -19,6 +19,8 @@ export type NativeSessionConnection = Awaited<ReturnType<typeof connectAdmitted>
|
|
|
19
19
|
export declare function connectNativeSession(options: ClientOpts & {
|
|
20
20
|
session: NativeOAuthSession;
|
|
21
21
|
servers: readonly string[];
|
|
22
|
+
/** Sentinel user JWT from discovery; read from the session's issuer when omitted. */
|
|
23
|
+
natsSentinel?: string;
|
|
22
24
|
}): AsyncResult<NativeSessionConnection, AuthError | TransportError | UnexpectedError>;
|
|
23
25
|
/** Native generated facade options. Application requests select local surfaces, never wire authorization. */
|
|
24
26
|
export type NativeClientConnectOptions<T extends AppRequestDescriptor> = ClientOpts & {
|
package/native/connection.js
CHANGED
|
@@ -9,6 +9,7 @@ import { Trellis, } from "../session.js";
|
|
|
9
9
|
import { observeTrellisConnection, transitionConnectionAvailability, } from "../connection.js";
|
|
10
10
|
import { AuthError } from "../errors/AuthError.js";
|
|
11
11
|
import { TransportError } from "../errors/TransportError.js";
|
|
12
|
+
import { discoverNativeOAuth } from "./discovery.js";
|
|
12
13
|
/** Connect a verified native OAuth session through the unchanged admission/authority/transport pipeline. Consumes session connection ownership. */
|
|
13
14
|
export function connectNativeSession(options) {
|
|
14
15
|
return AsyncResult.from((async () => {
|
|
@@ -19,12 +20,17 @@ export function connectNativeSession(options) {
|
|
|
19
20
|
custody = session.claimConnection();
|
|
20
21
|
let admission = session.admission;
|
|
21
22
|
const trust = session.trust;
|
|
23
|
+
const natsSentinel = options.natsSentinel ??
|
|
24
|
+
(await discoverNativeOAuth(session.scope.issuer, {
|
|
25
|
+
signal: options.signal,
|
|
26
|
+
})).orThrow().natsSentinel;
|
|
22
27
|
connected = await connectAdmitted({
|
|
23
28
|
servers: [...options.servers],
|
|
24
29
|
trellisInstanceId: trust.instanceId,
|
|
25
30
|
audienceNatsAccount: trust.account,
|
|
26
31
|
issuers: [trust.issuer],
|
|
27
32
|
rotationSequence: trust.rotationSequence,
|
|
33
|
+
natsSentinel,
|
|
28
34
|
auth: session.auth,
|
|
29
35
|
runtimeId: session.runtimeId,
|
|
30
36
|
kind: "user",
|
package/native/discovery.d.ts
CHANGED
|
@@ -7,6 +7,8 @@ export type NativeOAuthServer = Readonly<{
|
|
|
7
7
|
/** Native NATS addresses, or the WebSocket ones when the Trellis advertises only those. */
|
|
8
8
|
natsServers: readonly string[];
|
|
9
9
|
trust: RuntimeAuthorizationTrust;
|
|
10
|
+
/** Sentinel user JWT every connection presents so NATS hands it to Trellis's auth callout. */
|
|
11
|
+
natsSentinel: string;
|
|
10
12
|
/** The token endpoint's current DPoP nonce, when the issuer offers it, so the first token request needs no challenge. */
|
|
11
13
|
dpopNonce?: string;
|
|
12
14
|
}>;
|
package/native/discovery.js
CHANGED
|
@@ -26,6 +26,7 @@ const metadataSchema = z.object({
|
|
|
26
26
|
requiredAuthorizationDetailsTypes: z
|
|
27
27
|
.array(z.literal("trellis_capabilities"))
|
|
28
28
|
.min(1),
|
|
29
|
+
natsSentinel: z.string().min(1),
|
|
29
30
|
}),
|
|
30
31
|
});
|
|
31
32
|
/** RFC 9728 protected resource metadata, as the Console's address serves it. */
|
|
@@ -137,6 +138,7 @@ export async function discoverNativeOAuth(origin, options = {}) {
|
|
|
137
138
|
issuer: active[0],
|
|
138
139
|
rotationSequence: metadata.trellis.rotationSequence,
|
|
139
140
|
},
|
|
141
|
+
natsSentinel: metadata.trellis.natsSentinel,
|
|
140
142
|
...(dpopNonce ? { dpopNonce } : {}),
|
|
141
143
|
});
|
|
142
144
|
}
|
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.
|
|
54
|
+
"@oatscenter/result": "0.100.0-rc.25",
|
|
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.
|
|
74
|
+
"version": "0.100.0-rc.25",
|
|
75
75
|
"type": "module",
|
|
76
76
|
"license": "Apache-2.0",
|
|
77
77
|
"publishConfig": {
|
|
@@ -260,6 +260,7 @@ export function participantAvailability(participant, resourceBindings) {
|
|
|
260
260
|
}
|
|
261
261
|
return Object.freeze({
|
|
262
262
|
capabilities: Object.freeze(capabilities),
|
|
263
|
+
declined: Object.freeze(Object.fromEntries(Object.keys(capabilities).map((id) => [id, false]))),
|
|
263
264
|
resources: Object.freeze(resources),
|
|
264
265
|
});
|
|
265
266
|
}
|
package/runtime_transport.js
CHANGED
|
@@ -57,7 +57,14 @@ export async function loadDefaultRuntimeTransport() {
|
|
|
57
57
|
});
|
|
58
58
|
}
|
|
59
59
|
const { connect } = await import("@nats-io/transport-node");
|
|
60
|
-
const
|
|
60
|
+
const servers = Array.isArray(options.servers)
|
|
61
|
+
? options.servers
|
|
62
|
+
: [options.servers];
|
|
63
|
+
// Plain `nats://` stays plaintext: a development installation serves
|
|
64
|
+
// native NATS that way on loopback.
|
|
65
|
+
const ca = servers.some((server) => server?.startsWith("tls://"))
|
|
66
|
+
? acceptedIssuersFor(servers)
|
|
67
|
+
: undefined;
|
|
61
68
|
return await connect(ca ? { ...options, tls: { ca: ca.join("\n") } } : options);
|
|
62
69
|
},
|
|
63
70
|
};
|
|
@@ -1548,6 +1548,7 @@ export function connectTrellisServiceWithRuntimeDeps(args, deps) {
|
|
|
1548
1548
|
audienceNatsAccount: server.trust.account,
|
|
1549
1549
|
issuers: [server.trust.issuer],
|
|
1550
1550
|
rotationSequence: server.trust.rotationSequence,
|
|
1551
|
+
natsSentinel: server.natsSentinel,
|
|
1551
1552
|
seed: args.seed,
|
|
1552
1553
|
timeout: args.timeout,
|
|
1553
1554
|
signal: args.signal,
|
package/transport/generations.js
CHANGED
|
@@ -696,6 +696,7 @@ export class TransportGenerationManager {
|
|
|
696
696
|
#monitorGeneration(generation) {
|
|
697
697
|
const iterator = generation.nc.status()[Symbol.asyncIterator]();
|
|
698
698
|
void (async () => {
|
|
699
|
+
let reconnecting = false;
|
|
699
700
|
try {
|
|
700
701
|
while (true) {
|
|
701
702
|
const next = await iterator.next();
|
|
@@ -705,6 +706,18 @@ export class TransportGenerationManager {
|
|
|
705
706
|
listener(next.value);
|
|
706
707
|
const event = next.value;
|
|
707
708
|
const type = event?.type;
|
|
709
|
+
if (type === "disconnect" && reconnecting) {
|
|
710
|
+
// The broker dropped a reconnect attempt mid-handshake, as NATS
|
|
711
|
+
// does when an auth callout goes unanswered while Trellis is
|
|
712
|
+
// starting. nats.js keeps waiting on that attempt until its
|
|
713
|
+
// connect timeout, so a fresh generation recovers instead.
|
|
714
|
+
this.#closeGeneration(generation, "recovery");
|
|
715
|
+
continue;
|
|
716
|
+
}
|
|
717
|
+
if (type === "reconnecting")
|
|
718
|
+
reconnecting = true;
|
|
719
|
+
if (type === "reconnect")
|
|
720
|
+
reconnecting = false;
|
|
708
721
|
if (type === "disconnect" ||
|
|
709
722
|
type === "reconnecting" ||
|
|
710
723
|
type === "staleConnection" ||
|