@ekanos/integration-schema 0.1.0
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/LICENSE +21 -0
- package/README.md +48 -0
- package/dist/capability-context.d.ts +178 -0
- package/dist/capability-context.js +2 -0
- package/dist/capability-context.js.map +1 -0
- package/dist/component-reference.d.ts +14 -0
- package/dist/component-reference.js +6 -0
- package/dist/component-reference.js.map +1 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.js +29 -0
- package/dist/index.js.map +1 -0
- package/dist/integration-definition.d.ts +1771 -0
- package/dist/integration-definition.js +661 -0
- package/dist/integration-definition.js.map +1 -0
- package/dist/product-id.d.ts +64 -0
- package/dist/product-id.js +201 -0
- package/dist/product-id.js.map +1 -0
- package/dist/workspace-target.d.ts +295 -0
- package/dist/workspace-target.js +150 -0
- package/dist/workspace-target.js.map +1 -0
- package/package.json +53 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"integration-definition.js","sourceRoot":"","sources":["../src/integration-definition.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAQxB,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAEL,yBAAyB,GAC1B,MAAM,oBAAoB,CAAC;AAU5B,MAAM,eAAe,GAAyB,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,CACxD,CAAC,CAAC,KAAK,CAAC;IACN,CAAC,CAAC,MAAM,EAAE;IACV,yEAAyE;IACzE,oEAAoE;IACpE,+BAA+B;IAC/B,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE;IACnB,CAAC,CAAC,OAAO,EAAE;IACX,CAAC,CAAC,IAAI,EAAE;IACR,CAAC,CAAC,KAAK,CAAC,eAAe,CAAC;IACxB,CAAC,CAAC,MAAM,CAAC,eAAe,CAAC;CAC1B,CAAC,CACH,CAAC;AAE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AC,MAAA,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,mCAAI,EAAE,CAAC,EAAE,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC;QACjE,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["/**\n * The canonical integration-definition contract: ONE zod schema and ONE set\n * of inferred/hand-written types (F9). `@ekanos/sdk`'s `defineIntegration()`\n * validates against this schema at authoring time; `@kit/integrations-core`'s\n * `registerPartnerIntegration()` re-validates against the SAME schema at the\n * host trust boundary (F3). Both packages depend on this one; it depends on\n * neither, so there is no cycle and no hand-written structural twin.\n *\n * Dependency-pure (zod only): partner component refs are checked\n * structurally via `ComponentReference`, so no React dependency leaks in.\n */\nimport { z } from 'zod';\n\nimport type {\n IntegrationContext,\n StorageKeyDeclarationInput,\n StorageSchemas,\n} from './capability-context';\nimport type { ComponentReference } from './component-reference';\nimport { isComponentReference } from './component-reference';\nimport {\n type WorkspaceTargetDefinition,\n WorkspaceTargetListSchema,\n} from './workspace-target';\n\n// ---- JSON-compatible values (F4) ------------------------------------------\n\ntype JsonPrimitive = string | number | boolean | null;\nexport type JsonValue =\n | JsonPrimitive\n | JsonValue[]\n | { [key: string]: JsonValue };\n\nconst jsonValueSchema: z.ZodType<JsonValue> = z.lazy(() =>\n z.union([\n z.string(),\n // `.finite()` rejects Infinity/-Infinity AND NaN (Number.isFinite) — all\n // of which JSON.stringify silently turns to `null`, so they are not\n // JSON-compatible values (F4).\n z.number().finite(),\n z.boolean(),\n z.null(),\n z.array(jsonValueSchema),\n z.record(jsonValueSchema),\n ]),\n);\n\n// ---- Leaf validators -------------------------------------------------------\n\nfunction componentRefSchema(what: string) {\n return z.custom<ComponentReference>(isComponentReference, {\n message: `${what} must be a React component reference (a function component, or a memo/forwardRef/lazy wrapper) — pass the component itself, not an element or a module path.`,\n });\n}\n\nconst zodSchemaRef = z.custom<z.ZodType>(\n (value) =>\n typeof (value as { safeParse?: unknown } | null)?.safeParse === 'function',\n {\n message:\n 'Every storage key must declare a zod schema (e.g. z.object({ … })) — ctx.storage validates reads and writes against it (capability-context ruling 1).',\n },\n);\n\nconst nonEmpty = (what: string) =>\n z.string().min(1, { message: `${what} must be a non-empty string.` });\n\nconst slugSchema = z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, {\n message:\n 'slug must be kebab-case ([a-z0-9] segments separated by single hyphens), e.g. \"acme-crm\" — it becomes the product slug, route segment, and MCP namespace.',\n});\n\nconst widgetIdSchema = z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, {\n message:\n 'Widget ids are kebab-case and globally unique, e.g. \"acme-crm-pipeline\" — prefix with the integration slug to stay collision-free.',\n});\n\nconst storageKeySchema = z.string().regex(/^[a-z0-9_-]+(?:\\/[a-z0-9_-]+)?$/, {\n message:\n 'Storage keys are \"<dataType>\" or \"<dataType>/<subtype>\" in lowercase [a-z0-9_-] — they map onto the account/user product-data columns (capability-context ruling 6).',\n});\n\nconst toolNameSchema = z.string().regex(/^[a-z][a-z0-9_]*$/, {\n message:\n 'Tool names are lowercase snake_case starting with a letter, e.g. \"list_invoices\" — the model calls them by this exact string.',\n});\n\nconst webhookIdSchema = z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, {\n message:\n 'Webhook ids are kebab-case, e.g. \"payment-updated\" — the host ingress route addresses the handler by this exact string.',\n});\n\nconst scheduleIdSchema = z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, {\n message:\n 'Schedule ids are kebab-case, e.g. \"daily-reconcile\" — the host scheduler addresses the handler by this exact string.',\n});\n\n// Origin-only egress entries (ruling 3): absolute https origins, optional\n// `*.` subdomain wildcard, no path/query/hash/credentials/http. Kept as a\n// pure regex here so this package depends on nothing; the SDK's shared\n// `parseEgressEntry`/`isEgressAllowed` matcher enforces the identical shape\n// at runtime.\nconst egressEntrySchema = z.string().superRefine((entry, ctx) => {\n const match = /^https:\\/\\/(\\*\\.)?([a-z0-9.-]+)(?::(\\d+))?$/i.exec(entry);\n if (!match) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message:\n `Egress entry \"${entry}\" is invalid. Entries are https origins only — ` +\n `\"https://api.example.com\" (exact) or \"https://*.example.com\" ` +\n `(subdomain wildcard): scheme + host + optional port, no path, query, ` +\n `hash, credentials, or http. Fix it in the integration's egress list.`,\n });\n return;\n }\n const host = match[2] ?? '';\n if (host.includes('*') || host.startsWith('.') || host.endsWith('.')) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Egress entry \"${entry}\" has a malformed host — wildcards are only supported as a single leading \"*.\" (e.g. \"https://*.example.com\").`,\n });\n }\n});\n\n// ---- Sub-object schemas ----------------------------------------------------\n\nconst capabilitySchema = z\n .object({\n label: nonEmpty('capabilities[].label'),\n description: nonEmpty('capabilities[].description'),\n icon: componentRefSchema('capabilities[].icon').optional(),\n })\n .strict();\n\nconst permissionSchema = z\n .object({\n label: nonEmpty('permissions[].label'),\n detail: nonEmpty('permissions[].detail'),\n type: z.enum(['read', 'write']),\n })\n .strict();\n\nconst gridUnitSchema = z\n .object({\n cols: z.number().int().positive(),\n rows: z.number().int().positive(),\n })\n .strict();\n\nconst layoutBoxSchema = z\n .object({\n x: z.number(),\n y: z.number(),\n w: z.number(),\n h: z.number(),\n maxHeight: z.number().optional(),\n })\n .strict();\n\n/**\n * F7: authorable widget fields ONLY. Host-resolved fields (`productId`,\n * `widgetConfigId`, `workspaceId`, `collapsed`, `isPinned`, `health`,\n * `integrationMetadata`) are absent by design and rejected at runtime by\n * `.strict()` — the type and the runtime agree. The host adapter maps this\n * into the full `WidgetConfig`.\n */\nconst widgetSchema = z\n .object({\n id: widgetIdSchema,\n name: nonEmpty('widgets[].name'),\n component: componentRefSchema('widgets[].component'),\n widgetState: z.enum(['active', 'inactive', 'disabled']),\n gridSize: z.union([gridUnitSchema, z.array(gridUnitSchema)]).optional(),\n gridPosition: z\n .object({ col: z.number(), row: z.number() })\n .strict()\n .optional(),\n layouts: z\n .object({\n lg: layoutBoxSchema.optional(),\n md: layoutBoxSchema.optional(),\n sm: layoutBoxSchema.optional(),\n })\n .strict()\n .optional(),\n category: z\n .object({\n id: z.string(),\n name: z.string(),\n slug: z.string(),\n icon: z.string().nullable(),\n })\n .strict()\n .optional(),\n isCollapsible: z.boolean().optional(),\n isPinnable: z.boolean().optional(),\n aiFooterEnabled: z.boolean().optional(),\n })\n .strict();\n\nconst toolParametersSchema = z\n .object({\n type: z.literal('object'),\n properties: z.record(jsonValueSchema).optional(),\n required: z.array(z.string()).optional(),\n additionalProperties: z.boolean().optional(),\n })\n .strict();\n\nconst toolRunSchema = z.custom<\n (ctx: never, args: Record<string, unknown>) => Promise<unknown>\n>((value) => typeof value === 'function', {\n message:\n 'tools[].run must be a function (ctx, args) => Promise<result> — it receives the host-scoped IntegrationContext, never a raw client.',\n});\n\nconst toolSchema = z\n .object({\n name: toolNameSchema,\n description: nonEmpty('tools[].description'),\n parameters: toolParametersSchema.optional(),\n run: toolRunSchema,\n outputExample: z.record(jsonValueSchema).optional(),\n })\n .strict();\n\n// ---- Event surfaces (webhooks, schedules, OAuth) ---------------------------\n//\n// Declared exactly like MCP tools: metadata parsed strictly, handlers checked\n// structurally as functions (`z.custom`) and carried through the parse\n// untouched. The declarations are the CONTRACT; every transport — the local\n// harness today, the host's public ingress/scheduler/hosted-callback later —\n// binds to these same fields, so a partner package never changes when the\n// real transports arrive.\n\nfunction handlerSchema(what: string, shape: string) {\n return z.custom<(ctx: never, arg: never) => Promise<unknown>>(\n (value) => typeof value === 'function',\n {\n message: `${what} must be a function ${shape} — it receives the host-scoped IntegrationContext, never a raw request or client.`,\n },\n );\n}\n\nconst payloadSchemaRef = z.custom<z.ZodType>(\n (value) =>\n typeof (value as { safeParse?: unknown } | null)?.safeParse === 'function',\n {\n message:\n 'webhooks[].payloadSchema must be a zod schema (e.g. z.object({ … })) — the transport validates every delivery against it before the handler runs.',\n },\n);\n\n/**\n * How the TRANSPORT verifies a delivery. Verification is never the partner's\n * job: the declaration names the signature header and the secret that signs\n * it; the host ingress enforces it (the local harness logs it as skipped).\n * `'none'` is an explicit statement that the source is unsigned.\n */\nconst webhookSignatureSchema = z.union([\n z.literal('none'),\n z\n .object({\n header: nonEmpty('webhooks[].signature.header'),\n secretName: nonEmpty('webhooks[].signature.secretName'),\n })\n .strict(),\n]);\n\nconst webhookSchema = z\n .object({\n id: webhookIdSchema,\n description: nonEmpty('webhooks[].description'),\n payloadSchema: payloadSchemaRef,\n signature: webhookSignatureSchema,\n examplePayload: z.record(jsonValueSchema).optional(),\n handler: handlerSchema(\n 'webhooks[].handler',\n '(ctx, event) => Promise<WebhookResult>',\n ),\n })\n .strict();\n\nconst scheduleSchema = z\n .object({\n id: scheduleIdSchema,\n description: nonEmpty('schedules[].description'),\n // Presence only here — the dependency-pure schema package stays zod-only,\n // so the real 5-field cron syntax check lives in the SDK layer\n // (`defineIntegration()`), the same way it layers cross-field rules today.\n cron: nonEmpty('schedules[].cron'),\n handler: handlerSchema(\n 'schedules[].handler',\n '(ctx, invocation) => Promise<ScheduleResult>',\n ),\n })\n .strict();\n\nconst httpsUrlSchema = (what: string) =>\n z.string().superRefine((value, ctx) => {\n let parsed: URL;\n try {\n parsed = new URL(value);\n } catch {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `${what} must be an absolute URL, e.g. \"https://provider.example/oauth/authorize\".`,\n });\n return;\n }\n if (parsed.protocol !== 'https:') {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `${what} must use https — OAuth endpoints are never plain http.`,\n });\n }\n if (parsed.username !== '' || parsed.password !== '') {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `${what} must not embed credentials.`,\n });\n }\n });\n\nconst oauthSchema = z\n .object({\n provider: z\n .object({\n authorizationUrl: httpsUrlSchema('oauth.provider.authorizationUrl'),\n tokenUrl: httpsUrlSchema('oauth.provider.tokenUrl'),\n scopes: z.array(nonEmpty('oauth.provider.scopes[]')),\n pkce: z.boolean().optional(),\n })\n .strict(),\n credentials: z\n .object({\n clientIdSecretName: nonEmpty('oauth.credentials.clientIdSecretName'),\n clientSecretSecretName: nonEmpty(\n 'oauth.credentials.clientSecretSecretName',\n ),\n })\n .strict(),\n onTokens: handlerSchema('oauth.onTokens', '(ctx, tokens) => Promise<void>'),\n })\n .strict();\n\nconst toolClassificationProposalSchema = z\n .object({\n effect: z.enum(['read', 'write']).optional(),\n sensitivity: z.enum(['public', 'internal', 'pii', 'financial']).optional(),\n })\n .strict();\n\nconst proposalsSchema = z\n .object({\n credentialModel: z.enum(['account', 'user', 'source']).optional(),\n tools: z.record(toolClassificationProposalSchema).optional(),\n })\n .strict();\n\n/**\n * A storage key's EXPLICIT declaration: the zod schema plus its exposure\n * flags. `clientReadable` is the only way a declared key becomes readable by\n * the browser through the generic storage route — and it defaults to false,\n * so the bare-schema form stays server-only exactly as it always was.\n * `.strict()` keeps an unrecognized flag (a typo like `clientReadible`) an\n * error rather than a silently-ignored key whose author believes it is\n * exposed — or, worse, believes it is not.\n */\nconst storageKeyDeclarationSchema = z\n .object({\n schema: zodSchemaRef,\n clientReadable: z.boolean().optional(),\n })\n .strict();\n\n/** Duck-typed so a partner's own bundled zod copy still reads as a schema. */\nfunction isZodSchemaLike(value: unknown): boolean {\n return (\n typeof (value as { safeParse?: unknown } | null)?.safeParse === 'function'\n );\n}\n\n/**\n * Either declaration form, hand-routed rather than expressed as `z.union` so\n * the failure message stays specific. A union reports a bare \"Invalid input\"\n * for every wrong shape, which would lose both the \"declare a zod schema\"\n * guidance AND the strict-descriptor typo report — the two errors an author\n * is actually going to hit.\n */\nconst storageKeyDeclarationRef = z\n .custom<StorageKeyDeclarationInput>(() => true)\n .superRefine((value, ctx) => {\n if (isZodSchemaLike(value)) return;\n\n const looksLikeDescriptor =\n value !== null && typeof value === 'object' && !Array.isArray(value);\n\n // Neither form: name both, since the descriptor is the less obvious one.\n if (\n !looksLikeDescriptor ||\n !isZodSchemaLike((value as { schema?: unknown }).schema)\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message:\n 'Every storage key must declare either a zod schema (e.g. z.object({ … })) or a { schema, clientReadable } descriptor — ctx.storage validates reads and writes against the schema (capability-context ruling 1), and clientReadable (default false) is what opts the key in to the browser-readable storage route.',\n });\n return;\n }\n\n // A real descriptor with a real schema — report its own issues verbatim\n // (an unrecognized flag, a non-boolean clientReadable) rather than the\n // generic message, which would send the author looking in the wrong place.\n const result = storageKeyDeclarationSchema.safeParse(value);\n if (result.success) return;\n\n for (const issue of result.error.issues) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: issue.path,\n message: issue.message,\n });\n }\n });\n\nconst storageScopeSchema = z.record(storageKeySchema, storageKeyDeclarationRef);\n\nconst componentsSchema = z\n .object({\n activationForm: componentRefSchema('components.activationForm').optional(),\n marketplaceTile: componentRefSchema(\n 'components.marketplaceTile',\n ).optional(),\n widgets: z.array(widgetSchema).optional(),\n })\n .strict();\n\n/**\n * THE canonical schema. Strict everywhere: an unrecognized key is an error,\n * which is what keeps host-assigned fields (productId, kind, trust tier,\n * credentialModel, per-tool effect/sensitivity, host-resolved widget fields)\n * structurally un-settable at runtime, not merely absent from the type.\n */\nexport const IntegrationDefinitionSchema = z\n .object({\n slug: slugSchema,\n name: nonEmpty('name'),\n description: nonEmpty('description'),\n version: z\n .string()\n .regex(\n /^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$/,\n {\n message:\n 'version must be semver (\"1.0.0\", optionally with a prerelease/build suffix) — promotion diffs definitions by it.',\n },\n ),\n capabilities: z.array(capabilitySchema).optional(),\n permissions: z.array(permissionSchema).optional(),\n components: componentsSchema.optional(),\n workspaceTargets: WorkspaceTargetListSchema.optional(),\n tools: z.array(toolSchema).optional(),\n storage: z\n .object({\n account: storageScopeSchema.optional(),\n user: storageScopeSchema.optional(),\n })\n .strict()\n .optional(),\n egress: z.array(egressEntrySchema).optional(),\n webhooks: z.array(webhookSchema).optional(),\n schedules: z.array(scheduleSchema).optional(),\n oauth: oauthSchema.optional(),\n proposes: proposalsSchema.optional(),\n })\n .strict()\n .superRefine((definition, ctx) => {\n const webhookIds = (definition.webhooks ?? []).map((w) => w.id);\n for (const id of findDuplicates(webhookIds)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['webhooks'],\n message: `Webhook id \"${id}\" is declared more than once — give every webhook a unique id.`,\n });\n }\n\n const scheduleIds = (definition.schedules ?? []).map((s) => s.id);\n for (const id of findDuplicates(scheduleIds)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['schedules'],\n message: `Schedule id \"${id}\" is declared more than once — give every schedule a unique id.`,\n });\n }\n\n const widgetIds = (definition.components?.widgets ?? []).map((w) => w.id);\n for (const id of findDuplicates(widgetIds)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['components', 'widgets'],\n message: `Widget id \"${id}\" is declared more than once — give every widget a unique id.`,\n });\n }\n\n const toolNames = (definition.tools ?? []).map((tool) => tool.name);\n for (const name of findDuplicates(toolNames)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['tools'],\n message: `Tool \"${name}\" is declared more than once — give every tool a unique name.`,\n });\n }\n\n const declaredTools = new Set(toolNames);\n for (const proposedName of Object.keys(definition.proposes?.tools ?? {})) {\n if (!declaredTools.has(proposedName)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['proposes', 'tools', proposedName],\n message: `proposes.tools[\"${proposedName}\"] does not match any declared tool — proposals are keyed by the exact tool name in \\`tools\\`.`,\n });\n }\n }\n });\n\n// ---- Hand-written generic types (the parts a non-generic schema cannot\n// express) plus inferred types for everything else. One home, imported by\n// both @ekanos/sdk and @kit/integrations-core. -------------------------------\n\nexport type ToolClassificationProposal = z.infer<\n typeof toolClassificationProposalSchema\n>;\nexport type IntegrationProposals = z.infer<typeof proposalsSchema>;\nexport type PartnerToolParameters = z.infer<typeof toolParametersSchema>;\nexport type IntegrationCapabilityDeclaration = z.infer<typeof capabilitySchema>;\nexport type IntegrationPermissionDeclaration = z.infer<typeof permissionSchema>;\nexport type PartnerWidgetDeclaration = z.infer<typeof widgetSchema>;\n\nexport interface PartnerToolModule<\n Schemas extends StorageSchemas = StorageSchemas,\n> {\n name: string;\n description: string;\n parameters?: PartnerToolParameters;\n /**\n * Contravariant function property (F8): the declared `Schemas` generic\n * types `ctx.storage` for the author. The generic cannot survive the\n * by-value, monomorphic host registration boundary — the adapter erases it\n * — but nothing rests on it surviving: the host constructs `ctx` FROM the\n * definition's own `storage` schemas, and `ctx.storage` validates every\n * read/write against them at runtime regardless of the handler's\n * annotation. The static generic is DX; the runtime schema is the guard.\n */\n run: (\n ctx: IntegrationContext<Schemas>,\n args: Record<string, unknown>,\n ) => Promise<unknown>;\n outputExample?: Record<string, JsonValue>;\n}\n\nexport interface IntegrationComponentDeclarations {\n activationForm?: ComponentReference;\n marketplaceTile?: ComponentReference;\n widgets?: PartnerWidgetDeclaration[];\n}\n\n// ---- Event-surface types (webhooks, schedules, OAuth) ----------------------\n//\n// Hand-written generics like `PartnerToolModule`: the `Schemas` generic types\n// `ctx.storage` for the author and is erased at the host boundary, where the\n// runtime storage validator — built from the definition's own `storage`\n// schemas — is the guard.\n\n/**\n * How the transport verifies a webhook delivery. `'none'` states explicitly\n * that the source is unsigned; otherwise the transport reads the named header\n * and verifies it against the named secret. Verification is the TRANSPORT's\n * job (the local harness logs it as skipped; the host ingress enforces it) —\n * never the partner handler's.\n */\nexport type WebhookSignatureDeclaration =\n | 'none'\n | { header: string; secretName: string };\n\n/**\n * One delivery, as the handler receives it: transport-assigned id and receipt\n * time, the delivery headers, and the payload ALREADY parsed and validated\n * against the declaration's `payloadSchema`. A payload that fails the schema\n * never reaches the handler.\n */\nexport interface WebhookEvent {\n id: string;\n /** ISO-8601 — when the transport accepted the delivery. */\n receivedAt: string;\n headers: Record<string, string>;\n /** The parsed, schema-validated payload (output of `payloadSchema`). */\n payload: unknown;\n}\n\n/**\n * What the handler tells the transport. `processed` acknowledges the event;\n * `ignored` acknowledges it as irrelevant (still a 2xx — the sender must not\n * retry). A handler that cannot process a valid event THROWS, which the\n * transport maps to a retryable failure.\n */\nexport interface WebhookResult {\n status: 'processed' | 'ignored';\n detail?: string;\n}\n\nexport interface PartnerWebhookDeclaration<\n Schemas extends StorageSchemas = StorageSchemas,\n> {\n id: string;\n description: string;\n /** Validates every delivery before the handler runs. */\n payloadSchema: z.ZodType;\n signature: WebhookSignatureDeclaration;\n /**\n * A representative payload, JSON-compatible. Seeds the harness's payload\n * editor and documents the shape beside the schema.\n */\n examplePayload?: Record<string, JsonValue>;\n handler: (\n ctx: IntegrationContext<Schemas>,\n event: WebhookEvent,\n ) => Promise<WebhookResult>;\n}\n\n/**\n * One firing, as the handler receives it. `trigger` distinguishes the real\n * scheduler from a human pressing \"Run now\" (harness or admin) — handlers may\n * branch on it (e.g. skip idempotency windows for manual runs) but must be\n * safe under both.\n */\nexport interface ScheduleInvocation {\n /** ISO-8601 — the tick this invocation stands for. */\n scheduledFor: string;\n /** ISO-8601 — when the handler actually started. */\n invokedAt: string;\n trigger: 'schedule' | 'manual';\n}\n\n/**\n * `completed` means the run did its work; `skipped` means it correctly did\n * nothing (not configured, nothing to do). A handler that fails THROWS, which\n * the transport records as a failed run.\n */\nexport interface ScheduleResult {\n status: 'completed' | 'skipped';\n detail?: string;\n}\n\nexport interface PartnerScheduleDeclaration<\n Schemas extends StorageSchemas = StorageSchemas,\n> {\n id: string;\n description: string;\n /**\n * Standard 5-field cron (minute hour day-of-month month day-of-week),\n * validated by `defineIntegration()`. The schema package checks presence\n * only — full syntax validation is the SDK layer's job.\n */\n cron: string;\n handler: (\n ctx: IntegrationContext<Schemas>,\n invocation: ScheduleInvocation,\n ) => Promise<ScheduleResult>;\n}\n\n/**\n * The token set the transport hands `onTokens` after a code exchange (and\n * after each refresh). `raw` carries provider-specific extras verbatim.\n */\nexport interface OAuthTokens {\n accessToken: string;\n refreshToken?: string;\n /** ISO-8601 expiry, when the provider reports one. */\n expiresAt?: string;\n scope?: string;\n tokenType?: string;\n raw?: Record<string, JsonValue>;\n}\n\nexport interface OAuthProviderDeclaration {\n authorizationUrl: string;\n tokenUrl: string;\n scopes: string[];\n pkce?: boolean;\n}\n\n/**\n * The OAuth contract. The TRANSPORT owns the flow (authorize redirect, state,\n * callback, code exchange — localhost in the harness, hosted later); the\n * partner declares the provider endpoints, names the client-credential\n * secrets, and persists tokens in `onTokens` via `ctx.secrets` — so token\n * storage policy is the existing capability layer, nothing new.\n * `defineIntegration()` rejects the declaration unless both endpoint origins\n * are covered by the definition's `egress` list.\n */\nexport interface PartnerOAuthDeclaration<\n Schemas extends StorageSchemas = StorageSchemas,\n> {\n provider: OAuthProviderDeclaration;\n credentials: {\n clientIdSecretName: string;\n clientSecretSecretName: string;\n };\n onTokens: (\n ctx: IntegrationContext<Schemas>,\n tokens: OAuthTokens,\n ) => Promise<void>;\n}\n\nexport interface IntegrationDefinition<\n Schemas extends StorageSchemas = StorageSchemas,\n> {\n slug: string;\n name: string;\n description: string;\n version: string;\n capabilities?: IntegrationCapabilityDeclaration[];\n permissions?: IntegrationPermissionDeclaration[];\n components?: IntegrationComponentDeclarations;\n workspaceTargets?: WorkspaceTargetDefinition[];\n tools?: PartnerToolModule<Schemas>[];\n storage?: Schemas;\n egress?: string[];\n webhooks?: PartnerWebhookDeclaration<Schemas>[];\n schedules?: PartnerScheduleDeclaration<Schemas>[];\n oauth?: PartnerOAuthDeclaration<Schemas>;\n proposes?: IntegrationProposals;\n}\n\n// ---- Shared helpers --------------------------------------------------------\n\nfunction findDuplicates(values: readonly string[]): string[] {\n const seen = new Set<string>();\n const duplicates = new Set<string>();\n for (const value of values) {\n if (seen.has(value)) duplicates.add(value);\n seen.add(value);\n }\n return [...duplicates];\n}\n\nfunction formatIssues(issues: readonly z.ZodIssue[]): string {\n return issues\n .map((issue) => {\n const path = issue.path.length > 0 ? issue.path.join('.') : '(root)';\n return ` - ${path}: ${issue.message}`;\n })\n .join('\\n');\n}\n\nconst HOST_ASSIGNED_REMINDER =\n 'Host-assigned fields are never partner-authorable: productId, kind, trust ' +\n 'tier, and machine exposure (credentialModel) do not exist on ' +\n 'IntegrationDefinition, per-tool effect/sensitivity belong in the ' +\n '`proposes` block, and host-resolved widget fields (productId, ' +\n 'widgetConfigId, workspaceId, collapsed, isPinned, health, ' +\n 'integrationMetadata) are populated by the platform at runtime — remove ' +\n 'them from the definition.';\n\n/**\n * A zod schema (storage leaf) — detected via `instanceof` so we NEVER read a\n * property (like `.safeParse`) that could be a malicious getter (F4). A React\n * exotic (`memo`/`forwardRef`) is an object tagged with `$$typeof`; the `in`\n * check uses [[HasProperty]], which does not invoke a getter either.\n */\nfunction isDeclarationLeaf(value: object): boolean {\n return value instanceof z.ZodType || '$$typeof' in value;\n}\n\n/**\n * F4: reject accessor/proxy/class-instance/cyclic declaration containers\n * before parsing. An object with getters (or a proxy) can return validated\n * values during parse and different values later; a non-plain prototype can\n * smuggle mutable state past `z.object()`; a cycle would recurse into zod\n * rather than fail cleanly. We walk every CONTAINER (plain object / array),\n * and stop at legitimate leaves: functions (component refs, `run`) and zod\n * schemas (storage). Leaf detection happens BEFORE any own-property read, so\n * a `safeParse` getter cannot execute. Proxy detection is best-effort — the\n * re-parse at the host boundary (which materializes fresh values via zod) is\n * the real guard.\n *\n * Cycle detection tracks the ANCESTOR chain only (add on enter, remove on\n * exit): a genuine back-edge is a cycle, but the same object referenced from\n * two sibling branches (a DAG — e.g. a shallow-cloned widget sharing a\n * `layouts` object) is not, and must not be rejected.\n */\nexport function assertPlainDeclaration(\n value: unknown,\n path = '(root)',\n ancestors: WeakSet<object> = new WeakSet(),\n): void {\n if (value === null || typeof value !== 'object') return;\n\n if (typeof value === 'function') return;\n\n // Leaf detection first — instanceof / HasProperty never invoke a getter.\n if (isDeclarationLeaf(value)) return;\n\n if (ancestors.has(value)) {\n throw new Error(\n `Integration definition contains a cycle at ${path}. ` +\n `Declarations must be finite plain data — remove the self-reference. ${HOST_ASSIGNED_REMINDER}`,\n );\n }\n\n const proto = Object.getPrototypeOf(value) as unknown;\n const isArray = Array.isArray(value);\n if (!isArray && proto !== Object.prototype && proto !== null) {\n throw new Error(\n `Integration definition value at ${path} is a class/exotic instance, not a plain object. ` +\n `Declaration containers must be plain object/array literals so their values cannot mutate after validation. ${HOST_ASSIGNED_REMINDER}`,\n );\n }\n\n ancestors.add(value);\n for (const key of Object.keys(value)) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor && (descriptor.get || descriptor.set)) {\n throw new Error(\n `Integration definition property at ${path}.${key} is a getter/setter, not a data property. ` +\n `Declaration values must be plain data — a getter can return a different value after validation. ${HOST_ASSIGNED_REMINDER}`,\n );\n }\n assertPlainDeclaration(\n (value as Record<string, unknown>)[key],\n `${path}.${key}`,\n ancestors,\n );\n }\n ancestors.delete(value);\n}\n\nconst frozen = new WeakSet<object>();\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== 'object') return false;\n const proto = Object.getPrototypeOf(value) as unknown;\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * Cycle-aware deep freeze (F4). Freezes plain objects and arrays; leaves zod\n * schemas (freezing breaks their internal caches) and functions alone.\n */\nexport function deepFreezeDefinition(value: unknown): void {\n if (value === null || typeof value !== 'object') return;\n if (frozen.has(value)) return;\n\n if (Array.isArray(value)) {\n frozen.add(value);\n Object.freeze(value);\n for (const item of value) deepFreezeDefinition(item);\n return;\n }\n if (isPlainObject(value)) {\n frozen.add(value);\n Object.freeze(value);\n for (const item of Object.values(value)) deepFreezeDefinition(item);\n }\n}\n\n/**\n * The single validation entry point used by BOTH `defineIntegration()` (SDK,\n * authoring time) and `registerPartnerIntegration()` (core, host trust\n * boundary — F3). Rejects non-plain containers, then parses against the\n * canonical schema, and returns the SANITIZED `result.data` (fresh, plain,\n * strict-stripped — never the caller's original object). Throws an Error\n * whose message is a remediation instruction.\n */\nexport function parseIntegrationDefinition(\n input: unknown,\n): IntegrationDefinition {\n assertPlainDeclaration(input);\n\n const result = IntegrationDefinitionSchema.safeParse(input);\n if (!result.success) {\n const slug =\n typeof (input as { slug?: unknown } | null)?.slug === 'string'\n ? ` for \"${(input as { slug: string }).slug}\"`\n : '';\n throw new Error(\n `Invalid integration definition${slug}:\\n` +\n `${formatIssues(result.error.issues)}\\n` +\n HOST_ASSIGNED_REMINDER,\n );\n }\n\n // F4: freeze inside the canonical parser so BOTH defineIntegration() and\n // registerPartnerIntegration() register immutable output — the host boundary\n // no longer hands back mutable arrays. Function/zod leaves stay executable\n // by design (the T1 model), so this is structural immutability, not\n // behavioral.\n deepFreezeDefinition(result.data);\n\n // The schema's inferred output matches IntegrationDefinition in every\n // non-generic field; the storage/tool generics default to the permissive\n // base, which is exactly right for the loose registration boundary.\n return result.data as unknown as IntegrationDefinition;\n}\n\n// ---- Cross-definition collision detection (F5) -----------------------------\n\n/**\n * THE canonical effective MCP tool name — the single source of truth for how\n * discovery keys a tool. Tool discovery namespaces each raw tool name with the\n * integration slug (`slug.replace(/-/g,'_')`), skipping the prefix when the\n * name already carries it. Two collision-free RAW pairs can therefore collapse\n * to the same EFFECTIVE name (`{slug:\"foo\",tool:\"bar_baz\"}` and\n * `{slug:\"foo-bar\",tool:\"baz\"}` both become `foo_bar_baz`), so collision\n * checking MUST compare effective names, and runtime discovery MUST throw on a\n * duplicate assignment. Both call this one helper\n * (`packages/agents/src/tools/tool-discovery.ts`).\n */\nexport function getDiscoveredToolName(slug: string, rawName: string): string {\n const slugPrefix = slug.replace(/-/g, '_');\n return rawName.startsWith(slugPrefix) ? rawName : `${slugPrefix}_${rawName}`;\n}\n\n/**\n * The metadata-only shape collision checking needs — no handlers, no schemas\n * (F8: collision validation must not force widening the tool handlers). A\n * full `IntegrationDefinition` is assignable to it.\n */\nexport interface DefinitionCollisionInput {\n slug: string;\n components?: { widgets?: readonly { id: string }[] } | null;\n tools?: readonly { name: string }[] | null;\n}\n\n/**\n * First-party identifiers a partner definition must not collide with (F5).\n * Widget lookup matches on `widget.id` and the assistant's tool list is a\n * flat name-keyed map where a later registration overwrites an earlier one,\n * so a partner reusing a first-party id/name silently hijacks it. Sourced\n * from the reviewed registry inventory, not from executing partner handlers.\n */\nexport interface FirstPartyInventory {\n slugs?: readonly string[];\n widgetIds?: readonly string[];\n /**\n * EFFECTIVE (discovery) tool names — `getDiscoveredToolName(slug, rawName)` —\n * NOT raw names, since discovery keys the flat registry by the effective name.\n */\n toolNames?: readonly string[];\n}\n\n/**\n * Detects cross-definition collisions (duplicate slugs, widget ids, tool\n * names across the partner set) AND collisions against the first-party\n * inventory, throwing one error listing EVERY collision.\n *\n * This is the build-time gate the host registry deliberately lacks:\n * `integrationRegistry.register()` keys by slug via `Map.set` and silently\n * OVERWRITES, and duplicate widget/tool ids resolve last- or\n * first-registration-wins by import order.\n */\nexport function validateIntegrationDefinitions(\n definitions: readonly DefinitionCollisionInput[],\n firstParty: FirstPartyInventory = {},\n): void {\n const slugCounts = new Map<string, number>();\n const widgetOwners = new Map<string, string[]>();\n const toolOwners = new Map<string, string[]>();\n\n for (const definition of definitions) {\n slugCounts.set(definition.slug, (slugCounts.get(definition.slug) ?? 0) + 1);\n for (const widget of definition.components?.widgets ?? []) {\n widgetOwners.set(widget.id, [\n ...(widgetOwners.get(widget.id) ?? []),\n definition.slug,\n ]);\n }\n for (const tool of definition.tools ?? []) {\n // EFFECTIVE (discovery) name, not the raw name — two collision-free raw\n // names can collapse to the same effective key.\n const effective = getDiscoveredToolName(definition.slug, tool.name);\n toolOwners.set(effective, [\n ...(toolOwners.get(effective) ?? []),\n definition.slug,\n ]);\n }\n }\n\n const collisions: string[] = [];\n\n for (const [slug, count] of slugCounts) {\n if (count > 1) {\n collisions.push(\n `slug \"${slug}\" is declared by ${count} partner definitions — slugs are the registry key and must be globally unique.`,\n );\n }\n }\n for (const [id, owners] of widgetOwners) {\n if (owners.length > 1) {\n collisions.push(\n `widget id \"${id}\" is declared by [${owners.join(', ')}] — widget ids are global (widget_config rows key on them); prefix yours with the integration slug.`,\n );\n }\n }\n for (const [name, owners] of toolOwners) {\n if (owners.length > 1) {\n collisions.push(\n `effective tool name \"${name}\" is declared by [${owners.join(', ')}] — discovery namespaces tool names by slug, so these collapse to one flat key and overwrite each other. Rename so the slug-prefixed names differ.`,\n );\n }\n }\n\n const reservedSlugs = new Set(firstParty.slugs ?? []);\n const reservedWidgets = new Set(firstParty.widgetIds ?? []);\n const reservedTools = new Set(firstParty.toolNames ?? []);\n\n for (const [slug, owners] of groupOwners(definitions, (d) => [d.slug])) {\n if (reservedSlugs.has(slug)) {\n collisions.push(\n `slug \"${slug}\" (declared by [${owners.join(', ')}]) collides with a first-party integration — pick a slug no built-in product uses.`,\n );\n }\n }\n for (const [id, owners] of widgetOwners) {\n if (reservedWidgets.has(id)) {\n collisions.push(\n `widget id \"${id}\" (declared by [${owners.join(', ')}]) collides with a first-party widget — the dashboard resolves widgets by id, so this would hijack it. Prefix with the integration slug.`,\n );\n }\n }\n for (const [name, owners] of toolOwners) {\n if (reservedTools.has(name)) {\n collisions.push(\n `effective tool name \"${name}\" (declared by [${owners.join(', ')}]) collides with a first-party tool — the flat, slug-namespaced tool registry would overwrite one with the other. Rename it.`,\n );\n }\n }\n\n if (collisions.length > 0) {\n throw new Error(\n `Integration definitions collide (${collisions.length} collision${collisions.length === 1 ? '' : 's'}):\\n` +\n collisions.map((line) => ` - ${line}`).join('\\n') +\n '\\nRename until every slug, widget id, and tool name is unique — the host registry would otherwise silently overwrite or drop a registration.',\n );\n }\n}\n\nfunction groupOwners(\n definitions: readonly DefinitionCollisionInput[],\n keysOf: (definition: DefinitionCollisionInput) => string[],\n): Map<string, string[]> {\n const owners = new Map<string, string[]>();\n for (const definition of definitions) {\n for (const key of keysOf(definition)) {\n owners.set(key, [...(owners.get(key) ?? []), definition.slug]);\n }\n }\n return owners;\n}\n"]}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deterministic identifiers derived from an integration's slug.
|
|
3
|
+
*
|
|
4
|
+
* The problem this solves: every hand-written seed in
|
|
5
|
+
* `apps/web/supabase/seeds/` invents a `products.id` by hand — hex-word puns
|
|
6
|
+
* (`0d80b007` for dropbox, `1ea7b007` for learnworlds) and random v4s — and
|
|
7
|
+
* nothing checks them for collisions or reproduces them anywhere else. A slug
|
|
8
|
+
* therefore maps to a DIFFERENT uuid in every environment it was seeded into
|
|
9
|
+
* by hand, and re-deriving one after the fact is impossible.
|
|
10
|
+
*
|
|
11
|
+
* Here a slug maps to the same uuid everywhere, forever, computed rather than
|
|
12
|
+
* chosen: RFC 4122 version 5 (SHA-1, name-based) under one fixed Ekanos
|
|
13
|
+
* namespace. The SDK, the seed generator, and any future gate all call this
|
|
14
|
+
* one function and agree by construction.
|
|
15
|
+
*
|
|
16
|
+
* Dependency-pure and isomorphic on purpose. This package is imported by
|
|
17
|
+
* `@ekanos/sdk` and `@kit/integrations-core`, both of which reach the browser
|
|
18
|
+
* bundle, so SHA-1 is implemented here in ~50 lines rather than pulled from
|
|
19
|
+
* `node:crypto` (server-only) or a dependency (this package depends on zod and
|
|
20
|
+
* nothing else).
|
|
21
|
+
*/
|
|
22
|
+
/**
|
|
23
|
+
* The standard RFC 4122 DNS namespace. Present only so
|
|
24
|
+
* {@link EKANOS_INTEGRATION_NAMESPACE} below is auditable rather than
|
|
25
|
+
* arbitrary — nothing else should derive ids under it.
|
|
26
|
+
*/
|
|
27
|
+
export declare const DNS_NAMESPACE = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
|
|
28
|
+
/**
|
|
29
|
+
* THE Ekanos integration namespace. Every id this module derives descends
|
|
30
|
+
* from it, so it is a permanent constant: changing it re-points every slug at
|
|
31
|
+
* a different uuid and orphans every row already written.
|
|
32
|
+
*
|
|
33
|
+
* It is not a hand-picked random value either — it is itself
|
|
34
|
+
* `uuidv5('ekanos.dev', DNS)`, which `__tests__/product-id.test.ts` asserts,
|
|
35
|
+
* so a reader can verify where it came from instead of trusting it.
|
|
36
|
+
*/
|
|
37
|
+
export declare const EKANOS_INTEGRATION_NAMESPACE = "269944fc-4736-5497-b751-381be92fb8df";
|
|
38
|
+
/**
|
|
39
|
+
* The uuid `products.id` MUST carry for this integration.
|
|
40
|
+
*
|
|
41
|
+
* Derived as `uuidv5(slug, EKANOS_INTEGRATION_NAMESPACE)` — the name is the
|
|
42
|
+
* bare slug, with no prefix, so the derivation is trivially reproducible by
|
|
43
|
+
* any uuid tool (`uuidgen`, python's `uuid.uuid5`) against the namespace above.
|
|
44
|
+
*/
|
|
45
|
+
export declare function deriveProductId(slug: string): string;
|
|
46
|
+
/**
|
|
47
|
+
* The uuid a named `plans` row for this integration MUST carry.
|
|
48
|
+
*
|
|
49
|
+
* Derived from `plan:<slug>:<planName>` under the same namespace. The prefix
|
|
50
|
+
* keeps the plan-id space disjoint from the product-id space: a bare slug is
|
|
51
|
+
* always the product, so no plan can ever collide with a product id.
|
|
52
|
+
*
|
|
53
|
+
* `planName` is lowercased before hashing, because `plans.name` is free text
|
|
54
|
+
* ('Default') while the id must not depend on how it was capitalised.
|
|
55
|
+
*/
|
|
56
|
+
export declare function derivePlanId(slug: string, planName: string): string;
|
|
57
|
+
/**
|
|
58
|
+
* RFC 4122 §4.3 version 5: SHA-1 over (namespace bytes ‖ UTF-8 name bytes),
|
|
59
|
+
* with the version and variant bits overwritten in the first 16 bytes.
|
|
60
|
+
*
|
|
61
|
+
* Exported so tests can check it against the RFC's published vectors — the
|
|
62
|
+
* only way to be sure the hand-rolled SHA-1 below is the real one.
|
|
63
|
+
*/
|
|
64
|
+
export declare function uuidv5(name: string, namespace: string): string;
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deterministic identifiers derived from an integration's slug.
|
|
3
|
+
*
|
|
4
|
+
* The problem this solves: every hand-written seed in
|
|
5
|
+
* `apps/web/supabase/seeds/` invents a `products.id` by hand — hex-word puns
|
|
6
|
+
* (`0d80b007` for dropbox, `1ea7b007` for learnworlds) and random v4s — and
|
|
7
|
+
* nothing checks them for collisions or reproduces them anywhere else. A slug
|
|
8
|
+
* therefore maps to a DIFFERENT uuid in every environment it was seeded into
|
|
9
|
+
* by hand, and re-deriving one after the fact is impossible.
|
|
10
|
+
*
|
|
11
|
+
* Here a slug maps to the same uuid everywhere, forever, computed rather than
|
|
12
|
+
* chosen: RFC 4122 version 5 (SHA-1, name-based) under one fixed Ekanos
|
|
13
|
+
* namespace. The SDK, the seed generator, and any future gate all call this
|
|
14
|
+
* one function and agree by construction.
|
|
15
|
+
*
|
|
16
|
+
* Dependency-pure and isomorphic on purpose. This package is imported by
|
|
17
|
+
* `@ekanos/sdk` and `@kit/integrations-core`, both of which reach the browser
|
|
18
|
+
* bundle, so SHA-1 is implemented here in ~50 lines rather than pulled from
|
|
19
|
+
* `node:crypto` (server-only) or a dependency (this package depends on zod and
|
|
20
|
+
* nothing else).
|
|
21
|
+
*/
|
|
22
|
+
/**
|
|
23
|
+
* The standard RFC 4122 DNS namespace. Present only so
|
|
24
|
+
* {@link EKANOS_INTEGRATION_NAMESPACE} below is auditable rather than
|
|
25
|
+
* arbitrary — nothing else should derive ids under it.
|
|
26
|
+
*/
|
|
27
|
+
export const DNS_NAMESPACE = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
|
|
28
|
+
/**
|
|
29
|
+
* THE Ekanos integration namespace. Every id this module derives descends
|
|
30
|
+
* from it, so it is a permanent constant: changing it re-points every slug at
|
|
31
|
+
* a different uuid and orphans every row already written.
|
|
32
|
+
*
|
|
33
|
+
* It is not a hand-picked random value either — it is itself
|
|
34
|
+
* `uuidv5('ekanos.dev', DNS)`, which `__tests__/product-id.test.ts` asserts,
|
|
35
|
+
* so a reader can verify where it came from instead of trusting it.
|
|
36
|
+
*/
|
|
37
|
+
export const EKANOS_INTEGRATION_NAMESPACE = '269944fc-4736-5497-b751-381be92fb8df';
|
|
38
|
+
/**
|
|
39
|
+
* The slug shape `IntegrationDefinitionSchema` accepts. Re-stated (not
|
|
40
|
+
* imported) so this module stays a leaf: derivation must reject anything the
|
|
41
|
+
* definition schema would, because `deriveProductId('Acme')` and
|
|
42
|
+
* `deriveProductId('acme')` are different uuids and only one of them is the
|
|
43
|
+
* product.
|
|
44
|
+
*/
|
|
45
|
+
const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
46
|
+
function assertSlug(slug, what) {
|
|
47
|
+
if (!SLUG.test(slug)) {
|
|
48
|
+
throw new Error(`Cannot derive a ${what} from "${slug}": slugs are kebab-case ` +
|
|
49
|
+
`([a-z0-9] segments separated by single hyphens), e.g. "acme-crm". ` +
|
|
50
|
+
`Derivation is case- and punctuation-sensitive, so a slug that differs ` +
|
|
51
|
+
`only in case would silently become a different product.`);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* The uuid `products.id` MUST carry for this integration.
|
|
56
|
+
*
|
|
57
|
+
* Derived as `uuidv5(slug, EKANOS_INTEGRATION_NAMESPACE)` — the name is the
|
|
58
|
+
* bare slug, with no prefix, so the derivation is trivially reproducible by
|
|
59
|
+
* any uuid tool (`uuidgen`, python's `uuid.uuid5`) against the namespace above.
|
|
60
|
+
*/
|
|
61
|
+
export function deriveProductId(slug) {
|
|
62
|
+
assertSlug(slug, 'product id');
|
|
63
|
+
return uuidv5(slug, EKANOS_INTEGRATION_NAMESPACE);
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* The uuid a named `plans` row for this integration MUST carry.
|
|
67
|
+
*
|
|
68
|
+
* Derived from `plan:<slug>:<planName>` under the same namespace. The prefix
|
|
69
|
+
* keeps the plan-id space disjoint from the product-id space: a bare slug is
|
|
70
|
+
* always the product, so no plan can ever collide with a product id.
|
|
71
|
+
*
|
|
72
|
+
* `planName` is lowercased before hashing, because `plans.name` is free text
|
|
73
|
+
* ('Default') while the id must not depend on how it was capitalised.
|
|
74
|
+
*/
|
|
75
|
+
export function derivePlanId(slug, planName) {
|
|
76
|
+
assertSlug(slug, 'plan id');
|
|
77
|
+
const normalized = planName.trim().toLowerCase();
|
|
78
|
+
if (normalized.length === 0) {
|
|
79
|
+
throw new Error(`Cannot derive a plan id for "${slug}": planName must be a non-empty string (e.g. "Default").`);
|
|
80
|
+
}
|
|
81
|
+
return uuidv5(`plan:${slug}:${normalized}`, EKANOS_INTEGRATION_NAMESPACE);
|
|
82
|
+
}
|
|
83
|
+
// ---- RFC 4122 v5 ------------------------------------------------------------
|
|
84
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
85
|
+
/**
|
|
86
|
+
* RFC 4122 §4.3 version 5: SHA-1 over (namespace bytes ‖ UTF-8 name bytes),
|
|
87
|
+
* with the version and variant bits overwritten in the first 16 bytes.
|
|
88
|
+
*
|
|
89
|
+
* Exported so tests can check it against the RFC's published vectors — the
|
|
90
|
+
* only way to be sure the hand-rolled SHA-1 below is the real one.
|
|
91
|
+
*/
|
|
92
|
+
export function uuidv5(name, namespace) {
|
|
93
|
+
var _a, _b;
|
|
94
|
+
if (!UUID.test(namespace)) {
|
|
95
|
+
throw new Error(`uuidv5 namespace "${namespace}" is not a uuid — pass the canonical 8-4-4-4-12 hex form.`);
|
|
96
|
+
}
|
|
97
|
+
const namespaceBytes = uuidToBytes(namespace);
|
|
98
|
+
const nameBytes = new TextEncoder().encode(name);
|
|
99
|
+
const input = new Uint8Array(namespaceBytes.length + nameBytes.length);
|
|
100
|
+
input.set(namespaceBytes, 0);
|
|
101
|
+
input.set(nameBytes, namespaceBytes.length);
|
|
102
|
+
const hash = sha1(input);
|
|
103
|
+
// Version 5 in the high nibble of byte 6; RFC 4122 variant (10xx) in byte 8.
|
|
104
|
+
hash[6] = (((_a = hash[6]) !== null && _a !== void 0 ? _a : 0) & 0x0f) | 0x50;
|
|
105
|
+
hash[8] = (((_b = hash[8]) !== null && _b !== void 0 ? _b : 0) & 0x3f) | 0x80;
|
|
106
|
+
const hex = [...hash.slice(0, 16)]
|
|
107
|
+
.map((byte) => byte.toString(16).padStart(2, '0'))
|
|
108
|
+
.join('');
|
|
109
|
+
return [
|
|
110
|
+
hex.slice(0, 8),
|
|
111
|
+
hex.slice(8, 12),
|
|
112
|
+
hex.slice(12, 16),
|
|
113
|
+
hex.slice(16, 20),
|
|
114
|
+
hex.slice(20, 32),
|
|
115
|
+
].join('-');
|
|
116
|
+
}
|
|
117
|
+
function uuidToBytes(uuid) {
|
|
118
|
+
const hex = uuid.replace(/-/g, '');
|
|
119
|
+
const bytes = new Uint8Array(16);
|
|
120
|
+
for (let i = 0; i < 16; i += 1) {
|
|
121
|
+
bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
122
|
+
}
|
|
123
|
+
return bytes;
|
|
124
|
+
}
|
|
125
|
+
function rotl(value, shift) {
|
|
126
|
+
return ((value << shift) | (value >>> (32 - shift))) >>> 0;
|
|
127
|
+
}
|
|
128
|
+
/** FIPS 180-4 SHA-1. Returns the 20-byte digest. */
|
|
129
|
+
function sha1(message) {
|
|
130
|
+
var _a, _b, _c, _d, _e;
|
|
131
|
+
const bitLength = message.length * 8;
|
|
132
|
+
// Padded to a multiple of 64 with room for the 0x80 marker and the 8-byte
|
|
133
|
+
// big-endian length: (len + 1 + 8) rounded up to the next 64.
|
|
134
|
+
const padded = new Uint8Array(Math.ceil((message.length + 9) / 64) * 64);
|
|
135
|
+
padded.set(message, 0);
|
|
136
|
+
padded[message.length] = 0x80;
|
|
137
|
+
const view = new DataView(padded.buffer);
|
|
138
|
+
view.setUint32(padded.length - 8, Math.floor(bitLength / 4294967296), false);
|
|
139
|
+
view.setUint32(padded.length - 4, bitLength >>> 0, false);
|
|
140
|
+
let h0 = 0x67452301;
|
|
141
|
+
let h1 = 0xefcdab89;
|
|
142
|
+
let h2 = 0x98badcfe;
|
|
143
|
+
let h3 = 0x10325476;
|
|
144
|
+
let h4 = 0xc3d2e1f0;
|
|
145
|
+
const w = new Array(80).fill(0);
|
|
146
|
+
for (let offset = 0; offset < padded.length; offset += 64) {
|
|
147
|
+
for (let i = 0; i < 16; i += 1) {
|
|
148
|
+
w[i] = view.getUint32(offset + i * 4, false);
|
|
149
|
+
}
|
|
150
|
+
for (let i = 16; i < 80; i += 1) {
|
|
151
|
+
w[i] = rotl(((_a = w[i - 3]) !== null && _a !== void 0 ? _a : 0) ^ ((_b = w[i - 8]) !== null && _b !== void 0 ? _b : 0) ^ ((_c = w[i - 14]) !== null && _c !== void 0 ? _c : 0) ^ ((_d = w[i - 16]) !== null && _d !== void 0 ? _d : 0), 1);
|
|
152
|
+
}
|
|
153
|
+
let a = h0;
|
|
154
|
+
let b = h1;
|
|
155
|
+
let c = h2;
|
|
156
|
+
let d = h3;
|
|
157
|
+
let e = h4;
|
|
158
|
+
for (let i = 0; i < 80; i += 1) {
|
|
159
|
+
let f;
|
|
160
|
+
let k;
|
|
161
|
+
if (i < 20) {
|
|
162
|
+
f = ((b & c) | (~b & d)) >>> 0;
|
|
163
|
+
k = 0x5a827999;
|
|
164
|
+
}
|
|
165
|
+
else if (i < 40) {
|
|
166
|
+
f = (b ^ c ^ d) >>> 0;
|
|
167
|
+
k = 0x6ed9eba1;
|
|
168
|
+
}
|
|
169
|
+
else if (i < 60) {
|
|
170
|
+
f = ((b & c) | (b & d) | (c & d)) >>> 0;
|
|
171
|
+
k = 0x8f1bbcdc;
|
|
172
|
+
}
|
|
173
|
+
else {
|
|
174
|
+
f = (b ^ c ^ d) >>> 0;
|
|
175
|
+
k = 0xca62c1d6;
|
|
176
|
+
}
|
|
177
|
+
// Every term is < 2^32, so the five-way sum stays well inside the
|
|
178
|
+
// 2^53 exact-integer range; >>> 0 folds it back to uint32.
|
|
179
|
+
const temp = (rotl(a, 5) + f + e + k + ((_e = w[i]) !== null && _e !== void 0 ? _e : 0)) >>> 0;
|
|
180
|
+
e = d;
|
|
181
|
+
d = c;
|
|
182
|
+
c = rotl(b, 30);
|
|
183
|
+
b = a;
|
|
184
|
+
a = temp;
|
|
185
|
+
}
|
|
186
|
+
h0 = (h0 + a) >>> 0;
|
|
187
|
+
h1 = (h1 + b) >>> 0;
|
|
188
|
+
h2 = (h2 + c) >>> 0;
|
|
189
|
+
h3 = (h3 + d) >>> 0;
|
|
190
|
+
h4 = (h4 + e) >>> 0;
|
|
191
|
+
}
|
|
192
|
+
const digest = new Uint8Array(20);
|
|
193
|
+
const digestView = new DataView(digest.buffer);
|
|
194
|
+
digestView.setUint32(0, h0, false);
|
|
195
|
+
digestView.setUint32(4, h1, false);
|
|
196
|
+
digestView.setUint32(8, h2, false);
|
|
197
|
+
digestView.setUint32(12, h3, false);
|
|
198
|
+
digestView.setUint32(16, h4, false);
|
|
199
|
+
return digest;
|
|
200
|
+
}
|
|
201
|
+
//# sourceMappingURL=product-id.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"product-id.js","sourceRoot":"","sources":["../src/product-id.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH;;;;GAIG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,sCAAsC,CAAC;AAEpE;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,4BAA4B,GACvC,sCAAsC,CAAC;AAEzC;;;;;;GAMG;AACH,MAAM,IAAI,GAAG,4BAA4B,CAAC;AAE1C,SAAS,UAAU,CAAC,IAAY,EAAE,IAAY;IAC5C,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QACrB,MAAM,IAAI,KAAK,CACb,mBAAmB,IAAI,UAAU,IAAI,0BAA0B;YAC7D,oEAAoE;YACpE,wEAAwE;YACxE,yDAAyD,CAC5D,CAAC;IACJ,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,eAAe,CAAC,IAAY;IAC1C,UAAU,CAA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AE,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC;QACpB,EAAE,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC;QACpB,EAAE,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC;IACtB,CAAC;IAED,MAAM,MAAM,GAAG,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;IAClC,MAAM,UAAU,GAAG,IAAI,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IAC/C,UAAU,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;IACnC,UAAU,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;IACnC,UAAU,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;IACnC,UAAU,CAAC,SAAS,CAAC,EAAE,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;IACpC,UAAU,CAAC,SAAS,CAAC,EAAE,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;IACpC,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["/**\n * Deterministic identifiers derived from an integration's slug.\n *\n * The problem this solves: every hand-written seed in\n * `apps/web/supabase/seeds/` invents a `products.id` by hand — hex-word puns\n * (`0d80b007` for dropbox, `1ea7b007` for learnworlds) and random v4s — and\n * nothing checks them for collisions or reproduces them anywhere else. A slug\n * therefore maps to a DIFFERENT uuid in every environment it was seeded into\n * by hand, and re-deriving one after the fact is impossible.\n *\n * Here a slug maps to the same uuid everywhere, forever, computed rather than\n * chosen: RFC 4122 version 5 (SHA-1, name-based) under one fixed Ekanos\n * namespace. The SDK, the seed generator, and any future gate all call this\n * one function and agree by construction.\n *\n * Dependency-pure and isomorphic on purpose. This package is imported by\n * `@ekanos/sdk` and `@kit/integrations-core`, both of which reach the browser\n * bundle, so SHA-1 is implemented here in ~50 lines rather than pulled from\n * `node:crypto` (server-only) or a dependency (this package depends on zod and\n * nothing else).\n */\n\n/**\n * The standard RFC 4122 DNS namespace. Present only so\n * {@link EKANOS_INTEGRATION_NAMESPACE} below is auditable rather than\n * arbitrary — nothing else should derive ids under it.\n */\nexport const DNS_NAMESPACE = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';\n\n/**\n * THE Ekanos integration namespace. Every id this module derives descends\n * from it, so it is a permanent constant: changing it re-points every slug at\n * a different uuid and orphans every row already written.\n *\n * It is not a hand-picked random value either — it is itself\n * `uuidv5('ekanos.dev', DNS)`, which `__tests__/product-id.test.ts` asserts,\n * so a reader can verify where it came from instead of trusting it.\n */\nexport const EKANOS_INTEGRATION_NAMESPACE =\n '269944fc-4736-5497-b751-381be92fb8df';\n\n/**\n * The slug shape `IntegrationDefinitionSchema` accepts. Re-stated (not\n * imported) so this module stays a leaf: derivation must reject anything the\n * definition schema would, because `deriveProductId('Acme')` and\n * `deriveProductId('acme')` are different uuids and only one of them is the\n * product.\n */\nconst SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\n\nfunction assertSlug(slug: string, what: string): void {\n if (!SLUG.test(slug)) {\n throw new Error(\n `Cannot derive a ${what} from \"${slug}\": slugs are kebab-case ` +\n `([a-z0-9] segments separated by single hyphens), e.g. \"acme-crm\". ` +\n `Derivation is case- and punctuation-sensitive, so a slug that differs ` +\n `only in case would silently become a different product.`,\n );\n }\n}\n\n/**\n * The uuid `products.id` MUST carry for this integration.\n *\n * Derived as `uuidv5(slug, EKANOS_INTEGRATION_NAMESPACE)` — the name is the\n * bare slug, with no prefix, so the derivation is trivially reproducible by\n * any uuid tool (`uuidgen`, python's `uuid.uuid5`) against the namespace above.\n */\nexport function deriveProductId(slug: string): string {\n assertSlug(slug, 'product id');\n return uuidv5(slug, EKANOS_INTEGRATION_NAMESPACE);\n}\n\n/**\n * The uuid a named `plans` row for this integration MUST carry.\n *\n * Derived from `plan:<slug>:<planName>` under the same namespace. The prefix\n * keeps the plan-id space disjoint from the product-id space: a bare slug is\n * always the product, so no plan can ever collide with a product id.\n *\n * `planName` is lowercased before hashing, because `plans.name` is free text\n * ('Default') while the id must not depend on how it was capitalised.\n */\nexport function derivePlanId(slug: string, planName: string): string {\n assertSlug(slug, 'plan id');\n const normalized = planName.trim().toLowerCase();\n if (normalized.length === 0) {\n throw new Error(\n `Cannot derive a plan id for \"${slug}\": planName must be a non-empty string (e.g. \"Default\").`,\n );\n }\n return uuidv5(`plan:${slug}:${normalized}`, EKANOS_INTEGRATION_NAMESPACE);\n}\n\n// ---- RFC 4122 v5 ------------------------------------------------------------\n\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/**\n * RFC 4122 §4.3 version 5: SHA-1 over (namespace bytes ‖ UTF-8 name bytes),\n * with the version and variant bits overwritten in the first 16 bytes.\n *\n * Exported so tests can check it against the RFC's published vectors — the\n * only way to be sure the hand-rolled SHA-1 below is the real one.\n */\nexport function uuidv5(name: string, namespace: string): string {\n if (!UUID.test(namespace)) {\n throw new Error(\n `uuidv5 namespace \"${namespace}\" is not a uuid — pass the canonical 8-4-4-4-12 hex form.`,\n );\n }\n\n const namespaceBytes = uuidToBytes(namespace);\n const nameBytes = new TextEncoder().encode(name);\n const input = new Uint8Array(namespaceBytes.length + nameBytes.length);\n input.set(namespaceBytes, 0);\n input.set(nameBytes, namespaceBytes.length);\n\n const hash = sha1(input);\n // Version 5 in the high nibble of byte 6; RFC 4122 variant (10xx) in byte 8.\n hash[6] = ((hash[6] ?? 0) & 0x0f) | 0x50;\n hash[8] = ((hash[8] ?? 0) & 0x3f) | 0x80;\n\n const hex = [...hash.slice(0, 16)]\n .map((byte) => byte.toString(16).padStart(2, '0'))\n .join('');\n\n return [\n hex.slice(0, 8),\n hex.slice(8, 12),\n hex.slice(12, 16),\n hex.slice(16, 20),\n hex.slice(20, 32),\n ].join('-');\n}\n\nfunction uuidToBytes(uuid: string): Uint8Array {\n const hex = uuid.replace(/-/g, '');\n const bytes = new Uint8Array(16);\n for (let i = 0; i < 16; i += 1) {\n bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\nfunction rotl(value: number, shift: number): number {\n return ((value << shift) | (value >>> (32 - shift))) >>> 0;\n}\n\n/** FIPS 180-4 SHA-1. Returns the 20-byte digest. */\nfunction sha1(message: Uint8Array): Uint8Array {\n const bitLength = message.length * 8;\n // Padded to a multiple of 64 with room for the 0x80 marker and the 8-byte\n // big-endian length: (len + 1 + 8) rounded up to the next 64.\n const padded = new Uint8Array(Math.ceil((message.length + 9) / 64) * 64);\n padded.set(message, 0);\n padded[message.length] = 0x80;\n\n const view = new DataView(padded.buffer);\n view.setUint32(\n padded.length - 8,\n Math.floor(bitLength / 0x1_0000_0000),\n false,\n );\n view.setUint32(padded.length - 4, bitLength >>> 0, false);\n\n let h0 = 0x67452301;\n let h1 = 0xefcdab89;\n let h2 = 0x98badcfe;\n let h3 = 0x10325476;\n let h4 = 0xc3d2e1f0;\n\n const w = new Array<number>(80).fill(0);\n\n for (let offset = 0; offset < padded.length; offset += 64) {\n for (let i = 0; i < 16; i += 1) {\n w[i] = view.getUint32(offset + i * 4, false);\n }\n for (let i = 16; i < 80; i += 1) {\n w[i] = rotl(\n (w[i - 3] ?? 0) ^ (w[i - 8] ?? 0) ^ (w[i - 14] ?? 0) ^ (w[i - 16] ?? 0),\n 1,\n );\n }\n\n let a = h0;\n let b = h1;\n let c = h2;\n let d = h3;\n let e = h4;\n\n for (let i = 0; i < 80; i += 1) {\n let f: number;\n let k: number;\n if (i < 20) {\n f = ((b & c) | (~b & d)) >>> 0;\n k = 0x5a827999;\n } else if (i < 40) {\n f = (b ^ c ^ d) >>> 0;\n k = 0x6ed9eba1;\n } else if (i < 60) {\n f = ((b & c) | (b & d) | (c & d)) >>> 0;\n k = 0x8f1bbcdc;\n } else {\n f = (b ^ c ^ d) >>> 0;\n k = 0xca62c1d6;\n }\n\n // Every term is < 2^32, so the five-way sum stays well inside the\n // 2^53 exact-integer range; >>> 0 folds it back to uint32.\n const temp = (rotl(a, 5) + f + e + k + (w[i] ?? 0)) >>> 0;\n e = d;\n d = c;\n c = rotl(b, 30);\n b = a;\n a = temp;\n }\n\n h0 = (h0 + a) >>> 0;\n h1 = (h1 + b) >>> 0;\n h2 = (h2 + c) >>> 0;\n h3 = (h3 + d) >>> 0;\n h4 = (h4 + e) >>> 0;\n }\n\n const digest = new Uint8Array(20);\n const digestView = new DataView(digest.buffer);\n digestView.setUint32(0, h0, false);\n digestView.setUint32(4, h1, false);\n digestView.setUint32(8, h2, false);\n digestView.setUint32(12, h3, false);\n digestView.setUint32(16, h4, false);\n return digest;\n}\n"]}
|