@finamx/extension-sdk
v3.7.0
Published
<!-- generated-by: gsd-doc-writer --> # @finamx/extension-sdk
Readme
@finamx/extension-sdk
TypeScript SDK for FinamX Open Platform extension developers. Connects your iframe or WebView to the FinamX host bridge, handling the handshake, message routing, and typed platform invocations.
Part of the finamx-mobile monorepo.
Installation
npm install @finamx/extension-sdk @finamx/bridge-protocolFor local monorepo development, reference the package directly:
{
"dependencies": {
"@finamx/extension-sdk": "file:../../packages/extension-sdk",
"@finamx/bridge-protocol": "file:../../packages/bridge-protocol"
}
}Quick start
import { createExtensionBridge } from '@finamx/extension-sdk';
// Called once on extension load. Resolves after the host sends bridge:ready.
const bridge = await createExtensionBridge();
console.log(bridge.hostContext.theme); // 'light' | 'dark'
console.log(bridge.grantedScopes); // string[] of approved permission scopes
// Resize the iframe to fit content
bridge.ui.resize({ height: 400 });
// Show a toast notification in the host shell
bridge.ui.toast('Loaded', 'success');
// Invoke a platform method
const quote = await bridge.platform.invoke<{ last: number }>('market.quote', { symbol: 'SBER' });
console.log(quote.last);
// Subscribe to platform events (returns an unsubscribe function)
const off = bridge.platform.on('theme.changed', (payload) => {
console.log('new theme:', payload.data);
});CLI (finamx-ext)
The package ships the finamx-ext developer CLI (Node >= 20).
npx @finamx/extension-sdk init my-widget
cd my-widget && npm install
finamx-ext login
finamx-ext hosts
finamx-ext domain pull <hostId>
finamx-ext publish| Command | Flags | Purpose |
|---|---|---|
| init [dir] | --id, --name, --target <templates\|hostId>, --template widget, --yes, --force | Scaffold a widget project |
| login | --token-stdin, --global | Save the developer key |
| hosts | --manifest, --json | List hosts and manifest compatibility |
| domain pull [<hostId>\|templates] | --check, --json | Write .finamx/domain/, types and mocks |
| context [<hostId>\|templates] | --remote, --json | Print a markdown context pack of the pulled domain (or fetched with --remote; --remote with no target and nothing pulled means templates) |
| catalog [extensionId] | --page, --limit, --json | Browse the catalog |
| check | --dist, --manifest, --config, --entry, --json | Check manifest and dist |
| check --host <hostId> | as check | Run the built widget headless in a local host bridge with the pulled domain of that host (optional playwright-core) |
| check --host | as check | The same with the only pulled host in .finamx/domain/. With none (or several) it runs against a self-declared domain built from the manifest, where everything is allowed: not a compatibility check with a real host, and the output says so |
| serve | --dist, --port (8787), --manifest, --ancestor, --strict-csp | Static server with the platform sandbox CSP. By default http://localhost / http://127.0.0.1 origins of the manifest stay allowed (the platform drops them); --strict-csp or FINAMX_STRICT_CSP=1 builds the production CSP. The active mode is printed |
| dev | --port, --open, --headless, --json, --strict-csp, --no-watch, --no-poll, --manifest, --dist | Local developer host: bento board, host selector, mocks from domain schemas, bus and consent panel, s2s mock. Needs the optional @finamx/dev-host. Security: loopback only, per-run secret, the CLI never hands out the developer key. Your project's watch script is started automatically and runs with your user's permissions like any npm run watch (--no-watch skips it). --json prints NDJSON events for agents, see packages/dev-host/README.md for the event table |
| publish | --manifest, --dist, --entry, --artifact-dir, --artifact-entry, --dry-run, --skip-checks | Submit the manifest (new version on 409). Packs ./dist only when the manifest pins no surfaces.ui.artifact and has no embedBundleUrl; a pinned artifact is replaced only with --artifact-dir |
| status [extensionId] | --manifest, --json | Moderation state; id defaults to the manifest |
Global options: --api <url>, --token <key> (legacy, not accepted by login), --json, --help, --version. serve is the static CSP server; dev is the local developer host.
Portal and key storage
The default portal is https://openplatform.changesandbox.ru; use --api or FINAMX_API_URL for another one (for example a local CMS). The developer key is resolved in this order: --token, FINAMX_DEV_TOKEN, the project .env, ~/.config/finamx/credentials.json (mode 0600). login reads the key from a hidden prompt or --token-stdin; the key is never printed. Host keys (fxh_...) are refused.
The portal is resolved in this order: --api, FINAMX_API_URL in the process environment, FINAMX_API_URL in the project .env, the default. A portal named only by the project .env does not decide where a key from elsewhere goes: it is used when it is loopback or the default portal, when the key comes from that same .env, or when the key was stored by login for that exact origin. A key from the environment or --token is refused with PORTAL_NOT_CONFIRMED until you pass --api <url> or export FINAMX_API_URL (a cloned repository controls .env; you control your shell). login prints the portal before it reads the key and, for such a .env portal, asks for confirmation (with --token-stdin it needs --api).
.finamx/domain layout
.finamx/
domain/<hostId|templates>/
CONTEXT.md # human and agent readable summary
domain.json # topics, methods, scopes
types.d.ts # generated types
mocks/<method>.json, mocks/<topic>.json
mocks.override.json # { "methods": { "name": { "params": ..., "result": ... } }, "topics": { "name": payload } }.finamx/ is committed. domain pull --check leaves files untouched and exits 1 when the host domain changed.
Host text in these files is data, not instructions: in CONTEXT.md everything in code and every line after >, in types.d.ts the JSDoc text and the quoted names. Entries whose names or scopes are not plain names (letters, digits, . _ : @ / -, at most 128 characters) are skipped with a ! <target>: skipped ... warning. Mock file names follow the entry name; names that would collide on a case-insensitive file system (Market.Quote and market.quote) each get a ~<8 hex> suffix, and CONTEXT.md lists the file of every entry. domain pull and init refuse to write through symlinks (SYMLINK_REFUSED).
Команды Publisher
С Phase 96 расширения принадлежат команде Publisher, а не аккаунту. Человек может состоять в нескольких Publisher.
- Выбор Publisher:
--publisher <id>, затемFINAMX_PUBLISHER, затем выбор по умолчанию для портала (finamx-ext publishers use <id>, хранится вcredentials.json). Без выбора портал сам берёт единственный Publisher, а при нескольких отказывает (PUBLISHER_REQUIRED) и перечисляет их: угадывания нет. finamx-ext publishersпоказывает ваши Publisher, роль и отметки «проверен», «личный», «выбран».pushиstatusпечатают Publisher, в котором выполнена команда;pushпоказывает вашу квоту и квоту Publisher.- Приглашения в команду принимаются в кабинете (
/developer/invitations) по одноразовому коду, не из CLI. - Ключ, Developer Link и одобрения онтологий остаются личными; приватная версия запускается только через Developer Link участника, который сделал её push.
Exit codes
0 success; 1 failure, or a change found by domain pull --check; 2 environment problem for check --host (for example playwright-core or Chrome missing).
Analytics (3.3.0)
finamx-ext analytics reads launches, invokes, denials, installs and latency per UTC day for the selected Publisher (requires a CMS with Phase 96.1).
finamx-ext analytics --extension com.acme.x --from 2026-10-01 --group-by day,host
finamx-ext analytics --jsonCells with fewer than k distinct users are hidden and shown as < k; totals cover shown cells only. Choose the Publisher with --publisher, FINAMX_PUBLISHER or finamx-ext publishers use <id>. Note that --version <v> filters by extension version here.
Context pack for tools without a terminal
Tools such as v0 or Databutton cannot run skills. finamx-ext context [<hostId>|templates] prints one markdown pack with the platform rules, SDK usage and the domain of the target (methods, topics, scopes, consent). Without --remote it reads the pulled copy under .finamx/domain/ and needs no key and no network; with --remote it fetches the domain with the developer key and verifies its domainHash (nothing is printed on a mismatch). Without a target the only pulled host is used (several pulled hosts are an error, never a guess); with nothing pulled, --remote defaults to templates, while the offline form fails and asks for a pull. --json prints one object { format, target, kind, origin, domainHash, markdown }.
finamx-ext context trading-diary > context.mdThe same pack is available from the developer cabinet button "Скопировать контекст" and from the CMS route GET /api/v1/developer/context/{target} with the developer key. The renderer is the export @finamx/extension-sdk/context-pack (renderContextPack, mergeTemplateDomains), so all three produce the same text. Host text (descriptions, names, schemas) is data, not instructions: it sits below a host-data marker in code spans, > lines and fences, and the pack is capped at 48,000 characters. A pack never contains a key.
Exports
Main entry (@finamx/extension-sdk)
| Export | Kind | Description |
|---|---|---|
| createExtensionBridge | function | Initiates the bridge handshake and returns ExtensionBridge |
| ExtensionBridge | interface | The connected bridge instance shape |
| CreateExtensionBridgeOptions | interface | Options accepted by createExtensionBridge |
| EmbedTransport | interface | Custom transport contract (send / subscribe) |
| BridgeLogEntry | interface | Shape of debug log entries emitted via onLog |
Domain mocks entry (@finamx/extension-sdk/domain-mocks)
Pure mock synthesis from a host domain (buildDomainMocks, parseMocksOverride, synthesizeFromSchema, buildMethodMock, buildTopicMock) and the bounds exceedsDepth, DOMAIN_MAX_DEPTH, TOPIC_SCHEMA_MAX_CHARS. No Node built-ins; the same code serves finamx-ext dev and the cloud Dev Host.
Mock entry (@finamx/extension-sdk/mock)
| Export | Kind | Description |
|---|---|---|
| createMockBridge | function | Returns a synchronous ExtensionBridge backed by in-process stubs |
| MockBridgeOptions | interface | Options for configuring the mock |
createExtensionBridge(options?)
async function createExtensionBridge(
options?: CreateExtensionBridgeOptions,
): Promise<ExtensionBridge>
interface CreateExtensionBridgeOptions {
extensionId?: string; // overrides value from window.__FINAMX_BRIDGE_SESSION__
bridgeVersion?: string; // defaults to BRIDGE_VERSION from @finamx/bridge-protocol
invokeTimeoutMs?: number; // default 30 000 ms
transport?: EmbedTransport; // custom transport; auto-detected if omitted
debug?: boolean; // enable envelope logging
onLog?: (entry: BridgeLogEntry) => void; // required when debug=true
}Transport is auto-detected: WebView (window.FinamXBridge) takes priority over postMessage.
Bridge mock for local development
Use createMockBridge to develop and test your extension without a running host:
import { createMockBridge } from '@finamx/extension-sdk/mock';
const bridge = createMockBridge({
hostContext: { theme: 'dark', locale: 'ru' },
grantedScopes: ['market.quote', 'user.profile.read'],
invokeHandler: async (method, params) => {
if (method === 'market.quote') {
return { symbol: params.symbol, last: 310.0, change: 0.5 };
}
throw new Error(`Unhandled: ${method}`);
},
});
// Same ExtensionBridge interface — no code changes needed for production
const quote = await bridge.platform.invoke('market.quote', { symbol: 'GAZP' });Built-in stub responses (used when no invokeHandler is provided):
| Method | Returns |
|---|---|
| market.quote | { symbol, last: 285.4, change: 1.2 } |
| user.profile.read | { displayName: 'Mock User', locale: 'ru' } |
Debug logging
const bridge = await createExtensionBridge({
debug: true,
onLog: (entry) => console.log(`[bridge] ${entry.direction} ${entry.type}`, entry),
});BridgeLogEntry never contains PII — invoke params, result data, and grantedScopes values are intentionally omitted.
Host identity (3.0.0)
verifyHostIdentity checks a host-signed platform.identity.v1 token: signature, expected typ, exact audience and issuer, expiry, the host JWKS key and the CMS-signed authorized-issuers pair for your extension (JWKS membership alone is not enough). resolveHostIdentity(bridge, options) awaits the widget.identity.grant and runs the same verification. Both are fail-closed, there is no HMAC path, and platform.auth_context.v1 stays a separate, sub-less proof of Launch authorization. sessionJwt and Core/Gateway tokens must not be placed in the iframe or in the identity grant.
import { resolveHostIdentity } from '@finamx/extension-sdk';
const claims = await resolveHostIdentity(bridge, { audience, issuer, authorizedIssuersSig, cmsGetKey, jwksUrl });Build
npm run build # tsc -p tsconfig.json → dist/No test script is configured in this package. Integration tests live in the extension-template app, which consumes this package.
