@kelpie/server 0.3.1 → 0.4.1

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.
@@ -120,6 +120,13 @@
120
120
  "when": 1786410884983,
121
121
  "tag": "0016_misty_mentor",
122
122
  "breakpoints": true
123
+ },
124
+ {
125
+ "idx": 17,
126
+ "version": "7",
127
+ "when": 1786490413323,
128
+ "tag": "0017_drop_integration_connections",
129
+ "breakpoints": true
123
130
  }
124
131
  ]
125
- }
132
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kelpie/server",
3
- "version": "0.3.1",
3
+ "version": "0.4.1",
4
4
  "description": "The Kelpie service as a library: module runtime, core CRM modules, REST API, MCP surface, and the shared migration pipeline.",
5
5
  "keywords": [
6
6
  "kelpie",
@@ -52,16 +52,18 @@
52
52
  },
53
53
  "dependencies": {
54
54
  "@hono/node-server": "^2.0.12",
55
- "@kelpie/schemas": "^0.3.1",
55
+ "@kelpie/schemas": "^0.4.1",
56
56
  "@node-rs/argon2": "^2.0.2",
57
57
  "drizzle-orm": "^0.45.2",
58
58
  "hono": "^4.12.32",
59
+ "nodemailer": "^9.0.5",
59
60
  "postgres": "^3.4.9",
60
61
  "ulid": "^3.0.2",
61
62
  "zod": "^4.4.3"
62
63
  },
