From 831518b01a0f7dbe41efe375a7aa118d036622f5 Mon Sep 17 00:00:00 2001 From: "Paul K." Date: Thu, 19 Nov 2026 21:58:02 -0500 Subject: [PATCH] feat(relay): look up a platform's --metadata keys instead of a hardcoded table (v2.17.0) `one relay metadata ` reads the setup fields One already stores per platform (GET /v1/webhooks/relay/config/{connectorId}, the list the dashboard's Configuration step shows) and prints each key with its label, whether it's required, and whether it's a secret. A secret field's placeholder is never repeated. `relay create --create-webhook` checks the required keys before calling the API. When one is missing it returns `status: "metadata_required"` with the missing fields, exits 1, and creates nothing. Before, the endpoint was created, the webhook never registered, and only a warning said why. When the field list can't be read, or One stores none for the platform, create goes ahead as before. The 49-row metadata table in the skill and `one guide relay` is gone; both now point at the command. README and --help updated. Co-Authored-By: Claude Opus 5.5 --- README.md | 3 +- package-lock.json | 4 +- package.json | 2 +- skills/one/references/relay.md | 69 +++-------- src/cli.ts | 11 +- src/commands/relay-metadata.test.ts | 172 ++++++++++++++++++++++++++++ src/commands/relay.ts | 151 ++++++++++++++++++++++-- src/lib/api.ts | 25 ++++ src/lib/guide-content.ts | 67 ++--------- src/lib/types.ts | 17 +++ 10 files changed, 395 insertions(+), 126 deletions(-) create mode 100644 src/commands/relay-metadata.test.ts diff --git a/README.md b/README.md index dcefbb8..344f408 100644 --- a/README.md +++ b/README.md @@ -552,6 +552,7 @@ Receive webhooks from platforms and forward them to any connected platform via p ```bash one relay platforms # List relay-capable platforms + event type counts one relay event-types # List supported event types for a platform +one relay metadata # List the --metadata keys the platform needs on create one relay create --connection-key --create-webhook --event-filters '["event.type"]' one relay activate --actions '' # Attach passthrough forwarding actions (agent mode: add --confirm-write for actions that write) one relay list # List existing relay endpoints @@ -559,7 +560,7 @@ one relay events --platform

# Inspect received events one relay deliveries --endpoint-id # Check delivery status ``` -Start with `one relay platforms` to discover which platforms support relay at all, then drill into `event-types ` for the specific events. Run `one guide relay` for the full reference including `--metadata` requirements per platform. +Start with `one relay platforms` to discover which platforms support relay at all, then drill into `event-types ` for the specific events and `metadata ` for the `--metadata` keys it needs. With `--create-webhook`, `relay create` refuses to create anything while a required key is missing. Run `one guide relay` for the full reference. ### `one skills` diff --git a/package-lock.json b/package-lock.json index 372fc5b..e8a723d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@withone/cli", - "version": "2.16.2", + "version": "2.17.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@withone/cli", - "version": "2.16.2", + "version": "2.17.0", "dependencies": { "@clack/prompts": "^0.9.1", "commander": "^13.1.0", diff --git a/package.json b/package.json index 18043fe..5793746 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@withone/cli", - "version": "2.16.2", + "version": "2.17.0", "description": "CLI for managing One", "type": "module", "files": [ diff --git a/skills/one/references/relay.md b/skills/one/references/relay.md index 6d687cf..8d39b0f 100644 --- a/skills/one/references/relay.md +++ b/skills/one/references/relay.md @@ -59,61 +59,17 @@ Always use `--create-webhook` — it registers the webhook URL with the source p **One relay per source connection.** All relays on a connection share one hosted URL and one signing secret, and a second `--create-webhook` replaces the stored secret. If the connection already has a relay, add your actions to it with `relay update --actions` (pass the full list; it replaces) instead of creating another. -**Many source platforms require extra identifiers via `--metadata`** (ask the user for the values). Every platform not listed (Stripe, Linear, Attio, Google Calendar, ...) needs none. Keys are case-sensitive; a missing one doesn't fail `create`, but the webhook isn't registered and the `warning` names the key. +**Check what `--metadata` the source platform needs first:** -| Platform | Required metadata keys | -|---|---| -| `airtable` | `AIRTABLE_DATABASE_ID` | -| `apify` | `APIFY_ACTOR_ID` or `APIFY_ACTOR_TASK_ID` | -| `asana` | `ASANA_RESOURCE_GID` | -| `autodesk` | `AUTODESK_SYSTEM`, `AUTODESK_SCOPE` (an object) | -| `basin` | `BASIN_FORM_ID` (a number) | -| `bookingmood` | `BOOKINGMOOD_ORGANIZATION_ID` | -| `box` | `BOX_TARGET_ID`, `BOX_TARGET_TYPE` | -| `brevo` | `BREVO_DOMAIN`, only when `BREVO_TYPE` is `inbound` | -| `browse-ai` | `BROWSE_AI_ROBOT_ID` | -| `btcpay-server` | `BTCPAY_SERVER_STORE_ID` | -| `calendly` | `CALENDLY_ORGANIZATION`, plus `CALENDLY_USER` or `CALENDLY_GROUP` for a user or group `CALENDLY_SCOPE` | -| `chargebee` | `CHARGEBEE_WEBHOOK_NAME` | -| `click-up` | `CLICK_UP_TEAM_ID` | -| `clockify` | `CLOCKIFY_WORKSPACE_ID`, `CLOCKIFY_WEBHOOK_NAME`, `CLOCKIFY_TRIGGER_SOURCE_TYPE`, `CLOCKIFY_TRIGGER_SOURCE` (a list) | -| `cloudinary` | `CLOUDINARY_SIGNING_SECRET` | -| `contentful-content-management` | `CONTENTFUL_CONTENT_MANAGEMENT_SPACE_ID` | -| `crowdin` | `CROWDIN_PROJECT_ID` | -| `datadog` | `DATADOG_WEBHOOK_NAME` | -| `doppler-secretops` | `DOPPLER_SECRETOPS_PROJECT`, `DOPPLER_SECRETOPS_CONFIGS` (a list) | -| `fathom` | `FATHOM_TRIGGERED_FOR` | -| `figma` | `FIGMA_CONTEXT`, `FIGMA_CONTEXT_ID` | -| `files-com` | `FILES_COM_PATH` | -| `fillout` | `FILLOUT_FORM_ID` | -| `formbricks` | `FORMBRICKS_ENVIRONMENT_ID` | -| `git-lab` | `GIT_LAB_PROJECT_ID` | -| `github` | `GITHUB_OWNER`, `GITHUB_REPOSITORY` | -| `grist` | `GRIST_DOC_ID`, `GRIST_TABLE_ID` | -| `heyy` | `HEYY_TENANT_ID` | -| `hugging-face` | `HUGGING_FACE_WATCHED` | -| `jira` | `jqlFilter` | -| `launchdarkly` | `LAUNCHDARKLY_RESOURCES` (a list) | -| `loyverse` | `LOYVERSE_MERCHANT_ID` | -| `mailchimp-marketing` | `MAILCHIMP_MARKETING_LIST_ID` | -| `mailersend` | `MAILERSEND_DOMAIN_ID` | -| `monday` | `MONDAY_BOARD_ID` | -| `paradym` | `PARADYM_PROJECT_ID`, `PARADYM_WEBHOOK_NAME` | -| `parseur` | `PARSEUR_MAILBOX_ID`, `PARSEUR_WEBHOOK_NAME` | -| `posthog` | `POSTHOG_PROJECT_ID`, `POSTHOG_WEBHOOK_NAME` | -| `productive` | `PRODUCTIVE_ORGANIZATION_ID` | -| `sanity` | `SANITY_PROJECT_ID`, `SANITY_DATASET` | -| `sentry` | `SENTRY_ORGANIZATION_ID_OR_SLUG`, `SENTRY_PROJECT_ID_OR_SLUG` | -| `storyblok` | `STORYBLOK_SPACE_ID` | -| `tally` | `TALLY_FORM_ID` | -| `toggl-track` | `TOGGL_TRACK_WORKSPACE_ID` | -| `trello` | `TRELLO_MODEL_ID` | -| `typeform` | `TYPEFORM_FORM_ID` | -| `webflow` | `WEBFLOW_SITE_ID` | -| `workable` | `WORKABLE_ACCOUNT_ID`, only for `candidate_*` events | -| `workiom` | `WORKIOM_APP_ID`, `WORKIOM_LIST_ID` | - -Some platforms also take optional keys (e.g. `GOOGLE_CALENDAR_CALENDAR_ID`, which defaults to the primary calendar). Example for GitHub: +```bash +one --agent relay metadata +``` + +It returns `{platform, fields: [{key, label, required, secret, placeholder?}]}`: the keys One lists for registering that platform's webhook (the same list the dashboard's setup form shows). Ask the user for the values and pass them as one JSON object in `--metadata`. Keys are case-sensitive. A `secret` field is a credential: ask the user for it, and never use the placeholder as a value. An empty `fields` list means One lists none; most such platforms need none. + +With `--create-webhook`, `relay create` checks the required keys first. If any is missing it returns `"status": "metadata_required"` with the `missing` fields, exits 1 and creates nothing. A key the list doesn't name can still be missing: then the create response's `warning` names it. + +Example for GitHub: ```bash one --agent relay create \ @@ -274,6 +230,7 @@ The access settings from `one config` (and `.onerc`) apply to relays as well as ```bash one --agent relay platforms # All relay-capable platforms + event type counts one --agent relay event-types # Event types for a specific platform +one --agent relay metadata # --metadata keys the platform needs on create ``` ## Management Commands @@ -304,6 +261,8 @@ Agent-mode output: | `delete` | `{deleted: true, id}` | | `platforms` | `{platforms: [{platform, eventTypeCount}]}` | | `event-types` | `{platform, eventTypes: [...]}` | +| `metadata` | `{platform, fields: [{key, label, required, secret, placeholder?}]}` | +| `create` refused | `{status: "metadata_required", error, platform, missing: [...]}`, exit 1 | To page `list` or `events`, raise `--page` until `showing` is 0. With a connection allowlist, rows are filtered after the server pages them, so a page can hold fewer than `--limit` rows and `total` counts only the rows shown. @@ -323,7 +282,7 @@ To page `list` or `events`, raise `--page` until `showing` is 0. With a connecti - Event filters on both the endpoint and individual actions must match - Multiple actions can be attached to a single relay endpoint - Missing template variables resolve to empty strings — verify `{{payload.*}}` paths against the actual payload -- Many platforms require `--metadata` on create (see the table in Step 5); a `warning` in the create response means the webhook was not registered with the source platform +- Many platforms require `--metadata` on create (`relay metadata ` lists the keys); a `warning` in the create response means the webhook was not registered with the source platform - Every rendered template value is a string - Don't pass `--webhook-secret` on activate when the endpoint was created with `--create-webhook` unless activate asks for one; a wrong secret makes One reject every webhook on that connection (no events at all) - Keep one relay per source connection and add actions to it diff --git a/src/cli.ts b/src/cli.ts index 4ac2d1f..6a627f9 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -42,6 +42,7 @@ import { relayDeliveriesCommand, relayEventTypesCommand, relayPlatformsCommand, + relayMetadataCommand, } from './commands/relay.js'; import { connectCreateCommand, connectTypesCommand } from './commands/connect.js'; @@ -141,6 +142,7 @@ program one relay activate Attach forwarding actions (agent mode: --confirm-write for writes) one relay get|update|delete Inspect, change, or remove an endpoint one relay event-types List supported event types + one relay metadata List the --metadata keys a platform needs on create one relay events List received webhook events (relay event for one) one relay deliveries List delivery attempts @@ -712,7 +714,7 @@ relay .option('--description ', 'Description of the relay endpoint') .option('--event-filters ', 'JSON array of event types to filter (e.g. \'["customer.created"]\')') .option('--tags ', 'JSON array of tags') - .option('--metadata ', 'JSON object of platform-specific values many platforms need to register the webhook (e.g. GitHub: \'{"GITHUB_OWNER":"org","GITHUB_REPOSITORY":"repo"}\', Airtable: \'{"AIRTABLE_DATABASE_ID":"app..."}\'). `one guide relay` lists every platform\'s keys; a missing one leaves the webhook unregistered and the response carries a warning') + .option('--metadata ', 'JSON object of platform-specific values many platforms need to register the webhook (e.g. GitHub: \'{"GITHUB_OWNER":"org","GITHUB_REPOSITORY":"repo"}\'). `one relay metadata ` lists a platform\'s keys. With --create-webhook, a missing required key stops the create before anything is made') .option('--create-webhook', 'Automatically register the webhook with the source platform') .action(async (options: { connectionKey: string; description?: string; eventFilters?: string; tags?: string; metadata?: string; createWebhook?: boolean }) => { await relayCreateCommand(options); @@ -809,6 +811,13 @@ relay await relayPlatformsCommand(); }); +relay + .command('metadata ') + .description('List the --metadata keys a platform needs on relay create to register its webhook') + .action(async (platform: string) => { + await relayMetadataCommand(platform); + }); + // ── Sync Commands ── diff --git a/src/commands/relay-metadata.test.ts b/src/commands/relay-metadata.test.ts new file mode 100644 index 0000000..e3c4744 --- /dev/null +++ b/src/commands/relay-metadata.test.ts @@ -0,0 +1,172 @@ +import { describe, it, beforeEach, afterEach } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import http from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { relayCreateCommand, relayMetadataCommand } from './relay.js'; +import { setHomeTo, snapshotHomeEnv, restoreHomeEnv, type HomeEnvSnapshot } from '../test-support/home.js'; + +// `relay metadata` reads the setup fields One stores per platform (the list the +// dashboard's Configuration step shows), and `relay create --create-webhook` +// stops before creating anything when a required one is missing. Without the +// check the endpoint is created and the webhook never registers. + +const CONNECTORS: Record = { github: 'conn_def::GH', stripe: 'conn_def::ST' }; +const CONFIGS: Record = { + 'conn_def::GH': { + formData: [ + { name: 'GITHUB_OWNER', type: 'input', label: 'Repository Owner', placeholder: 'acme', options: [], optional: null }, + { name: 'GITHUB_REPOSITORY', type: 'input', label: 'Repository Name', placeholder: 'api', options: [], optional: null }, + { name: 'GITHUB_SIGNING_SECRET', type: 'password', label: 'Signing secret', placeholder: 'a1b2c3-not-for-output', options: [], optional: true }, + ], + }, +}; + +interface Harness { server: http.Server; port: number; requests: string[]; created: unknown[]; failConfig: boolean } + +function startServer(): Promise { + const h = { requests: [] as string[], created: [] as unknown[], failConfig: false } as Harness; + h.server = http.createServer((req, res) => { + const url = new URL(req.url ?? '/', 'http://localhost'); + let raw = ''; + req.on('data', chunk => { raw += chunk; }); + req.on('end', () => { + h.requests.push(`${req.method} ${url.pathname}`); + res.setHeader('content-type', 'application/json'); + if (url.pathname === '/v1/available-connectors') { + const platform = url.searchParams.get('platform') ?? ''; + const id = CONNECTORS[platform]; + res.end(JSON.stringify({ rows: id ? [{ id, platform }] : [], total: id ? 1 : 0, pages: 1, page: 1 })); + return; + } + if (url.pathname.startsWith('/v1/webhooks/relay/config/')) { + if (h.failConfig) { res.statusCode = 500; res.end('{"message":"boom"}'); return; } + const config = CONFIGS[decodeURIComponent(url.pathname.slice('/v1/webhooks/relay/config/'.length))]; + if (!config) { res.statusCode = 404; res.end('{"message":"Webhook relay config not found"}'); return; } + res.end(JSON.stringify(config)); + return; + } + if (url.pathname === '/v1/webhooks/relay' && req.method === 'POST') { + h.created.push(JSON.parse(raw)); + res.end(JSON.stringify({ id: 'r1', url: 'https://example.test/in', active: true })); + return; + } + res.statusCode = 404; + res.end('{}'); + }); + }); + return new Promise(resolve => h.server.listen(0, () => { + h.port = (h.server.address() as AddressInfo).port; + resolve(h); + })); +} + +class Exit extends Error { constructor(public code?: number) { super(`exit(${code})`); } } + +describe('relay --metadata fields', () => { + let tmp: string; + let home: HomeEnvSnapshot; + let agent: string | undefined; + let write: typeof process.stdout.write; + let exit: typeof process.exit; + let lines: string[]; + let h: Harness; + + beforeEach(async () => { + home = snapshotHomeEnv(); + agent = process.env.ONE_AGENT; + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'one-cli-relay-metadata-')); + setHomeTo(tmp); + process.env.ONE_AGENT = '1'; + h = await startServer(); + fs.mkdirSync(path.join(tmp, '.one'), { recursive: true }); + fs.writeFileSync(path.join(tmp, '.one', 'config.json'), + JSON.stringify({ apiKey: 'sk_test', apiBase: `http://localhost:${h.port}` })); + + lines = []; + write = process.stdout.write.bind(process.stdout); + process.stdout.write = ((chunk: any, ...rest: any[]) => { + if (typeof chunk !== 'string') return (write as any)(chunk, ...rest); + if (chunk.trim().startsWith('{')) lines.push(chunk); + return true; + }) as typeof process.stdout.write; + exit = process.exit; + process.exit = ((code?: number) => { throw new Exit(code); }) as typeof process.exit; + }); + + afterEach(() => { + process.stdout.write = write; + process.exit = exit; + restoreHomeEnv(home); + if (agent === undefined) delete process.env.ONE_AGENT; else process.env.ONE_AGENT = agent; + h.server.close(); + fs.rmSync(tmp, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }); + }); + + const last = () => JSON.parse(lines[lines.length - 1]); + + async function exitCode(fn: () => Promise): Promise { + try { await fn(); return undefined; } catch (e) { if (e instanceof Exit) return e.code; throw e; } + } + + const GITHUB = 'live::github::default::abc123'; + + it('relay metadata lists the stored fields with which are required', async () => { + await relayMetadataCommand('github'); + const out = last(); + assert.equal(out.platform, 'github'); + assert.deepEqual(out.fields.map((f: any) => [f.key, f.required, f.secret]), [ + ['GITHUB_OWNER', true, false], + ['GITHUB_REPOSITORY', true, false], + ['GITHUB_SIGNING_SECRET', false, true], + ]); + assert.equal(out.fields[0].placeholder, 'acme'); + assert.ok(!JSON.stringify(out).includes('not-for-output'), 'a secret field\'s placeholder is not repeated'); + }); + + it('relay metadata says when One lists no fields for a platform', async () => { + await relayMetadataCommand('stripe'); + const out = last(); + assert.deepEqual(out.fields, []); + assert.match(out._hint, /lists no --metadata fields/); + }); + + it('relay create --create-webhook stops before creating when a required key is missing', async () => { + const code = await exitCode(() => relayCreateCommand({ + connectionKey: GITHUB, createWebhook: true, metadata: '{"GITHUB_OWNER":"acme","GITHUB_REPOSITORY":" "}', + })); + assert.equal(code, 1); + const out = last(); + assert.equal(out.status, 'metadata_required'); + assert.deepEqual(out.missing.map((f: any) => f.key), ['GITHUB_REPOSITORY']); + assert.deepEqual(h.created, []); + assert.equal(lines.length, 1, 'prints the refusal once'); + }); + + it('relay create goes through when the required keys are there, optional ones aside', async () => { + await relayCreateCommand({ + connectionKey: GITHUB, createWebhook: true, metadata: '{"GITHUB_OWNER":"acme","GITHUB_REPOSITORY":"api"}', + }); + assert.equal(h.created.length, 1); + assert.equal(last().id, 'r1'); + }); + + it('relay create without --create-webhook does not look the fields up', async () => { + await relayCreateCommand({ connectionKey: GITHUB }); + assert.equal(h.created.length, 1); + assert.ok(!h.requests.some(r => r.includes('/webhooks/relay/config/'))); + }); + + it('relay create goes through for a platform with no stored fields', async () => { + await relayCreateCommand({ connectionKey: 'live::stripe::default::abc123', createWebhook: true }); + assert.equal(h.created.length, 1); + }); + + it('relay create goes through when the field list cannot be read', async () => { + h.failConfig = true; + await relayCreateCommand({ connectionKey: GITHUB, createWebhook: true }); + assert.equal(h.created.length, 1); + }); +}); diff --git a/src/commands/relay.ts b/src/commands/relay.ts index 6cf8965..93d4c7d 100644 --- a/src/commands/relay.ts +++ b/src/commands/relay.ts @@ -3,7 +3,7 @@ import { getApiKey, getApiBase, getAccessControlFromAllSources } from '../lib/co import { OneApi } from '../lib/api.js'; import { checkManagementAccess, checkRelayActions, isConnectionAllowed, relayWritesOf, WRITE_CONFIRMATION_HINT } from '../lib/access-gate.js'; import { resolveActionDetails } from '../lib/action-details.js'; -import type { AccessControlSettings } from '../lib/types.js'; +import type { AccessControlSettings, RelayFormField } from '../lib/types.js'; import { printTable } from '../lib/table.js'; import * as output from '../lib/output.js'; @@ -95,6 +95,60 @@ function parseJsonArg(value: string, argName: string): any { } } +/** The platform segment of a connection key (`live::github::default::…`). */ +function platformOfConnectionKey(key: string): string | null { + const parts = key.split('::'); + return parts.length >= 3 && parts[1] ? parts[1] : null; +} + +/** + * A field as `relay metadata` reports it: the key to pass and what it is. A + * secret field's placeholder is never repeated, in case a real value was + * stored as the example. + */ +function describeField(field: RelayFormField) { + const secret = field.type === 'password'; + return { + key: field.name, + label: field.label, + required: field.optional !== true, + secret, + ...(field.placeholder && !secret ? { placeholder: field.placeholder } : {}), + ...(Array.isArray(field.options) && field.options.length > 0 ? { options: field.options } : {}), + }; +} + +function isBlank(value: unknown): boolean { + return value === undefined || value === null || (typeof value === 'string' && value.trim() === ''); +} + +/** + * The fields One lists as required for the connection's platform that + * `--metadata` leaves out. Without them the endpoint would be created but the + * webhook never registered, so `relay create --create-webhook` stops first. + * Returns nothing to report when the list can't be read: the server's own + * `warning` still covers that case. + */ +async function missingMetadataFields( + api: OneApi, + connectionKey: string, + metadata: unknown, +): Promise<{ platform: string; missing: RelayFormField[] } | null> { + const platform = platformOfConnectionKey(connectionKey); + if (!platform) return null; + let fields: RelayFormField[] | null; + try { + fields = await api.getRelayMetadataFields(platform); + } catch { + return null; + } + const given = metadata && typeof metadata === 'object' && !Array.isArray(metadata) + ? metadata as Record + : {}; + const missing = (fields ?? []).filter(field => field.optional !== true && isBlank(given[field.name])); + return missing.length > 0 ? { platform, missing } : null; +} + // ── Commands ── export async function relayCreateCommand(options: { @@ -112,20 +166,43 @@ export async function relayCreateCommand(options: { output.error(`Connection key "${options.connectionKey}" is not allowed.`); } + const body: Record = { + connectionKey: options.connectionKey, + }; + if (options.description) body.description = options.description; + if (options.eventFilters) body.eventFilters = parseJsonArg(options.eventFilters, '--event-filters'); + if (options.tags) body.tags = parseJsonArg(options.tags, '--tags'); + if (options.metadata) body.metadata = parseJsonArg(options.metadata, '--metadata'); + if (options.createWebhook) body.createWebhook = true; + const api = new OneApi(apiKey, getApiBase()); const spinner = output.createSpinner(); + + if (options.createWebhook) { + spinner.start('Checking --metadata...'); + const gap = await missingMetadataFields(api, options.connectionKey, body.metadata); + spinner.stop(gap ? 'Missing --metadata' : 'Checked --metadata'); + if (gap) { + const keys = gap.missing.map(field => field.name); + const message = `${gap.platform} needs ${keys.join(', ')} in --metadata to register the webhook. Nothing was created.`; + if (output.isAgentMode()) { + output.json({ + status: 'metadata_required', + error: message, + platform: gap.platform, + missing: gap.missing.map(describeField), + _hint: `Ask the user for these values, then run relay create again with them in --metadata. \`one --agent relay metadata ${gap.platform}\` lists every field.`, + }); + process.exit(1); + } + const lines = gap.missing.map(field => ` ${field.name} ${pc.dim(field.label)}`); + output.error(`${message}\n${lines.join('\n')}`); + } + } + spinner.start('Creating relay endpoint...'); try { - const body: Record = { - connectionKey: options.connectionKey, - }; - if (options.description) body.description = options.description; - if (options.eventFilters) body.eventFilters = parseJsonArg(options.eventFilters, '--event-filters'); - if (options.tags) body.tags = parseJsonArg(options.tags, '--tags'); - if (options.metadata) body.metadata = parseJsonArg(options.metadata, '--metadata'); - if (options.createWebhook) body.createWebhook = true; - const result = await api.createRelayEndpoint(body as any); if (output.isAgentMode()) { @@ -590,3 +667,57 @@ export async function relayEventTypesCommand(platform: string): Promise { output.error(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`); } } + +export async function relayMetadataCommand(platform: string): Promise { + const { apiKey } = getConfig(); + const api = new OneApi(apiKey, getApiBase()); + const spinner = output.createSpinner(); + spinner.start(`Loading --metadata fields for ${pc.cyan(platform)}...`); + + try { + const fields = await api.getRelayMetadataFields(platform); + const described = (fields ?? []).map(describeField); + const noneListed = + `One lists no --metadata fields for ${platform}. Most such platforms need none. If relay create returns a ` + + '`warning` naming a missing key, delete that endpoint and create it again with the key in --metadata.'; + + if (output.isAgentMode()) { + output.json({ + platform, + fields: described, + ...(described.length === 0 + ? { _hint: noneListed } + : { _hint: 'Pass these as one JSON object: relay create --create-webhook --metadata \'{"KEY":"value"}\'. Ask the user for the values; required ones must be set.' }), + }); + return; + } + + spinner.stop(`${described.length} --metadata field${described.length === 1 ? '' : 's'} for ${platform}`); + + if (described.length === 0) { + console.log(`\n ${noneListed}\n`); + return; + } + + console.log(); + printTable( + [ + { key: 'key', label: 'Key' }, + { key: 'required', label: 'Required' }, + { key: 'label', label: 'What it is', color: pc.dim }, + { key: 'placeholder', label: 'Example', color: pc.dim }, + ], + described.map(field => ({ + key: field.key, + required: field.required ? 'yes' : 'no', + label: field.label, + placeholder: field.placeholder ?? '', + })) + ); + console.log(); + console.log(pc.dim(` Pass them as JSON: one relay create --create-webhook --metadata '{"${described[0].key}":"..."}'\n`)); + } catch (error) { + spinner.stop('Failed to load --metadata fields'); + output.error(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`); + } +} diff --git a/src/lib/api.ts b/src/lib/api.ts index 4b0d274..b884a7e 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -23,6 +23,7 @@ import type { KeyAccessDocument, AccessControlSettings, ViewerAccessLevel, + RelayFormField, } from './types.js'; export class ApiError extends Error { @@ -786,6 +787,30 @@ export class OneApi { return this.requestFull({ path: '/webhooks/relay/platforms' }); } + /** + * The `--metadata` fields One stores for a platform's relay setup, which is + * the list the dashboard's Configuration step shows. Resolves `null` when + * One stores none for the platform (or has no such connector), so callers + * can tell "nothing listed" from a failed request, which throws. + */ + async getRelayMetadataFields(platform: string): Promise { + const connectors = await this.requestFull<{ rows?: Array<{ id: string; platform: string }> }>({ + path: '/available-connectors', + queryParams: { platform, limit: '5' }, + }); + const connector = (connectors.rows || []).find(row => row.platform === platform); + if (!connector) return null; + try { + const config = await this.requestFull<{ formData?: RelayFormField[] }>({ + path: `/webhooks/relay/config/${encodeURIComponent(connector.id)}`, + }); + return config.formData ?? []; + } catch (error) { + if (error instanceof ApiError && error.status === 404) return null; + throw error; + } + } + async waitForConnection( platform: string, diff --git a/src/lib/guide-content.ts b/src/lib/guide-content.ts index 7f95cf6..09cad9f 100644 --- a/src/lib/guide-content.ts +++ b/src/lib/guide-content.ts @@ -338,6 +338,7 @@ Webhook relay receives events from 100+ platforms (Stripe, GitHub, Airtable, Att \`\`\`bash one --agent relay platforms # List relay-capable platforms + event type counts one --agent relay event-types # List available events +one --agent relay metadata # --metadata keys the platform needs on create one --agent relay create --connection-key --create-webhook --event-filters '["event.type"]' # also: --description , --tags , --metadata one --agent relay activate --actions '' --confirm-write # Add forwarding actions @@ -369,68 +370,22 @@ Aliases: \`one r\`, \`relay ls\`. Agent output: \`list\` returns \`{total, showi 2. **Get event types** — \`one --agent relay event-types \` 3. **Get source knowledge** — understand the incoming webhook payload shape (\`{{payload.*}}\` paths) 4. **Get destination knowledge** — understand the outgoing API body shape -5. **Create endpoint** — with \`--create-webhook\`, \`--event-filters\` holding at least one event (most platforms won't register a webhook without one), and \`--metadata\` when the source platform needs it (table below; ask the user for the values). **If the response has a \`warning\`, the endpoint exists but the webhook was NOT registered with the source platform.** Show the warning to the user, \`relay delete\` the endpoint, and create it again with what was missing. If the source connection already has a relay, add your actions to that one with \`relay update --actions\` (pass the full list; it replaces) instead of creating a second: all relays on a connection share one URL and one signing secret, and a second \`--create-webhook\` replaces the stored secret. +5. **Create endpoint** — with \`--create-webhook\`, \`--event-filters\` holding at least one event (most platforms won't register a webhook without one), and \`--metadata\` when the source platform needs it (\`relay metadata \` lists the keys; ask the user for the values). **If the response has a \`warning\`, the endpoint exists but the webhook was NOT registered with the source platform.** Show the warning to the user, \`relay delete\` the endpoint, and create it again with what was missing. If the source connection already has a relay, add your actions to that one with \`relay update --actions\` (pass the full list; it replaces) instead of creating a second: all relays on a connection share one URL and one signing secret, and a second \`--create-webhook\` replaces the stored secret. 6. **Activate** — with a passthrough action mapping source fields to destination fields. **Don't pass \`--webhook-secret\`** when the endpoint was created with \`--create-webhook\`: the secret is already stored on the source connection. Pass it only when activate fails asking for one (the platform returned no secret at registration), with the signing secret the user copies from the source platform's webhook settings. A wrong secret replaces the stored one for every relay on that connection; the source's webhooks are then rejected with 401 and no events are recorded at all. Endpoints are created active with no actions; \`activate\` attaches the actions, and calling it again replaces them. ## Platform-Specific Metadata (\`--metadata\`) -These source platforms need values in \`--metadata ''\` on \`relay create\` before the webhook can be registered. Every other platform (Stripe, Linear, Attio, Google Calendar, ...) needs none. Keys are case-sensitive. A missing key doesn't fail \`create\`: the endpoint is created, the webhook isn't registered, and the response's \`warning\` names the key. - -| Platform | Required metadata keys | -|---|---| -| \`airtable\` | \`AIRTABLE_DATABASE_ID\` | -| \`apify\` | \`APIFY_ACTOR_ID\` or \`APIFY_ACTOR_TASK_ID\` | -| \`asana\` | \`ASANA_RESOURCE_GID\` | -| \`autodesk\` | \`AUTODESK_SYSTEM\`, \`AUTODESK_SCOPE\` (an object) | -| \`basin\` | \`BASIN_FORM_ID\` (a number) | -| \`bookingmood\` | \`BOOKINGMOOD_ORGANIZATION_ID\` | -| \`box\` | \`BOX_TARGET_ID\`, \`BOX_TARGET_TYPE\` | -| \`brevo\` | \`BREVO_DOMAIN\`, only when \`BREVO_TYPE\` is \`inbound\` | -| \`browse-ai\` | \`BROWSE_AI_ROBOT_ID\` | -| \`btcpay-server\` | \`BTCPAY_SERVER_STORE_ID\` | -| \`calendly\` | \`CALENDLY_ORGANIZATION\`, plus \`CALENDLY_USER\` or \`CALENDLY_GROUP\` for a user or group \`CALENDLY_SCOPE\` | -| \`chargebee\` | \`CHARGEBEE_WEBHOOK_NAME\` | -| \`click-up\` | \`CLICK_UP_TEAM_ID\` | -| \`clockify\` | \`CLOCKIFY_WORKSPACE_ID\`, \`CLOCKIFY_WEBHOOK_NAME\`, \`CLOCKIFY_TRIGGER_SOURCE_TYPE\`, \`CLOCKIFY_TRIGGER_SOURCE\` (a list) | -| \`cloudinary\` | \`CLOUDINARY_SIGNING_SECRET\` | -| \`contentful-content-management\` | \`CONTENTFUL_CONTENT_MANAGEMENT_SPACE_ID\` | -| \`crowdin\` | \`CROWDIN_PROJECT_ID\` | -| \`datadog\` | \`DATADOG_WEBHOOK_NAME\` | -| \`doppler-secretops\` | \`DOPPLER_SECRETOPS_PROJECT\`, \`DOPPLER_SECRETOPS_CONFIGS\` (a list) | -| \`fathom\` | \`FATHOM_TRIGGERED_FOR\` | -| \`figma\` | \`FIGMA_CONTEXT\`, \`FIGMA_CONTEXT_ID\` | -| \`files-com\` | \`FILES_COM_PATH\` | -| \`fillout\` | \`FILLOUT_FORM_ID\` | -| \`formbricks\` | \`FORMBRICKS_ENVIRONMENT_ID\` | -| \`git-lab\` | \`GIT_LAB_PROJECT_ID\` | -| \`github\` | \`GITHUB_OWNER\`, \`GITHUB_REPOSITORY\` | -| \`grist\` | \`GRIST_DOC_ID\`, \`GRIST_TABLE_ID\` | -| \`heyy\` | \`HEYY_TENANT_ID\` | -| \`hugging-face\` | \`HUGGING_FACE_WATCHED\` | -| \`jira\` | \`jqlFilter\` | -| \`launchdarkly\` | \`LAUNCHDARKLY_RESOURCES\` (a list) | -| \`loyverse\` | \`LOYVERSE_MERCHANT_ID\` | -| \`mailchimp-marketing\` | \`MAILCHIMP_MARKETING_LIST_ID\` | -| \`mailersend\` | \`MAILERSEND_DOMAIN_ID\` | -| \`monday\` | \`MONDAY_BOARD_ID\` | -| \`paradym\` | \`PARADYM_PROJECT_ID\`, \`PARADYM_WEBHOOK_NAME\` | -| \`parseur\` | \`PARSEUR_MAILBOX_ID\`, \`PARSEUR_WEBHOOK_NAME\` | -| \`posthog\` | \`POSTHOG_PROJECT_ID\`, \`POSTHOG_WEBHOOK_NAME\` | -| \`productive\` | \`PRODUCTIVE_ORGANIZATION_ID\` | -| \`sanity\` | \`SANITY_PROJECT_ID\`, \`SANITY_DATASET\` | -| \`sentry\` | \`SENTRY_ORGANIZATION_ID_OR_SLUG\`, \`SENTRY_PROJECT_ID_OR_SLUG\` | -| \`storyblok\` | \`STORYBLOK_SPACE_ID\` | -| \`tally\` | \`TALLY_FORM_ID\` | -| \`toggl-track\` | \`TOGGL_TRACK_WORKSPACE_ID\` | -| \`trello\` | \`TRELLO_MODEL_ID\` | -| \`typeform\` | \`TYPEFORM_FORM_ID\` | -| \`webflow\` | \`WEBFLOW_SITE_ID\` | -| \`workable\` | \`WORKABLE_ACCOUNT_ID\`, only for \`candidate_*\` events | -| \`workiom\` | \`WORKIOM_APP_ID\`, \`WORKIOM_LIST_ID\` | - -Some platforms also take optional keys (e.g. \`GOOGLE_CALENDAR_CALENDAR_ID\`, which defaults to the primary calendar). +Many source platforms need values in \`--metadata ''\` on \`relay create\` before the webhook can be registered. Look them up instead of guessing: + +\`\`\`bash +one --agent relay metadata +\`\`\` + +It returns \`{platform, fields: [{key, label, required, secret, placeholder?}]}\`: the keys One lists for that platform (the same list the dashboard's setup form shows). Ask the user for the values. Keys are case-sensitive. A \`secret\` field is a credential to ask the user for; never use the placeholder as a value. An empty \`fields\` list means One lists none; most such platforms need none. + +With \`--create-webhook\`, \`relay create\` checks the required keys first: if any is missing it returns \`"status": "metadata_required"\` with the \`missing\` fields, exits 1 and creates nothing. A key the list doesn't name can still be missing: then the endpoint is created, the webhook isn't registered, and the response's \`warning\` names the key. Example (GitHub): diff --git a/src/lib/types.ts b/src/lib/types.ts index 80fa790..650c42e 100644 --- a/src/lib/types.ts +++ b/src/lib/types.ts @@ -44,6 +44,23 @@ export interface Platform { oauth?: boolean; } +/** + * One field of a platform's relay setup form, as One stores it + * (`GET /webhooks/relay/config/{connectorId}`). `name` is the key to pass in + * `relay create --metadata`. The dashboard builds its Configuration step from + * the same list. + */ +export interface RelayFormField { + name: string; + /** `input`, or `password` for a value that should not be echoed. */ + type: string; + label: string; + placeholder: string; + options?: unknown[] | null; + /** Only `true` makes a field optional; One stores `null` for required ones. */ + optional?: boolean | null; +} + export interface PlatformsResponse { rows: Platform[]; total: number;