@jini-ai/agent-plugins 0.4.7 → 0.4.8
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/CHANGELOG.md +21 -0
- package/README.md +46 -0
- package/dist/admin-surfaces/action-dispatcher.d.ts +37 -0
- package/dist/admin-surfaces/action-dispatcher.js +69 -0
- package/dist/admin-surfaces/action-schema.d.ts +56 -0
- package/dist/admin-surfaces/action-schema.js +167 -0
- package/dist/admin-surfaces/action-tools.d.ts +40 -0
- package/dist/admin-surfaces/action-tools.js +52 -0
- package/dist/admin-surfaces/callback-field-inbox.d.ts +35 -0
- package/dist/admin-surfaces/callback-field-inbox.js +53 -0
- package/dist/admin-surfaces/capability-declarations.d.ts +41 -0
- package/dist/admin-surfaces/capability-declarations.js +102 -0
- package/dist/admin-surfaces/contribution.d.ts +49 -0
- package/dist/admin-surfaces/contribution.js +30 -0
- package/dist/admin-surfaces/delivery-bindings.d.ts +76 -0
- package/dist/admin-surfaces/delivery-bindings.js +99 -0
- package/dist/admin-surfaces/descriptor.d.ts +69 -0
- package/dist/admin-surfaces/descriptor.js +196 -0
- package/dist/admin-surfaces/external-links.d.ts +45 -0
- package/dist/admin-surfaces/external-links.js +70 -0
- package/dist/admin-surfaces/host-validator.d.ts +62 -0
- package/dist/admin-surfaces/host-validator.js +87 -0
- package/dist/admin-surfaces/index.d.ts +23 -0
- package/dist/admin-surfaces/index.js +21 -0
- package/dist/admin-surfaces/protocol.d.ts +103 -0
- package/dist/admin-surfaces/protocol.js +25 -0
- package/dist/admin-surfaces/sandbox.d.ts +78 -0
- package/dist/admin-surfaces/sandbox.js +92 -0
- package/dist/admin-surfaces/settings-value.d.ts +28 -0
- package/dist/admin-surfaces/settings-value.js +45 -0
- package/dist/admin-surfaces/surface-capabilities.d.ts +167 -0
- package/dist/admin-surfaces/surface-capabilities.js +215 -0
- package/dist/admin-surfaces/surface-client.d.ts +116 -0
- package/dist/admin-surfaces/surface-client.js +219 -0
- package/dist/admin-surfaces/surface-handlers.d.ts +111 -0
- package/dist/admin-surfaces/surface-handlers.js +172 -0
- package/dist/admin-surfaces/theme.d.ts +59 -0
- package/dist/admin-surfaces/theme.js +57 -0
- package/dist/folder-zip-node.js +59 -49
- package/dist/folder-zip.js +9 -7
- package/dist/lifecycle/automatic-use.d.ts +79 -0
- package/dist/lifecycle/automatic-use.js +165 -0
- package/dist/lifecycle/compatibility-metadata.d.ts +19 -0
- package/dist/lifecycle/compatibility-metadata.js +45 -0
- package/dist/lifecycle/compatibility.d.ts +52 -0
- package/dist/lifecycle/compatibility.js +60 -0
- package/dist/lifecycle/fetch-archive.js +26 -24
- package/dist/lifecycle/index.d.ts +14 -2
- package/dist/lifecycle/index.js +8 -1
- package/dist/lifecycle/install.js +7 -0
- package/dist/lifecycle/installed-package-index.js +41 -29
- package/dist/lifecycle/installed-package-roots.js +28 -20
- package/dist/lifecycle/manifest.d.ts +13 -0
- package/dist/lifecycle/manifest.js +115 -101
- package/dist/lifecycle/package-paths.js +3 -3
- package/dist/lifecycle/ports.d.ts +1 -1
- package/dist/lifecycle/provider-contribution.d.ts +65 -0
- package/dist/lifecycle/provider-contribution.js +93 -0
- package/dist/lifecycle/resolve-agent-plugin-refs.js +15 -2
- package/dist/lifecycle/retire-bundled.js +20 -18
- package/dist/lifecycle/search.d.ts +6 -1
- package/dist/lifecycle/search.js +45 -7
- package/dist/lifecycle/set-enabled.d.ts +2 -1
- package/dist/lifecycle/set-enabled.js +52 -8
- package/dist/lifecycle/skill-file-reader.js +85 -71
- package/dist/lifecycle/tools/capabilities.d.ts +199 -0
- package/dist/lifecycle/tools/capabilities.js +213 -0
- package/dist/lifecycle/tools/definition.d.ts +32 -0
- package/dist/lifecycle/tools/definition.js +33 -0
- package/dist/lifecycle/tools/index.d.ts +10 -0
- package/dist/lifecycle/tools/index.js +10 -0
- package/dist/lifecycle/tools/manifest.d.ts +33 -0
- package/dist/lifecycle/tools/manifest.js +89 -0
- package/dist/lifecycle/tools/projection.d.ts +90 -0
- package/dist/lifecycle/tools/projection.js +283 -0
- package/dist/lifecycle/types.d.ts +2 -0
- package/dist/lifecycle/uninstall.d.ts +3 -1
- package/dist/lifecycle/uninstall.js +51 -27
- package/dist/lifecycle/update-plan.d.ts +18 -0
- package/dist/lifecycle/update-plan.js +22 -0
- package/dist/lifecycle/update-store.d.ts +71 -0
- package/dist/lifecycle/update-store.js +150 -0
- package/dist/lifecycle/update.d.ts +55 -0
- package/dist/lifecycle/update.js +321 -0
- package/package.json +38 -6
- package/ui-ux-design/plugin.json +7 -2
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file The one check every plugin-written settings value passes before a host stores it: plugin
|
|
3
|
+
* state (`./surface-capabilities.ts`) and a delivery binding's config (`./delivery-bindings.ts`).
|
|
4
|
+
*
|
|
5
|
+
* Why it is shared: both are plugin-chosen JSON the host persists and later hands back (to the
|
|
6
|
+
* plugin's tools, or to the delivery adapter), so both need the same guarantees — plain JSON only,
|
|
7
|
+
* bounded depth and size, and never a token the plugin obtained — and must not drift apart.
|
|
8
|
+
*/
|
|
9
|
+
import { PLUGIN_STATE_MAX_KEY_LENGTH } from '../lifecycle/tools/capabilities.js';
|
|
10
|
+
export const ADMIN_SURFACE_STATE_LIMITS = Object.freeze({ maxKeyLength: PLUGIN_STATE_MAX_KEY_LENGTH, maxValueBytes: 16 * 1024, maxDepth: 16 });
|
|
11
|
+
export const STATE_CREDENTIAL_MESSAGE = 'The plugin tried to save a connection credential in its settings; nothing was saved.';
|
|
12
|
+
function isStateScalar(value) {
|
|
13
|
+
return value === null || typeof value === 'string' || typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value));
|
|
14
|
+
}
|
|
15
|
+
/** True for plain JSON data only: no undefined, functions, NaN, class instances or deep nesting. @complexity O(n) nodes. */
|
|
16
|
+
function isStateValue(value, depth) {
|
|
17
|
+
if (isStateScalar(value))
|
|
18
|
+
return true;
|
|
19
|
+
if (typeof value !== 'object' || depth >= ADMIN_SURFACE_STATE_LIMITS.maxDepth)
|
|
20
|
+
return false;
|
|
21
|
+
if (Array.isArray(value))
|
|
22
|
+
return value.every((item) => isStateValue(item, depth + 1));
|
|
23
|
+
const prototype = Object.getPrototypeOf(value);
|
|
24
|
+
return (prototype === Object.prototype || prototype === null) && Object.values(value).every((item) => isStateValue(item, depth + 1));
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* The value the host stores: serialized once, scanned and size-checked on that text, then parsed
|
|
28
|
+
* back, so what is stored is exactly what was checked (the plugin cannot change it afterwards).
|
|
29
|
+
* @param required.gate - The call's capability gate (its token memory drives the scan).
|
|
30
|
+
* @param required.value - The plugin's value, unchecked.
|
|
31
|
+
* @throws Error when the value is not plain JSON, is too large, or mentions an obtained token.
|
|
32
|
+
* @complexity O(n) in the serialized size.
|
|
33
|
+
*/
|
|
34
|
+
export function storedStateValue(required, _optional = {}) {
|
|
35
|
+
const { gate, value } = required;
|
|
36
|
+
if (!isStateValue(value, 0))
|
|
37
|
+
throw new Error('A settings value must be plain JSON data (no undefined, functions, NaN or class instances).');
|
|
38
|
+
const text = JSON.stringify(value);
|
|
39
|
+
if (new TextEncoder().encode(text).byteLength > ADMIN_SURFACE_STATE_LIMITS.maxValueBytes)
|
|
40
|
+
throw new Error(`A settings value may be at most ${ADMIN_SURFACE_STATE_LIMITS.maxValueBytes} bytes of JSON.`);
|
|
41
|
+
if (gate.mentionsToken({ value: text }))
|
|
42
|
+
throw new Error(STATE_CREDENTIAL_MESSAGE);
|
|
43
|
+
return JSON.parse(text);
|
|
44
|
+
}
|
|
45
|
+
//# sourceMappingURL=settings-value.js.map
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file The host capability ports a plugin's admin-surface handlers receive, and the per-call
|
|
3
|
+
* session that wraps them. Jini defines the shapes and the checks; the host implements the ports
|
|
4
|
+
* (connections backed by its API-connection service, state by its own store, public config by its
|
|
5
|
+
* own settings) and Jini never names a provider.
|
|
6
|
+
*
|
|
7
|
+
* Why surfaces get more than tools: account actions (connect, reconnect, switch account, disconnect)
|
|
8
|
+
* and saving a chosen resource are admin actions a person takes on a settings screen, so they exist
|
|
9
|
+
* here and never on the executable-tool port. Why every check sits here and not only in the host:
|
|
10
|
+
* the surfaces file is the shipped, digest-checked allowlist, so the session refuses anything the
|
|
11
|
+
* surface did not declare (a connection, a start parameter, a callback field, a config name) before
|
|
12
|
+
* the host sees it, and a host that answers with more than the port promises (a connection ref, raw
|
|
13
|
+
* scopes, undeclared callback fields) is cut back to the declared shape. Like the tool session it
|
|
14
|
+
* revokes everything once the plugin is disabled and withholds results and errors that mention a
|
|
15
|
+
* token the plugin obtained (in this call, an earlier one, or one of its tools); it also refuses to persist
|
|
16
|
+
* such a token in plugin state.
|
|
17
|
+
*/
|
|
18
|
+
import { type AgentPluginStateReader, type AgentPluginStateValue, type AgentPluginToolCapabilities, type AgentPluginToolCapabilityScope, type IssuedTokenMemory } from '../lifecycle/tools/capabilities.js';
|
|
19
|
+
import type { AdminSurfaceCapabilityDeclarations } from './capability-declarations.js';
|
|
20
|
+
import { type AdminSurfaceDeliveryBindings } from './delivery-bindings.js';
|
|
21
|
+
export { ADMIN_SURFACE_STATE_LIMITS, STATE_CREDENTIAL_MESSAGE } from './settings-value.js';
|
|
22
|
+
/** Mirrors the API-connection lifecycle (`ApiConnectionStatus`); only `connected` serves access tokens. */
|
|
23
|
+
export type AdminSurfaceConnectionState = 'connected' | 'reconnect-required' | 'revocation-pending' | 'disconnected';
|
|
24
|
+
/**
|
|
25
|
+
* The API-connection start intent each account action maps to (`ApiConnectionIntent` in
|
|
26
|
+
* `@jini-ai/integrations/api-connections`, mirrored because agent-plugins does not depend on it), so a
|
|
27
|
+
* host passes `ADMIN_SURFACE_ACTION_INTENTS[action]` straight to `start`. `reconnect` and `add-scopes`
|
|
28
|
+
* are a same-account `connect` with the scope sets the handler passes (`add-scopes` re-consents for
|
|
29
|
+
* more of them); `switch` stages another account.
|
|
30
|
+
*/
|
|
31
|
+
export declare const ADMIN_SURFACE_ACTION_INTENTS: Readonly<{
|
|
32
|
+
readonly connect: "connect";
|
|
33
|
+
readonly reconnect: "connect";
|
|
34
|
+
readonly switch: "switch-account";
|
|
35
|
+
readonly 'add-scopes': "connect";
|
|
36
|
+
}>;
|
|
37
|
+
export type AdminSurfaceConnectionAction = keyof typeof ADMIN_SURFACE_ACTION_INTENTS;
|
|
38
|
+
/**
|
|
39
|
+
* The honest remote outcome of a disconnect, the same values as `ApiConnectionRemoteRevocation`:
|
|
40
|
+
* never `confirmed` unless the provider confirmed it.
|
|
41
|
+
*/
|
|
42
|
+
export type AdminSurfaceRevocationOutcome = 'confirmed' | 'pending' | 'not-needed';
|
|
43
|
+
/** Token-free status. Scope sets are the plugin's own ids, never raw provider scopes. */
|
|
44
|
+
export interface AdminSurfaceConnectionStatus {
|
|
45
|
+
readonly connectionId: string;
|
|
46
|
+
readonly status: AdminSurfaceConnectionState;
|
|
47
|
+
readonly accountLabel: string | null;
|
|
48
|
+
readonly grantedScopeSetIds: readonly string[];
|
|
49
|
+
/** The account a staged switch would move to, awaiting `confirmSwitch`. */
|
|
50
|
+
readonly pendingSwitchAccountLabel: string | null;
|
|
51
|
+
/** Why the latest sign-in did not complete and what to do next, as the HOST's own lowercase
|
|
52
|
+
* hyphenated codes (for example `access-denied` / `reconnect`), never provider text; `null` when
|
|
53
|
+
* the latest attempt succeeded or none is recorded. A value that is not a safe code becomes `null`. */
|
|
54
|
+
readonly lastSignInAttempt: AdminSurfaceSignInAttempt | null;
|
|
55
|
+
}
|
|
56
|
+
/** The outcome codes of a sign-in attempt that did not complete. */
|
|
57
|
+
export interface AdminSurfaceSignInAttempt {
|
|
58
|
+
readonly code: string;
|
|
59
|
+
readonly nextAction: string;
|
|
60
|
+
}
|
|
61
|
+
/** A sign-in the person opens (a button on hosted, the system browser on desktop). */
|
|
62
|
+
export interface AdminSurfaceAuthorizationStart {
|
|
63
|
+
readonly authorizationUrl: string;
|
|
64
|
+
/** Opaque id for `takeCallbackFields` once the sign-in completed: the connection service's attempt
|
|
65
|
+
* id, never the authorization `state`. */
|
|
66
|
+
readonly attemptId: string;
|
|
67
|
+
readonly expiresAt: string;
|
|
68
|
+
}
|
|
69
|
+
export interface AdminSurfaceConnections {
|
|
70
|
+
/** A fresh access token for one of the surface's declared connections; never a refresh token. */
|
|
71
|
+
getAccessToken(required: {
|
|
72
|
+
readonly connectionId: string;
|
|
73
|
+
}, optional?: Record<string, never>): Promise<string>;
|
|
74
|
+
status(required: {
|
|
75
|
+
readonly connectionId: string;
|
|
76
|
+
}, optional?: Record<string, never>): Promise<AdminSurfaceConnectionStatus>;
|
|
77
|
+
begin(required: {
|
|
78
|
+
readonly connectionId: string;
|
|
79
|
+
readonly action: AdminSurfaceConnectionAction;
|
|
80
|
+
}, optional?: {
|
|
81
|
+
readonly scopeSetIds?: readonly string[];
|
|
82
|
+
readonly startParams?: Readonly<Record<string, string>>;
|
|
83
|
+
}): Promise<AdminSurfaceAuthorizationStart>;
|
|
84
|
+
confirmSwitch(required: {
|
|
85
|
+
readonly connectionId: string;
|
|
86
|
+
}, optional?: Record<string, never>): Promise<AdminSurfaceConnectionStatus>;
|
|
87
|
+
cancelSwitch(required: {
|
|
88
|
+
readonly connectionId: string;
|
|
89
|
+
}, optional?: Record<string, never>): Promise<AdminSurfaceConnectionStatus>;
|
|
90
|
+
disconnect(required: {
|
|
91
|
+
readonly connectionId: string;
|
|
92
|
+
}, optional?: Record<string, never>): Promise<AdminSurfaceConnectionStatus & {
|
|
93
|
+
readonly revocation: AdminSurfaceRevocationOutcome;
|
|
94
|
+
}>;
|
|
95
|
+
/** The declared callback fields of a completed sign-in, once; `null` when absent, taken or not completed.
|
|
96
|
+
* Still untrusted: verify them through the provider's API before saving anything. */
|
|
97
|
+
takeCallbackFields(required: {
|
|
98
|
+
readonly connectionId: string;
|
|
99
|
+
readonly attemptId: string;
|
|
100
|
+
}, optional?: Record<string, never>): Promise<Readonly<Record<string, string>> | null>;
|
|
101
|
+
}
|
|
102
|
+
export type AdminSurfaceStateValue = AgentPluginStateValue;
|
|
103
|
+
/** Plugin- and workspace-scoped JSON values (the host keys them by the session's scope). The plugin's
|
|
104
|
+
* tools read the same store through the read-only `AgentPluginStateReader`; only surfaces write. */
|
|
105
|
+
export interface AdminSurfaceState extends AgentPluginStateReader {
|
|
106
|
+
set(required: {
|
|
107
|
+
readonly key: string;
|
|
108
|
+
readonly value: AdminSurfaceStateValue;
|
|
109
|
+
}, optional?: Record<string, never>): Promise<void>;
|
|
110
|
+
delete(required: {
|
|
111
|
+
readonly key: string;
|
|
112
|
+
}, optional?: Record<string, never>): Promise<void>;
|
|
113
|
+
}
|
|
114
|
+
/** Host-supplied public values (an app id, a browser key) for names the surface declares; `null` when unset. */
|
|
115
|
+
export interface AdminSurfacePublicConfig {
|
|
116
|
+
get(required: {
|
|
117
|
+
readonly name: string;
|
|
118
|
+
}, optional?: Record<string, never>): Promise<string | null>;
|
|
119
|
+
}
|
|
120
|
+
/** Only form identity and display text, never fields, recipients or submission data. */
|
|
121
|
+
export interface AdminSurfaceForm {
|
|
122
|
+
readonly slug: string;
|
|
123
|
+
readonly title: string;
|
|
124
|
+
}
|
|
125
|
+
/** Workspace-scoped discovery. The session returns at most 200 choices; titles are capped at 1024 characters. */
|
|
126
|
+
export interface AdminSurfaceForms {
|
|
127
|
+
list(required: Record<string, never>, optional?: Record<string, never>): Promise<readonly AdminSurfaceForm[]>;
|
|
128
|
+
}
|
|
129
|
+
export type AdminSurfaceCapabilities = Pick<AgentPluginToolCapabilities, 'http' | 'limiter' | 'artifacts'> & {
|
|
130
|
+
readonly connections: AdminSurfaceConnections;
|
|
131
|
+
readonly state: AdminSurfaceState;
|
|
132
|
+
readonly publicConfig: AdminSurfacePublicConfig;
|
|
133
|
+
/** The workspace's form-delivery bindings (`./delivery-bindings.ts`). Optional for the host; a handler
|
|
134
|
+
* gets it only when its surface declares `deliveryAdapters` and the host provides it. */
|
|
135
|
+
readonly deliveryBindings?: AdminSurfaceDeliveryBindings;
|
|
136
|
+
/** Absent unless both the host supplies it and this surface declares `forms: ["list"]`. */
|
|
137
|
+
readonly forms?: AdminSurfaceForms;
|
|
138
|
+
};
|
|
139
|
+
/** Host port: builds one call's capabilities for the loaded plugin, workspace and admin principal. */
|
|
140
|
+
export type AdminSurfaceCapabilitiesPort = (required: AgentPluginToolCapabilityScope, optional?: Record<string, never>) => AdminSurfaceCapabilities;
|
|
141
|
+
/**
|
|
142
|
+
* Opens the capability session for one admin-surface handler call.
|
|
143
|
+
* @param required.capabilities - The host's ports for this call (already scoped to plugin, workspace, principal).
|
|
144
|
+
* @param required.isLive - False once the plugin's surface handlers are revoked.
|
|
145
|
+
* @param required.declared - The surface's own capability declarations (the allowlists).
|
|
146
|
+
* @param required.issued - The plugin's token memory, shared by all its calls (tools included).
|
|
147
|
+
* @param optional.actorId - The signed-in admin; account actions are refused without one.
|
|
148
|
+
* @returns Wrapped capabilities plus the shared `release` (result) and `sanitize` (error) gates.
|
|
149
|
+
* @complexity O(1) to open; each check is bounded by the declared lists and the value caps.
|
|
150
|
+
*/
|
|
151
|
+
export declare function openAdminSurfaceCapabilitySession(required: {
|
|
152
|
+
readonly capabilities: AdminSurfaceCapabilities;
|
|
153
|
+
readonly isLive: () => boolean;
|
|
154
|
+
readonly declared: AdminSurfaceCapabilityDeclarations;
|
|
155
|
+
readonly issued: IssuedTokenMemory;
|
|
156
|
+
}, optional?: {
|
|
157
|
+
readonly actorId?: string;
|
|
158
|
+
}): {
|
|
159
|
+
capabilities: AdminSurfaceCapabilities;
|
|
160
|
+
release: <T>({ value }: {
|
|
161
|
+
readonly value: T;
|
|
162
|
+
}) => T;
|
|
163
|
+
sanitize: ({ error }: {
|
|
164
|
+
readonly error: unknown;
|
|
165
|
+
}) => unknown;
|
|
166
|
+
};
|
|
167
|
+
//# sourceMappingURL=surface-capabilities.d.ts.map
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file The host capability ports a plugin's admin-surface handlers receive, and the per-call
|
|
3
|
+
* session that wraps them. Jini defines the shapes and the checks; the host implements the ports
|
|
4
|
+
* (connections backed by its API-connection service, state by its own store, public config by its
|
|
5
|
+
* own settings) and Jini never names a provider.
|
|
6
|
+
*
|
|
7
|
+
* Why surfaces get more than tools: account actions (connect, reconnect, switch account, disconnect)
|
|
8
|
+
* and saving a chosen resource are admin actions a person takes on a settings screen, so they exist
|
|
9
|
+
* here and never on the executable-tool port. Why every check sits here and not only in the host:
|
|
10
|
+
* the surfaces file is the shipped, digest-checked allowlist, so the session refuses anything the
|
|
11
|
+
* surface did not declare (a connection, a start parameter, a callback field, a config name) before
|
|
12
|
+
* the host sees it, and a host that answers with more than the port promises (a connection ref, raw
|
|
13
|
+
* scopes, undeclared callback fields) is cut back to the declared shape. Like the tool session it
|
|
14
|
+
* revokes everything once the plugin is disabled and withholds results and errors that mention a
|
|
15
|
+
* token the plugin obtained (in this call, an earlier one, or one of its tools); it also refuses to persist
|
|
16
|
+
* such a token in plugin state.
|
|
17
|
+
*/
|
|
18
|
+
import { checkedStateKey, guardSharedCapabilities, guardStateReader, openCapabilityGate, } from '../lifecycle/tools/capabilities.js';
|
|
19
|
+
import { guardDeliveryBindings } from './delivery-bindings.js';
|
|
20
|
+
import { storedStateValue } from './settings-value.js';
|
|
21
|
+
// Moved to `./settings-value.ts` so delivery-binding config shares the exact checks; re-exported so callers keep importing them here.
|
|
22
|
+
export { ADMIN_SURFACE_STATE_LIMITS, STATE_CREDENTIAL_MESSAGE } from './settings-value.js';
|
|
23
|
+
/**
|
|
24
|
+
* The API-connection start intent each account action maps to (`ApiConnectionIntent` in
|
|
25
|
+
* `@jini-ai/integrations/api-connections`, mirrored because agent-plugins does not depend on it), so a
|
|
26
|
+
* host passes `ADMIN_SURFACE_ACTION_INTENTS[action]` straight to `start`. `reconnect` and `add-scopes`
|
|
27
|
+
* are a same-account `connect` with the scope sets the handler passes (`add-scopes` re-consents for
|
|
28
|
+
* more of them); `switch` stages another account.
|
|
29
|
+
*/
|
|
30
|
+
export const ADMIN_SURFACE_ACTION_INTENTS = Object.freeze({
|
|
31
|
+
connect: 'connect', reconnect: 'connect', switch: 'switch-account', 'add-scopes': 'connect',
|
|
32
|
+
});
|
|
33
|
+
const ACTIONS = Object.keys(ADMIN_SURFACE_ACTION_INTENTS);
|
|
34
|
+
const SCOPE_SET_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
35
|
+
const ATTEMPT_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
|
|
36
|
+
const MAX_SCOPE_SETS = 16;
|
|
37
|
+
const MAX_START_PARAM_LENGTH = 2048;
|
|
38
|
+
/** Names in messages come from plugin code: cut them so a message stays a message. */
|
|
39
|
+
const named = (value) => String(value).slice(0, 64);
|
|
40
|
+
const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
41
|
+
function declaredConnection(declared, connectionId) {
|
|
42
|
+
const found = declared.find((connection) => connection.id === connectionId);
|
|
43
|
+
if (found === undefined)
|
|
44
|
+
throw new Error(`This admin surface does not declare connection '${named(connectionId)}', so its handlers cannot use it. Declare it in the surface's connections.`);
|
|
45
|
+
return found;
|
|
46
|
+
}
|
|
47
|
+
/** A copy of the start parameters, every name declared for this connection and every value a bounded string. @complexity O(p). */
|
|
48
|
+
function checkedStartParams(connection, startParams) {
|
|
49
|
+
if (!isRecord(startParams))
|
|
50
|
+
throw new Error('Start parameters must be an object of strings.');
|
|
51
|
+
for (const [name, value] of Object.entries(startParams)) {
|
|
52
|
+
if (!connection.startParams.includes(name))
|
|
53
|
+
throw new Error(`Start parameter '${named(name)}' is not declared for connection '${connection.id}' on this admin surface.`);
|
|
54
|
+
if (typeof value !== 'string' || value.length > MAX_START_PARAM_LENGTH)
|
|
55
|
+
throw new Error(`Start parameter '${name}' must be a string of at most ${MAX_START_PARAM_LENGTH} characters.`);
|
|
56
|
+
}
|
|
57
|
+
return { ...startParams };
|
|
58
|
+
}
|
|
59
|
+
function checkedScopeSetIds(scopeSetIds) {
|
|
60
|
+
const valid = Array.isArray(scopeSetIds) && scopeSetIds.length <= MAX_SCOPE_SETS && scopeSetIds.every((id) => typeof id === 'string' && SCOPE_SET_ID_PATTERN.test(id));
|
|
61
|
+
if (!valid)
|
|
62
|
+
throw new Error(`Scope sets must be at most ${MAX_SCOPE_SETS} short ids.`);
|
|
63
|
+
return [...scopeSetIds];
|
|
64
|
+
}
|
|
65
|
+
/** The begin options the host receives: only the ones the handler passed, checked and copied. */
|
|
66
|
+
function beginOptions(connection, optional = {}) {
|
|
67
|
+
return {
|
|
68
|
+
...(optional.scopeSetIds !== undefined && { scopeSetIds: checkedScopeSetIds(optional.scopeSetIds) }),
|
|
69
|
+
...(optional.startParams !== undefined && { startParams: checkedStartParams(connection, optional.startParams) }),
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
const SAFE_CODE_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
73
|
+
const MAX_SAFE_CODE_LENGTH = 64;
|
|
74
|
+
const isSafeCode = (value) => typeof value === 'string' && value.length <= MAX_SAFE_CODE_LENGTH && SAFE_CODE_PATTERN.test(value);
|
|
75
|
+
/** Only `code` and `nextAction`, and only when both are safe codes: a host that forwarded provider
|
|
76
|
+
* text (an error description) by mistake must not put it in front of the person or the plugin. */
|
|
77
|
+
function toSignInAttempt(attempt) {
|
|
78
|
+
if (typeof attempt !== 'object' || attempt === null)
|
|
79
|
+
return null;
|
|
80
|
+
const { code, nextAction } = attempt;
|
|
81
|
+
return isSafeCode(code) && isSafeCode(nextAction) ? { code, nextAction } : null;
|
|
82
|
+
}
|
|
83
|
+
/** The status shape the port promises, whatever else the host's object carried. */
|
|
84
|
+
function toStatus(connectionId, status) {
|
|
85
|
+
return {
|
|
86
|
+
connectionId, status: status.status, accountLabel: status.accountLabel ?? null,
|
|
87
|
+
grantedScopeSetIds: [...status.grantedScopeSetIds], pendingSwitchAccountLabel: status.pendingSwitchAccountLabel ?? null,
|
|
88
|
+
lastSignInAttempt: toSignInAttempt(status.lastSignInAttempt),
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
/** Only this connection's declared callback fields, as strings; anything else the host returned is dropped. */
|
|
92
|
+
function declaredCallbackFields(connection, fields) {
|
|
93
|
+
if (fields === null)
|
|
94
|
+
return null;
|
|
95
|
+
return Object.fromEntries(connection.callbackFields.filter((name) => typeof fields[name] === 'string').map((name) => [name, fields[name]]));
|
|
96
|
+
}
|
|
97
|
+
/** Account actions run for a person; a call without one (a background route) is refused. */
|
|
98
|
+
function requireActor(actorId) {
|
|
99
|
+
if (actorId === undefined)
|
|
100
|
+
throw new Error('Account actions need a signed-in admin. Open the surface from an authenticated admin page and retry.');
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* A token is handed out (to a handler, and through bootstrap data to the frame) only for a signed-in
|
|
104
|
+
* admin: a route without one must not mint a bearer token a frame keeps until it expires. Disabling
|
|
105
|
+
* the plugin cannot recall a token already handed out; disconnecting revokes it at the provider.
|
|
106
|
+
*/
|
|
107
|
+
function requireTokenActor(actorId) {
|
|
108
|
+
if (actorId === undefined)
|
|
109
|
+
throw new Error('Connection access needs a signed-in admin. Open the surface from an authenticated admin page and retry.');
|
|
110
|
+
}
|
|
111
|
+
/** The read side: a token (noted for the scans) and token-free status. */
|
|
112
|
+
function readConnections({ gate, host, declared, actorId }) {
|
|
113
|
+
return {
|
|
114
|
+
getAccessToken: gate.guard(async ({ connectionId }) => {
|
|
115
|
+
const { id } = declaredConnection(declared, connectionId);
|
|
116
|
+
requireTokenActor(actorId);
|
|
117
|
+
return gate.noteToken({ token: await host.getAccessToken({ connectionId: id }) });
|
|
118
|
+
}),
|
|
119
|
+
status: gate.guard(async ({ connectionId }) => {
|
|
120
|
+
const { id } = declaredConnection(declared, connectionId);
|
|
121
|
+
return toStatus(id, await host.status({ connectionId: id }));
|
|
122
|
+
}),
|
|
123
|
+
takeCallbackFields: gate.guard(async ({ connectionId, attemptId }) => {
|
|
124
|
+
const connection = declaredConnection(declared, connectionId);
|
|
125
|
+
if (typeof attemptId !== 'string' || !ATTEMPT_ID_PATTERN.test(attemptId))
|
|
126
|
+
throw new Error('The sign-in attempt id is not valid; start the sign-in again.');
|
|
127
|
+
return declaredCallbackFields(connection, await host.takeCallbackFields({ connectionId: connection.id, attemptId }));
|
|
128
|
+
}),
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
/** The account actions: declared connection, declared start parameters, a signed-in admin. */
|
|
132
|
+
function actConnections({ gate, host, declared, actorId }) {
|
|
133
|
+
const forActor = (connectionId) => { requireActor(actorId); return declaredConnection(declared, connectionId); };
|
|
134
|
+
const statusAction = (run) => gate.guard(async ({ connectionId }) => {
|
|
135
|
+
const { id } = forActor(connectionId);
|
|
136
|
+
return toStatus(id, await run({ connectionId: id }));
|
|
137
|
+
});
|
|
138
|
+
return {
|
|
139
|
+
begin: gate.guard(async ({ connectionId, action }, optional) => {
|
|
140
|
+
const connection = forActor(connectionId);
|
|
141
|
+
if (!ACTIONS.includes(action))
|
|
142
|
+
throw new Error(`Account action '${named(action)}' is not one of ${ACTIONS.join(', ')}.`);
|
|
143
|
+
const started = await host.begin({ connectionId: connection.id, action }, beginOptions(connection, optional));
|
|
144
|
+
return { authorizationUrl: started.authorizationUrl, attemptId: started.attemptId, expiresAt: started.expiresAt };
|
|
145
|
+
}),
|
|
146
|
+
confirmSwitch: statusAction((input) => host.confirmSwitch(input)),
|
|
147
|
+
cancelSwitch: statusAction((input) => host.cancelSwitch(input)),
|
|
148
|
+
disconnect: gate.guard(async ({ connectionId }) => {
|
|
149
|
+
const { id } = forActor(connectionId);
|
|
150
|
+
const outcome = await host.disconnect({ connectionId: id });
|
|
151
|
+
return { ...toStatus(id, outcome), revocation: outcome.revocation };
|
|
152
|
+
}),
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
function guardState(gate, host) {
|
|
156
|
+
return Object.freeze({
|
|
157
|
+
...guardStateReader({ gate, state: host }),
|
|
158
|
+
set: gate.guard(async ({ key, value }) => host.set({ key: checkedStateKey({ key }), value: storedStateValue({ gate, value }) })),
|
|
159
|
+
delete: gate.guard(({ key }) => host.delete({ key: checkedStateKey({ key }) })),
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
function guardPublicConfig(gate, host, declared) {
|
|
163
|
+
return Object.freeze({
|
|
164
|
+
get: gate.guard(async ({ name }) => {
|
|
165
|
+
if (!declared.includes(name))
|
|
166
|
+
throw new Error(`This admin surface does not declare public config '${named(name)}'. Declare it in the surface's publicConfig.`);
|
|
167
|
+
return host.get({ name });
|
|
168
|
+
}),
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
/** Read-only discovery shares revocation and actor checks with other surface-only ports. Unknown
|
|
172
|
+
* host fields never reach a handler; collection and string caps bound the disclosure.
|
|
173
|
+
* @complexity O(min(f, 200)) time/space for f host forms, one workspace read. */
|
|
174
|
+
function guardForms(required, optional = {}) {
|
|
175
|
+
const { gate, host } = required;
|
|
176
|
+
return Object.freeze({
|
|
177
|
+
list: gate.guard(async (_input, _options = {}) => {
|
|
178
|
+
requireActor(optional.actorId);
|
|
179
|
+
const forms = await host.list({});
|
|
180
|
+
return forms.slice(0, 200).map(({ slug, title }) => {
|
|
181
|
+
if (typeof slug !== 'string' || slug.length === 0 || slug.length > 64 || typeof title !== 'string')
|
|
182
|
+
throw new Error('The forms host returned an invalid form choice.');
|
|
183
|
+
return { slug, title: title.slice(0, 1024) };
|
|
184
|
+
});
|
|
185
|
+
}),
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Opens the capability session for one admin-surface handler call.
|
|
190
|
+
* @param required.capabilities - The host's ports for this call (already scoped to plugin, workspace, principal).
|
|
191
|
+
* @param required.isLive - False once the plugin's surface handlers are revoked.
|
|
192
|
+
* @param required.declared - The surface's own capability declarations (the allowlists).
|
|
193
|
+
* @param required.issued - The plugin's token memory, shared by all its calls (tools included).
|
|
194
|
+
* @param optional.actorId - The signed-in admin; account actions are refused without one.
|
|
195
|
+
* @returns Wrapped capabilities plus the shared `release` (result) and `sanitize` (error) gates.
|
|
196
|
+
* @complexity O(1) to open; each check is bounded by the declared lists and the value caps.
|
|
197
|
+
*/
|
|
198
|
+
export function openAdminSurfaceCapabilitySession(required, optional = {}) {
|
|
199
|
+
const { capabilities: host, isLive, declared, issued } = required;
|
|
200
|
+
const gate = openCapabilityGate({ isLive, issued });
|
|
201
|
+
const input = { gate, host: host.connections, declared: declared.connections ?? [], actorId: optional.actorId };
|
|
202
|
+
const { deliveryAdapters } = declared;
|
|
203
|
+
const deliveryBindings = deliveryAdapters === undefined || host.deliveryBindings === undefined ? undefined
|
|
204
|
+
: guardDeliveryBindings({ gate, host: host.deliveryBindings, adapterIds: deliveryAdapters, connectionIds: input.declared.map((connection) => connection.id) }, { actorId: optional.actorId });
|
|
205
|
+
const capabilities = Object.freeze({
|
|
206
|
+
...guardSharedCapabilities({ gate, host }),
|
|
207
|
+
connections: Object.freeze({ ...readConnections(input), ...actConnections(input) }),
|
|
208
|
+
state: guardState(gate, host.state),
|
|
209
|
+
publicConfig: guardPublicConfig(gate, host.publicConfig, declared.publicConfig ?? []),
|
|
210
|
+
...(deliveryBindings && { deliveryBindings }),
|
|
211
|
+
...(declared.forms?.includes('list') && host.forms !== undefined && { forms: guardForms({ gate, host: host.forms }, optional) }),
|
|
212
|
+
});
|
|
213
|
+
return { capabilities, release: gate.release, sanitize: gate.sanitize };
|
|
214
|
+
}
|
|
215
|
+
//# sourceMappingURL=surface-capabilities.js.map
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file The surface-side half of the admin-surface message protocol, for a plugin's own UI.
|
|
3
|
+
*
|
|
4
|
+
* Self-contained on purpose (no imports): a plugin's surface is plain static files, so it may import
|
|
5
|
+
* this module from the package or copy the compiled file next to its entry. The constants repeat
|
|
6
|
+
* `./protocol.ts`; the vertical-slice test proves the two still agree.
|
|
7
|
+
*
|
|
8
|
+
* Trust rules it applies: it accepts init only from its parent window (once), learns the host's
|
|
9
|
+
* origin from that init and posts only to that origin (never "*"), and accepts a response only from
|
|
10
|
+
* the parent, from that origin, for this mount, for a request it still has pending, in a valid shape.
|
|
11
|
+
*
|
|
12
|
+
* Theme: the host may send its design tokens with init and again in `theme` messages (`./theme.ts`).
|
|
13
|
+
* The client applies the `--jini-*` ones with a safe value as custom properties on the surface's root
|
|
14
|
+
* element (CSSOM `setProperty`, which a CSP without 'unsafe-inline' allows), plus `color-scheme` and
|
|
15
|
+
* `data-jini-scheme`, so the surface's own stylesheet can follow the admin's look and light/dark mode.
|
|
16
|
+
*/
|
|
17
|
+
/** The parts of `window.parent` the client uses. */
|
|
18
|
+
export interface AdminSurfaceParentPort {
|
|
19
|
+
postMessage(message: unknown, targetOrigin: string): void;
|
|
20
|
+
}
|
|
21
|
+
/** The fields of a `MessageEvent` the client reads. */
|
|
22
|
+
export interface AdminSurfaceIncomingMessage {
|
|
23
|
+
readonly origin: string;
|
|
24
|
+
readonly source: unknown;
|
|
25
|
+
readonly data: unknown;
|
|
26
|
+
}
|
|
27
|
+
/** Subscribes to `message` events; returns the unsubscribe function. */
|
|
28
|
+
export type AdminSurfaceListenPort = (handler: (event: AdminSurfaceIncomingMessage) => void) => () => void;
|
|
29
|
+
/** The element the host's tokens are applied to (in a browser, `document.documentElement`). */
|
|
30
|
+
export interface AdminSurfaceThemeRoot {
|
|
31
|
+
readonly style: {
|
|
32
|
+
setProperty(name: string, value: string): void;
|
|
33
|
+
removeProperty(name: string): void;
|
|
34
|
+
};
|
|
35
|
+
setAttribute(name: string, value: string): void;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Reports the surface's content height in CSS pixels whenever it may have changed; returns the stop
|
|
39
|
+
* function. The host sizes the frame to it, so a surface never scrolls inside the admin page.
|
|
40
|
+
*/
|
|
41
|
+
export type AdminSurfaceSizePort = (onHeight: (height: number) => void) => () => void;
|
|
42
|
+
/** The body element the default size source measures and listens on (in a browser, `document.body`). */
|
|
43
|
+
export interface AdminSurfaceSizedBody {
|
|
44
|
+
readonly scrollHeight: number;
|
|
45
|
+
getBoundingClientRect(): {
|
|
46
|
+
readonly height: number;
|
|
47
|
+
};
|
|
48
|
+
addEventListener(type: 'mouseover' | 'focusin', listener: () => void): void;
|
|
49
|
+
removeEventListener(type: 'mouseover' | 'focusin', listener: () => void): void;
|
|
50
|
+
}
|
|
51
|
+
/** An observer constructor the default size source re-measures from (Resize/MutationObserver). */
|
|
52
|
+
export type AdminSurfaceObserverConstructor = new (callback: () => void) => {
|
|
53
|
+
observe(target: AdminSurfaceSizedBody, options?: Readonly<Record<string, boolean>>): void;
|
|
54
|
+
disconnect(): void;
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* The browser globals the default theme root and size source read. Injectable so the defaults are
|
|
58
|
+
* testable without a DOM; `globalThis` is wired in at the client's composition edge.
|
|
59
|
+
*/
|
|
60
|
+
export interface AdminSurfaceBrowserScope {
|
|
61
|
+
readonly document?: {
|
|
62
|
+
readonly documentElement?: AdminSurfaceThemeRoot;
|
|
63
|
+
readonly body?: AdminSurfaceSizedBody | null;
|
|
64
|
+
};
|
|
65
|
+
readonly ResizeObserver?: AdminSurfaceObserverConstructor;
|
|
66
|
+
readonly MutationObserver?: AdminSurfaceObserverConstructor;
|
|
67
|
+
readonly getComputedStyle?: (element: AdminSurfaceSizedBody) => {
|
|
68
|
+
readonly marginTop: string;
|
|
69
|
+
readonly marginBottom: string;
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
/** The host's design tokens as the client accepted them. */
|
|
73
|
+
export interface AdminSurfaceClientTheme {
|
|
74
|
+
readonly scheme: 'light' | 'dark';
|
|
75
|
+
readonly tokens: Readonly<Record<string, string>>;
|
|
76
|
+
}
|
|
77
|
+
export interface AdminSurfaceClientFailure {
|
|
78
|
+
readonly code: string;
|
|
79
|
+
readonly message: string;
|
|
80
|
+
readonly retryable: boolean;
|
|
81
|
+
}
|
|
82
|
+
/** Rejection value of `call` when the host refused the action or the request timed out. */
|
|
83
|
+
export declare class AdminSurfaceCallError extends Error {
|
|
84
|
+
readonly code: string;
|
|
85
|
+
readonly retryable: boolean;
|
|
86
|
+
constructor(required: AdminSurfaceClientFailure);
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Connects a surface to its host. In a browser:
|
|
90
|
+
* `createAdminSurfaceClient({ parent: window.parent, listen: (h) => { addEventListener('message', h); return () => removeEventListener('message', h); } })`.
|
|
91
|
+
* @param optional.timeoutMs - How long `call` waits for a response before rejecting with `timeout`.
|
|
92
|
+
* @complexity O(1) per message.
|
|
93
|
+
*/
|
|
94
|
+
export declare function createAdminSurfaceClient(required: {
|
|
95
|
+
readonly parent: AdminSurfaceParentPort;
|
|
96
|
+
readonly listen: AdminSurfaceListenPort;
|
|
97
|
+
}, optional?: {
|
|
98
|
+
readonly timeoutMs?: number;
|
|
99
|
+
readonly nowMs?: () => number;
|
|
100
|
+
readonly themeRoot?: AdminSurfaceThemeRoot | null;
|
|
101
|
+
readonly size?: AdminSurfaceSizePort | null;
|
|
102
|
+
readonly browser?: AdminSurfaceBrowserScope;
|
|
103
|
+
}): {
|
|
104
|
+
ready: Promise<void>;
|
|
105
|
+
call: (input: {
|
|
106
|
+
readonly action: string;
|
|
107
|
+
readonly payload: unknown;
|
|
108
|
+
}) => Promise<unknown>;
|
|
109
|
+
openLink: (input: {
|
|
110
|
+
readonly url: string;
|
|
111
|
+
}) => Promise<void>;
|
|
112
|
+
bootstrap: () => unknown;
|
|
113
|
+
theme: () => AdminSurfaceClientTheme | undefined;
|
|
114
|
+
close: () => void;
|
|
115
|
+
};
|
|
116
|
+
//# sourceMappingURL=surface-client.d.ts.map
|