63
64
  "devDependencies": {
64
65
  "@types/node": "^26.1.2",
66
+ "@types/nodemailer": "^8.0.1",
65
67
  "drizzle-kit": "^0.31.10",
66
68
  "vite": "^8.2.0",
67
69
  "vitest": "^4.1.10"
package/src/lib/config.ts CHANGED
@@ -69,31 +69,41 @@ const environmentSchema = z.object({
69
69
  LOG_LEVEL: z.enum(['debug', 'info', 'warn', 'error']),
70
70
  KELPIE_MODULE_CONFIG_PATH: z.string().min(1).optional(),
71
71
  WEB_BUNDLE_DIR: z.string().min(1).optional(),
72
- ...emailConfigSchema.shape,
73
72
  ...rateLimitConfigSchema.shape,
74
73
  })
75
74
 
76
75
  /**
77
76
  * Parses an environment into a validated config.
78
77
  *
78
+ * `emailConfigSchema` is a discriminated union, so it is parsed separately
79
+ * from the rest: a union has no flat `.shape` to spread into `environmentSchema`,
80
+ * only its own `EMAIL_PROVIDER`-keyed branches. Problems from both parses are
81
+ * combined into one error, preserving the "every missing variable at once" rule.
82
+ *
79
83
  * @param environment Raw variables, normally `process.env`.
80
84
  * @throws ConfigurationError listing every invalid or missing variable.
81
85
  */
82
86
  export function loadConfig(environment: Environment): KelpieConfig {
83
- const result = environmentSchema.safeParse(environment)
87
+ const environmentResult = environmentSchema.safeParse(environment)
88
+ const emailResult = emailConfigSchema.safeParse(environment)
89
+
90
+ if (!environmentResult.success || !emailResult.success) {
91
+ const problems = [
92
+ ...(environmentResult.success ? [] : environmentResult.error.issues.map(describeValidationIssue)),
93
+ ...(emailResult.success ? [] : emailResult.error.issues.map(describeValidationIssue)),
94
+ ]
84
95
 
85
- if (!result.success) {
86
- throw new ConfigurationError(result.error.issues.map(describeValidationIssue))
96
+ throw new ConfigurationError(problems)
87
97
  }
88
98
 
89
99
  return {
90
- runtimeMode: result.data.NODE_ENV,
91
- port: result.data.PORT,
92
- databaseUrl: result.data.DATABASE_URL,
93
- logLevel: result.data.LOG_LEVEL,
94
- email: { EMAIL_PROVIDER: result.data.EMAIL_PROVIDER, EMAIL_FROM: result.data.EMAIL_FROM },
95
- moduleConfigPath: result.data.KELPIE_MODULE_CONFIG_PATH,
96
- webBundleDirectory: result.data.WEB_BUNDLE_DIR,
97
- rateLimit: rateLimitConfigFrom(result.data),
100
+ runtimeMode: environmentResult.data.NODE_ENV,
101
+ port: environmentResult.data.PORT,
102
+ databaseUrl: environmentResult.data.DATABASE_URL,
103
+ logLevel: environmentResult.data.LOG_LEVEL,
104
+ email: emailResult.data,
105
+ moduleConfigPath: environmentResult.data.KELPIE_MODULE_CONFIG_PATH,
106
+ webBundleDirectory: environmentResult.data.WEB_BUNDLE_DIR,
107
+ rateLimit: rateLimitConfigFrom(environmentResult.data),
98
108
  }
99
109
  }
package/src/lib/email.ts CHANGED
@@ -1,5 +1,7 @@
1
+ import nodemailer from 'nodemailer'
1
2
  import { z } from 'zod'
2
3
 
4
+ import { describeThrown } from './errors.ts'
3
5
  import type { Logger } from './logger.ts'
4
6
 
5
7
  /**
@@ -7,9 +9,15 @@ import type { Logger } from './logger.ts'
7
9
  * and account-change notifications, nothing else. Kelpie never sends outreach
8
10
  * email.
9
11
  *
10
- * Roadmap decision 4: the provider is configured, never hardcoded. Core ships the
11
- * port and the `log` provider. Real providers ship as modules, so the open-source
12
- * assembly has no vendor account baked into it.
12
+ * Roadmap decision 4: the provider is configured, never hardcoded. Core ships
13
+ * the port and two providers, `log` and `smtp`. Both need no vendor account a
14
+ * deployment doesn't already have, which is what keeps them in core rather than
15
+ * a module, per `modules.md`'s split test. A provider that does need one
16
+ * (Resend, Postmark, Mailtrap, SendGrid) is a commercial integration under that
17
+ * same test and belongs in a module: it supplies its own `EmailSender` from its
18
+ * own config, and an assembly's entry point wires it into `services.email` in
19
+ * place of `createEmailSender`, the same way `kelpie-cloud/src/server.ts` wires
20
+ * this one today.
13
21
  */
14
22
 
15
23
  export interface EmailMessage {
@@ -22,12 +30,28 @@ export interface EmailSender {
22
30
  send(message: EmailMessage): Promise<void>
23
31
  }
24
32
 
25
- export const emailConfigSchema = z.object({
26
- EMAIL_PROVIDER: z.enum(['log']),
33
+ const logEmailConfigSchema = z.object({
34
+ EMAIL_PROVIDER: z.literal('log'),
27
35
  EMAIL_FROM: z.string().min(1),
28
36
  })
29
37
 
38
+ const smtpEmailConfigSchema = z.object({
39
+ EMAIL_PROVIDER: z.literal('smtp'),
40
+ EMAIL_FROM: z.string().min(1),
41
+ SMTP_HOST: z.string().min(1),
42
+ SMTP_PORT: z.coerce.number().int().positive().max(65535),
43
+ SMTP_SECURE: z.enum(['true', 'false']).transform((value) => value === 'true'),
44
+ SMTP_USER: z.string().min(1),
45
+ SMTP_PASSWORD: z.string().min(1),
46
+ })
47
+
48
+ export const emailConfigSchema = z.discriminatedUnion('EMAIL_PROVIDER', [
49
+ logEmailConfigSchema,
50
+ smtpEmailConfigSchema,
51
+ ])
52
+
30
53
  export type EmailConfig = z.infer<typeof emailConfigSchema>
54
+ export type SmtpEmailConfig = z.infer<typeof smtpEmailConfigSchema>
31
55
 
32
56
  /**
33
57
  * Writes the message to the log instead of sending it. For self-hosted
@@ -51,15 +75,59 @@ export function createLogEmailSender(logger: Logger, from: string): EmailSender
51
75
  }
52
76
  }
53
77
 
78
+ /**
79
+ * What `createSmtpEmailSender` sends a message through. A real deployment gets
80
+ * one backed by `nodemailer`; a test injects one that records calls, so the
81
+ * sender is verifiable without a container running a real SMTP conversation.
82
+ */
83
+ export interface SmtpTransport {
84
+ sendMail(message: { from: string; to: string; subject: string; text: string }): Promise<unknown>
85
+ }
86
+
87
+ function createNodemailerTransport(config: SmtpEmailConfig): SmtpTransport {
88
+ return nodemailer.createTransport({
89
+ host: config.SMTP_HOST,
90
+ port: config.SMTP_PORT,
91
+ secure: config.SMTP_SECURE,
92
+ auth: { user: config.SMTP_USER, pass: config.SMTP_PASSWORD },
93
+ })
94
+ }
95
+
96
+ /** Sends over SMTP. `transport` defaults to a real connection built from `config`. */
97
+ export function createSmtpEmailSender(
98
+ config: SmtpEmailConfig,
99
+ logger: Logger,
100
+ transport: SmtpTransport = createNodemailerTransport(config),
101
+ ): EmailSender {
102
+ return {
103
+ async send(message) {
104
+ try {
105
+ await transport.sendMail({
106
+ from: config.EMAIL_FROM,
107
+ to: message.to,
108
+ subject: message.subject,
109
+ text: message.body,
110
+ })
111
+ } catch (cause) {
112
+ const reason = describeThrown(cause)
113
+ logger.error('smtp send failed', { to: message.to, reason })
114
+ throw new Error(`Failed to send email to ${message.to} over SMTP: ${reason}`, { cause })
115
+ }
116
+ },
117
+ }
118
+ }
119
+
54
120
  /**
55
121
  * Builds the configured sender.
56
122
  *
57
- * @throws Never. An unknown provider cannot reach here: the config schema is an
58
- * enum, so boot rejects it first.
123
+ * @throws Never. An unknown provider cannot reach here: the config schema is a
124
+ * discriminated union, so boot rejects it first.
59
125
  */
60
126
  export function createEmailSender(config: EmailConfig, logger: Logger): EmailSender {
61
127
  switch (config.EMAIL_PROVIDER) {
62
128
  case 'log':
63
129
  return createLogEmailSender(logger, config.EMAIL_FROM)
130
+ case 'smtp':
131
+ return createSmtpEmailSender(config, logger)
64
132
  }
65
133
  }
package/src/lib/ids.ts CHANGED
@@ -36,7 +36,6 @@ export const idPrefixes = {
36
36
  agentRegistration: 'ag',
37
37
  agentRun: 'run',
38
38
  importJob: 'imp',
39
- integrationConnection: 'int',
40
39
  /** Never returns over the wire either: identified by `(workspace_id, module_id)` instead. */
41
40
  moduleSetting: 'mset',
42
41
  /**
@@ -13,7 +13,6 @@ import { createFormsModule } from './forms/index.ts'
13
13
  import { createHandbookModule } from './handbook/index.ts'
14
14
  import { createHiringModule } from './hiring/index.ts'
15
15
  import { createImportExportModule } from './import-export/index.ts'
16
- import * as integrations from './integrations/schema.ts'
17
16
  import { createNotesModule } from './notes/index.ts'
18
17
  import { createOpportunitiesModule } from './opportunities/index.ts'
19
18
  import { createPartnershipsModule } from './partnerships/index.ts'
@@ -40,21 +39,6 @@ import { createWorkspaceModule } from './workspace/index.ts'
40
39
  */
41
40
  export const coreMigrationsDirectory = fileURLToPath(new URL('../../migrations', import.meta.url))
42
41
 
43
- interface CoreModuleDefinition {
44
- readonly id: string
45
- readonly requires?: readonly string[]
46
- readonly tables: Readonly<Record<string, unknown>>
47
- }
48
-
49
- const definitions: readonly CoreModuleDefinition[] = [
50
- { id: 'integrations', requires: ['workspace'], tables: integrations },
51
- ]
52
-
53
- /**
54
- * Modules with behaviour are written out; the rest contribute only tables so far
55
- * and are generated from the table above. As each grows routes and services it
56
- * moves out of `definitions` into its own module file, like `auth` has.
57
- */
58
42
  export const coreModules: readonly KelpieModule[] = [
59
43
  createAuthModule(coreMigrationsDirectory),
60
44
  createWorkspaceModule(coreMigrationsDirectory),
@@ -81,13 +65,4 @@ export const coreModules: readonly KelpieModule[] = [
81
65
  createImportExportModule(coreMigrationsDirectory),
82
66
  createAgentTasksModule(coreMigrationsDirectory),
83
67
  createWebhooksModule(coreMigrationsDirectory),
84
- ...definitions.map((definition): KelpieModule => ({
85
- id: definition.id,
86
- ...(definition.requires === undefined ? {} : { requires: definition.requires }),
87
- register(context) {
88
- context.schema(definition.tables, coreMigrationsDirectory)
89
-
90
- return Promise.resolve()
91
- },
92
- })),
93
68
  ]
@@ -4,7 +4,6 @@ import type { Database } from '../lib/database.ts'
4
4
  import { SecretDecryptionError } from '../lib/secrets.ts'
5
5
  import type { SecretCipher } from '../lib/secrets.ts'
6
6
  import { agentRegistrations } from './agent-tasks/schema.ts'
7
- import { integrationConnections } from './integrations/schema.ts'
8
7
  import { webhooks } from './webhooks/schema.ts'
9
8
 
10
9
  /**
@@ -37,18 +36,20 @@ interface SealedColumn {
37
36
  }
38
37
 
39
38
  /**
40
- * Every column holding a value sealed by `lib/secrets.ts`.
39
+ * Every column in core's schema holding a value sealed by `lib/secrets.ts`.
41
40
  *
42
- * All three that exist are here, including the two nothing writes yet. Covering
43
- * a column before its first write is the cheap half of this: the expensive half
44
- * is noticing, a year later, that a rotation reported success while stranding a
45
- * customer's stored OAuth credential with no way back. `resealTest` asserts this
46
- * list against the schema, so a fourth `_encrypted` column fails a test the day
47
- * it is added rather than at the next rotation.
41
+ * All three that exist are here, including `agent_registrations`, which nothing
42
+ * writes yet. Covering a column before its first write is the cheap half of
43
+ * this: the expensive half is noticing, a year later, that a rotation reported
44
+ * success while stranding a customer's stored credential with no way back. The
45
+ * test asserts this list against the schema, so a fourth `_encrypted` column
46
+ * fails the day it is added rather than at the next rotation.
48
47
  *
49
48
  * There is no registry for modules to declare these through, on purpose. One
50
49
  * caller does not need an extension point, and a sealed column that nothing
51
- * re-seals is a bug whichever way it was registered.
50
+ * re-seals is a bug whichever way it was registered. A module outside core
51
+ * seals under the same key through `createSecretCipher` and brings its own pass
52
+ * over its own tables, which this one cannot see.
52
53
  */
53
54
  const SEALED_COLUMNS: readonly SealedColumn[] = [
54
55
  {
@@ -79,19 +80,6 @@ const SEALED_COLUMNS: readonly SealedColumn[] = [
79
80
  .where(eq(agentRegistrations.id, id))
80
81
  },
81
82
  },
82
- {
83
- label: 'integration_connections.secrets_encrypted',
84
- read: async (db) =>
85
- db
86
- .select({ id: integrationConnections.id, sealed: integrationConnections.secretsEncrypted })
87
- .from(integrationConnections),
88
- write: async (db, id, sealed) => {
89
- await db
90
- .update(integrationConnections)
91
- .set({ secretsEncrypted: sealed })
92
- .where(eq(integrationConnections.id, id))
93
- },
94
- },
95
83
  ]
96
84
 
97
85
  /** The columns this pass covers. Exported for the test that checks none is missing. */
@@ -27,5 +27,4 @@ export * from '../modules/forms/schema.ts'
27
27
  export * from '../modules/import-export/schema.ts'
28
28
  export * from '../modules/agent-tasks/schema.ts'
29
29
  export * from '../modules/webhooks/schema.ts'
30
- export * from '../modules/integrations/schema.ts'
31
30
  export * from '../modules/rate-limit/schema.ts'
@@ -1,31 +0,0 @@
1
- import { index, jsonb, pgTable, text } from 'drizzle-orm/pg-core'
2
-
3
- import { createdAt, moment, primaryId, updatedAt } from '../../lib/columns.ts'
4
- import { users } from '../auth/schema.ts'
5
- import { workspaces } from '../workspace/schema.ts'
6
-
7
- /**
8
- * Core owns the connection lifecycle; the provider itself ships as a module and
9
- * declares `provider_id`. Module-owned provider tables reference this row.
10
- *
11
- * `user_id` is set for personal connections such as a Gmail mailbox, null for
12
- * workspace-wide ones.
13
- */
14
- export const integrationConnections = pgTable(
15
- 'integration_connections',
16
- {
17
- id: primaryId(),
18
- workspaceId: text('workspace_id')
19
- .notNull()
20
- .references(() => workspaces.id, { onDelete: 'cascade' }),
21
- providerId: text('provider_id').notNull(),
22
- userId: text('user_id').references(() => users.id, { onDelete: 'cascade' }),
23
- status: text('status').notNull(),
24
- config: jsonb('config').notNull().default({}),
25
- secretsEncrypted: text('secrets_encrypted'),
26
- lastSyncAt: moment('last_sync_at'),
27
- createdAt: createdAt(),
28
- updatedAt: updatedAt(),
29
- },
30
- (table) => [index('integration_connections_workspace_idx').on(table.workspaceId)],
31
- )