@mastra/factory 0.21.1-alpha.2 → 0.21.1-alpha.3

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.
@@ -1 +1 @@
1
- {"version":3,"file":"secret-encryption.d.ts","sourceRoot":"","sources":["../src/secret-encryption.ts"],"names":[],"mappings":"AAaA,MAAM,WAAW,sBAAsB,CAAC,CAAC;IACvC,KAAK,EAAE,CAAC,CAAC;IACT,iBAAiB,EAAE,OAAO,CAAC;CAC5B;AAED,kFAAkF;AAClF,MAAM,WAAW,uBAAuB;IACtC,OAAO,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IACtC,OAAO,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,sBAAsB,CAAC,CAAC,CAAC,CAAC,CAAC;CAChE;AAED,MAAM,WAAW,0BAA0B;IACzC,EAAE,EAAE,MAAM,CAAC;IACX,GAAG,EAAE,UAAU,CAAC;CACjB;AAED,MAAM,WAAW,6BAA6B;IAC5C,OAAO,EAAE,0BAA0B,CAAC;IACpC,QAAQ,CAAC,EAAE,0BAA0B,EAAE,CAAC;CACzC;AAgCD;;;GAGG;AACH,wBAAgB,6BAA6B,CAAC,MAAM,EAAE,6BAA6B,GAAG,uBAAuB,CA+C5G;AAED,+EAA+E;AAC/E,wBAAgB,sCAAsC,IAAI,uBAAuB,CAiBhF"}
1
+ {"version":3,"file":"secret-encryption.d.ts","sourceRoot":"","sources":["../src/secret-encryption.ts"],"names":[],"mappings":"AAaA,MAAM,WAAW,sBAAsB,CAAC,CAAC;IACvC,KAAK,EAAE,CAAC,CAAC;IACT,iBAAiB,EAAE,OAAO,CAAC;CAC5B;AAED,kFAAkF;AAClF,MAAM,WAAW,uBAAuB;IACtC,OAAO,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IACtC,OAAO,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,sBAAsB,CAAC,CAAC,CAAC,CAAC,CAAC;CAChE;AAED,MAAM,WAAW,0BAA0B;IACzC,EAAE,EAAE,MAAM,CAAC;IACX,GAAG,EAAE,UAAU,CAAC;CACjB;AAED,MAAM,WAAW,6BAA6B;IAC5C,OAAO,EAAE,0BAA0B,CAAC;IACpC,QAAQ,CAAC,EAAE,0BAA0B,EAAE,CAAC;CACzC;AAgCD;;;GAGG;AACH,wBAAgB,6BAA6B,CAAC,MAAM,EAAE,6BAA6B,GAAG,uBAAuB,CAyD5G;AAED,+EAA+E;AAC/E,wBAAgB,sCAAsC,IAAI,uBAAuB,CAiBhF"}
@@ -44,10 +44,21 @@ function createFactorySecretEncryption(config) {
44
44
  return `${ENVELOPE_PREFIX}${Buffer.from(JSON.stringify(envelope), "utf8").toString("base64url")}`;
45
45
  },
46
46
  async decrypt(value) {
47
- if (typeof value !== "string" || !value.startsWith(ENVELOPE_PREFIX)) return {
47
+ if (typeof value !== "string") return {
48
48
  value: structuredClone(value),
49
49
  needsReencryption: true
50
50
  };
51
+ if (!value.startsWith(ENVELOPE_PREFIX)) try {
52
+ return {
53
+ value: JSON.parse(value),
54
+ needsReencryption: true
55
+ };
56
+ } catch {
57
+ return {
58
+ value,
59
+ needsReencryption: true
60
+ };
61
+ }
51
62
  const envelope = parseEnvelope(value);
52
63
  const key = keys.get(envelope.keyId);
53
64
  if (!key) throw new Error(`[FactorySecretEncryption] Unknown key id "${envelope.keyId}".`);
@@ -1 +1 @@
1
- {"version":3,"file":"secret-encryption.js","names":[],"sources":["../src/secret-encryption.ts"],"sourcesContent":["import { createCipheriv, createDecipheriv } from 'node:crypto';\n\nconst ENVELOPE_PREFIX = 'mastra:factory-secret:v1:';\nconst ALGORITHM = 'aes-256-gcm';\nconst IV_BYTES = 12;\n\ninterface SecretEnvelopeV1 {\n keyId: string;\n iv: string;\n ciphertext: string;\n tag: string;\n}\n\nexport interface DecryptedFactorySecret<T> {\n value: T;\n needsReencryption: boolean;\n}\n\n/** Encrypts opaque JSON values before they cross the Factory storage boundary. */\nexport interface FactorySecretEncryption {\n encrypt<T>(value: T): Promise<string>;\n decrypt<T>(value: unknown): Promise<DecryptedFactorySecret<T>>;\n}\n\nexport interface FactorySecretEncryptionKey {\n id: string;\n key: Uint8Array;\n}\n\nexport interface FactorySecretEncryptionConfig {\n primary: FactorySecretEncryptionKey;\n previous?: FactorySecretEncryptionKey[];\n}\n\nfunction validateKey({ id, key }: FactorySecretEncryptionKey): Buffer {\n if (!id) throw new Error('[FactorySecretEncryption] Key id is required.');\n const buffer = Buffer.from(key);\n if (buffer.byteLength !== 32) {\n throw new Error(`[FactorySecretEncryption] Key \"${id}\" must be exactly 32 bytes.`);\n }\n return buffer;\n}\n\nfunction parseEnvelope(value: string): SecretEnvelopeV1 {\n let parsed: unknown;\n try {\n parsed = JSON.parse(Buffer.from(value.slice(ENVELOPE_PREFIX.length), 'base64url').toString('utf8'));\n } catch {\n throw new Error('[FactorySecretEncryption] Invalid encrypted value.');\n }\n\n if (\n !parsed ||\n typeof parsed !== 'object' ||\n typeof (parsed as SecretEnvelopeV1).keyId !== 'string' ||\n typeof (parsed as SecretEnvelopeV1).iv !== 'string' ||\n typeof (parsed as SecretEnvelopeV1).ciphertext !== 'string' ||\n typeof (parsed as SecretEnvelopeV1).tag !== 'string'\n ) {\n throw new Error('[FactorySecretEncryption] Invalid encrypted value.');\n }\n return parsed as SecretEnvelopeV1;\n}\n\n/**\n * Creates a versioned AES-256-GCM encryptor. The primary key is used for new\n * writes; previous keys remain decrypt-only until stored values are rotated.\n */\nexport function createFactorySecretEncryption(config: FactorySecretEncryptionConfig): FactorySecretEncryption {\n const primaryKey = validateKey(config.primary);\n const keys = new Map<string, Buffer>([[config.primary.id, primaryKey]]);\n for (const previous of config.previous ?? []) {\n if (keys.has(previous.id)) throw new Error(`[FactorySecretEncryption] Duplicate key id \"${previous.id}\".`);\n keys.set(previous.id, validateKey(previous));\n }\n\n return {\n async encrypt<T>(value: T): Promise<string> {\n const iv = Buffer.from(globalThis.crypto.getRandomValues(new Uint8Array(IV_BYTES)));\n const cipher = createCipheriv(ALGORITHM, primaryKey, iv);\n const ciphertext = Buffer.concat([cipher.update(JSON.stringify(value), 'utf8'), cipher.final()]);\n const envelope: SecretEnvelopeV1 = {\n keyId: config.primary.id,\n iv: iv.toString('base64url'),\n ciphertext: ciphertext.toString('base64url'),\n tag: cipher.getAuthTag().toString('base64url'),\n };\n return `${ENVELOPE_PREFIX}${Buffer.from(JSON.stringify(envelope), 'utf8').toString('base64url')}`;\n },\n\n async decrypt<T>(value: unknown): Promise<DecryptedFactorySecret<T>> {\n if (typeof value !== 'string' || !value.startsWith(ENVELOPE_PREFIX)) {\n return { value: structuredClone(value) as T, needsReencryption: true };\n }\n\n const envelope = parseEnvelope(value);\n const key = keys.get(envelope.keyId);\n if (!key) throw new Error(`[FactorySecretEncryption] Unknown key id \"${envelope.keyId}\".`);\n\n try {\n const decipher = createDecipheriv(ALGORITHM, key, Buffer.from(envelope.iv, 'base64url'));\n decipher.setAuthTag(Buffer.from(envelope.tag, 'base64url'));\n const plaintext = Buffer.concat([\n decipher.update(Buffer.from(envelope.ciphertext, 'base64url')),\n decipher.final(),\n ]).toString('utf8');\n return {\n value: JSON.parse(plaintext) as T,\n needsReencryption: envelope.keyId !== config.primary.id,\n };\n } catch {\n throw new Error('[FactorySecretEncryption] Unable to decrypt encrypted value.');\n }\n },\n };\n}\n\n/** Explicit plaintext compatibility for local, no-auth Factory development. */\nexport function createPlaintextFactorySecretEncryption(): FactorySecretEncryption {\n return {\n async encrypt<T>(value: T): Promise<string> {\n return JSON.stringify(value);\n },\n async decrypt<T>(value: unknown): Promise<DecryptedFactorySecret<T>> {\n if (typeof value !== 'string') return { value: structuredClone(value) as T, needsReencryption: false };\n try {\n return { value: JSON.parse(value) as T, needsReencryption: false };\n } catch {\n // Pre-encryption rows stored raw secret strings (e.g. a bare\n // `custom_providers.api_key`), not JSON. Treat the raw string as the\n // value and flag it so migration rewrites it in the current format.\n return { value: value as T, needsReencryption: true };\n }\n },\n };\n}\n"],"mappings":";;AAEA,MAAM,kBAAkB;AACxB,MAAM,YAAY;AAClB,MAAM,WAAW;AA8BjB,SAAS,YAAY,EAAE,IAAI,OAA2C;CACpE,IAAI,CAAC,IAAI,MAAM,IAAI,MAAM,+CAA+C;CACxE,MAAM,SAAS,OAAO,KAAK,GAAG;CAC9B,IAAI,OAAO,eAAe,IACxB,MAAM,IAAI,MAAM,kCAAkC,GAAG,4BAA4B;CAEnF,OAAO;AACT;AAEA,SAAS,cAAc,OAAiC;CACtD,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,OAAO,KAAK,MAAM,MAAM,EAAsB,GAAG,WAAW,CAAC,CAAC,SAAS,MAAM,CAAC;CACpG,QAAQ;EACN,MAAM,IAAI,MAAM,oDAAoD;CACtE;CAEA,IACE,CAAC,UACD,OAAO,WAAW,YAClB,OAAQ,OAA4B,UAAU,YAC9C,OAAQ,OAA4B,OAAO,YAC3C,OAAQ,OAA4B,eAAe,YACnD,OAAQ,OAA4B,QAAQ,UAE5C,MAAM,IAAI,MAAM,oDAAoD;CAEtE,OAAO;AACT;;;;;AAMA,SAAgB,8BAA8B,QAAgE;CAC5G,MAAM,aAAa,YAAY,OAAO,OAAO;CAC7C,MAAM,uBAAO,IAAI,IAAoB,CAAC,CAAC,OAAO,QAAQ,IAAI,UAAU,CAAC,CAAC;CACtE,KAAK,MAAM,YAAY,OAAO,YAAY,CAAC,GAAG;EAC5C,IAAI,KAAK,IAAI,SAAS,EAAE,GAAG,MAAM,IAAI,MAAM,+CAA+C,SAAS,GAAG,GAAG;EACzG,KAAK,IAAI,SAAS,IAAI,YAAY,QAAQ,CAAC;CAC7C;CAEA,OAAO;EACL,MAAM,QAAW,OAA2B;GAC1C,MAAM,KAAK,OAAO,KAAK,WAAW,OAAO,gBAAgB,IAAI,WAAW,QAAQ,CAAC,CAAC;G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AM,QAAW,OAAoD;GACnE,IAAI,OAAO,UAAU,UAAU,OAAO;IAAE,OAAO,gBAAgB,KAAK;IAAQ,mBAAmB;GAAM;GACrG,IAAI;IACF,OAAO;KAAE,OAAO,KAAK,MAAM,KAAK;KAAQ,mBAAmB;IAAM;GACnE,QAAQ;IAIN,OAAO;KAAS;KAAY,mBAAmB;IAAK;GACtD;EACF;CACF;AACF"}
1
+ {"version":3,"file":"secret-encryption.js","names":[],"sources":["../src/secret-encryption.ts"],"sourcesContent":["import { createCipheriv, createDecipheriv } from 'node:crypto';\n\nconst ENVELOPE_PREFIX = 'mastra:factory-secret:v1:';\nconst ALGORITHM = 'aes-256-gcm';\nconst IV_BYTES = 12;\n\ninterface SecretEnvelopeV1 {\n keyId: string;\n iv: string;\n ciphertext: string;\n tag: string;\n}\n\nexport interface DecryptedFactorySecret<T> {\n value: T;\n needsReencryption: boolean;\n}\n\n/** Encrypts opaque JSON values before they cross the Factory storage boundary. */\nexport interface FactorySecretEncryption {\n encrypt<T>(value: T): Promise<string>;\n decrypt<T>(value: unknown): Promise<DecryptedFactorySecret<T>>;\n}\n\nexport interface FactorySecretEncryptionKey {\n id: string;\n key: Uint8Array;\n}\n\nexport interface FactorySecretEncryptionConfig {\n primary: FactorySecretEncryptionKey;\n previous?: FactorySecretEncryptionKey[];\n}\n\nfunction validateKey({ id, key }: FactorySecretEncryptionKey): Buffer {\n if (!id) throw new Error('[FactorySecretEncryption] Key id is required.');\n const buffer = Buffer.from(key);\n if (buffer.byteLength !== 32) {\n throw new Error(`[FactorySecretEncryption] Key \"${id}\" must be exactly 32 bytes.`);\n }\n return buffer;\n}\n\nfunction parseEnvelope(value: string): SecretEnvelopeV1 {\n let parsed: unknown;\n try {\n parsed = JSON.parse(Buffer.from(value.slice(ENVELOPE_PREFIX.length), 'base64url').toString('utf8'));\n } catch {\n throw new Error('[FactorySecretEncryption] Invalid encrypted value.');\n }\n\n if (\n !parsed ||\n typeof parsed !== 'object' ||\n typeof (parsed as SecretEnvelopeV1).keyId !== 'string' ||\n typeof (parsed as SecretEnvelopeV1).iv !== 'string' ||\n typeof (parsed as SecretEnvelopeV1).ciphertext !== 'string' ||\n typeof (parsed as SecretEnvelopeV1).tag !== 'string'\n ) {\n throw new Error('[FactorySecretEncryption] Invalid encrypted value.');\n }\n return parsed as SecretEnvelopeV1;\n}\n\n/**\n * Creates a versioned AES-256-GCM encryptor. The primary key is used for new\n * writes; previous keys remain decrypt-only until stored values are rotated.\n */\nexport function createFactorySecretEncryption(config: FactorySecretEncryptionConfig): FactorySecretEncryption {\n const primaryKey = validateKey(config.primary);\n const keys = new Map<string, Buffer>([[config.primary.id, primaryKey]]);\n for (const previous of config.previous ?? []) {\n if (keys.has(previous.id)) throw new Error(`[FactorySecretEncryption] Duplicate key id \"${previous.id}\".`);\n keys.set(previous.id, validateKey(previous));\n }\n\n return {\n async encrypt<T>(value: T): Promise<string> {\n const iv = Buffer.from(globalThis.crypto.getRandomValues(new Uint8Array(IV_BYTES)));\n const cipher = createCipheriv(ALGORITHM, primaryKey, iv);\n const ciphertext = Buffer.concat([cipher.update(JSON.stringify(value), 'utf8'), cipher.final()]);\n const envelope: SecretEnvelopeV1 = {\n keyId: config.primary.id,\n iv: iv.toString('base64url'),\n ciphertext: ciphertext.toString('base64url'),\n tag: cipher.getAuthTag().toString('base64url'),\n };\n return `${ENVELOPE_PREFIX}${Buffer.from(JSON.stringify(envelope), 'utf8').toString('base64url')}`;\n },\n\n async decrypt<T>(value: unknown): Promise<DecryptedFactorySecret<T>> {\n if (typeof value !== 'string') {\n return { value: structuredClone(value) as T, needsReencryption: true };\n }\n if (!value.startsWith(ENVELOPE_PREFIX)) {\n // JSON text written by the plaintext encryptor, or a raw pre-encryption\n // secret string. Decode it the same way the plaintext encryptor does so\n // migration encrypts the original value, not its JSON text.\n try {\n return { value: JSON.parse(value) as T, needsReencryption: true };\n } catch {\n return { value: value as T, needsReencryption: true };\n }\n }\n\n const envelope = parseEnvelope(value);\n const key = keys.get(envelope.keyId);\n if (!key) throw new Error(`[FactorySecretEncryption] Unknown key id \"${envelope.keyId}\".`);\n\n try {\n const decipher = createDecipheriv(ALGORITHM, key, Buffer.from(envelope.iv, 'base64url'));\n decipher.setAuthTag(Buffer.from(envelope.tag, 'base64url'));\n const plaintext = Buffer.concat([\n decipher.update(Buffer.from(envelope.ciphertext, 'base64url')),\n decipher.final(),\n ]).toString('utf8');\n return {\n value: JSON.parse(plaintext) as T,\n needsReencryption: envelope.keyId !== config.primary.id,\n };\n } catch {\n throw new Error('[FactorySecretEncryption] Unable to decrypt encrypted value.');\n }\n },\n };\n}\n\n/** Explicit plaintext compatibility for local, no-auth Factory development. */\nexport function createPlaintextFactorySecretEncryption(): FactorySecretEncryption {\n return {\n async encrypt<T>(value: T): Promise<string> {\n return JSON.stringify(value);\n },\n async decrypt<T>(value: unknown): Promise<DecryptedFactorySecret<T>> {\n if (typeof value !== 'string') return { value: structuredClone(value) as T, needsReencryption: false };\n try {\n return { value: JSON.parse(value) as T, needsReencryption: false };\n } catch {\n // Pre-encryption rows stored raw secret strings (e.g. a bare\n // `custom_providers.api_key`), not JSON. Treat the raw string as the\n // value and flag it so migration rewrites it in the current format.\n return { value: value as T, needsReencryption: true };\n }\n },\n };\n}\n"],"mappings":";;AAEA,MAAM,kBAAkB;AACxB,MAAM,YAAY;AAClB,MAAM,WAAW;AA8BjB,SAAS,YAAY,EAAE,IAAI,OAA2C;CACpE,IAAI,CAAC,IAAI,MAAM,IAAI,MAAM,+CAA+C;CACxE,MAAM,SAAS,OAAO,KAAK,GAAG;CAC9B,IAAI,OAAO,eAAe,IACxB,MAAM,IAAI,MAAM,kCAAkC,GAAG,4BAA4B;CAEnF,OAAO;AACT;AAEA,SAAS,cAAc,OAAiC;CACtD,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,OAAO,KAAK,MAAM,MAAM,EAAsB,GAAG,WAAW,CAAC,CAAC,SAAS,MAAM,CAAC;CACpG,QAAQ;EACN,MAAM,IA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,CAAC,IAAI,CAAC;IAMrB,mBAAmB,IAAI,OAAO,CAAC,IAAI,CAAC;IAgD1C;;;;;;;OAOG;IACG,MAAM,CAAC,EACX,KAAK,EACL,MAAM,EACN,KAAK,EACL,kBAAkB,GACnB,EAAE;QACD,KAAK,EAAE,MAAM,CAAC;QACd,MAAM,EAAE,MAAM,CAAC;QACf,KAAK,EAAE,yBAAyB,CAAC;QACjC,kBAAkB,CAAC,EAAE,MAAM,CAAC;KAC7B,GAAG,OAAO,CAAC,oBAAoB,CAAC;IAqG3B,IAAI,CAAC,EAAE,KAAK,EAAE,EAAE;QAAE,KAAK,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,oBAAoB,EAAE,CAAC;IASnE,MAAM,CAAC,EAAE,KAAK,EAAE,UAAU,EAAE,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,OAAO,CAAC;CAG7F"}
@@ -41,7 +41,7 @@ var CustomProvidersStorage = class extends FactoryStorageDomain {
41
41
  return this.ops;
42
42
  }
43
43
  async #toRecord(row) {
44
- const apiKey = row.api_key === null ? null : (await this.encryption.decrypt(row.api_key)).value;
44
+ const apiKey = row.api_key === null ? null : (await this.#decryptApiKey(row.api_key)).value;
45
45
  return {
46
46
  id: row.id,
47
47
  orgId: row.org_id,
@@ -55,13 +55,24 @@ var CustomProvidersStorage = class extends FactoryStorageDomain {
55
55
  updatedAt: row.updated_at
56
56
  };
57
57
  }
58
+ /**
59
+ * API keys are always strings. A legacy raw key that happens to be valid JSON
60
+ * (e.g. `12345`) decodes to a non-string, so keep the stored text instead.
61
+ */
62
+ async #decryptApiKey(stored) {
63
+ const decrypted = await this.encryption.decrypt(stored);
64
+ return {
65
+ value: typeof decrypted.value === "string" ? decrypted.value : stored,
66
+ needsReencryption: decrypted.needsReencryption
67
+ };
68
+ }
58
69
  async #encryptApiKey(apiKey) {
59
70
  return apiKey === void 0 ? null : this.encryption.encrypt(apiKey);
60
71
  }
61
72
  async #migrateApiKey(id) {
62
73
  await this.#db.updateAtomic("custom_providers", { id }, async (row) => {
63
74
  if (row.api_key === null) return null;
64
- const decrypted = await this.encryption.decrypt(row.api_key);
75
+ const decrypted = await this.#decryptApiKey(row.api_key);
65
76
  return decrypted.needsReencryption ? { api_key: await this.encryption.encrypt(decrypted.value) } : null;
66
77
  });
67
78
  }
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","names":["#migrateApiKey","#db","#toRecord","#encryptApiKey","#write"],"sources":["../../../../src/storage/domains/custom-providers/base.ts"],"sourcesContent":["import { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\nimport type { CollectionSchema, FactoryStorageOps } from '@mastra/core/storage';\nimport { createPlaintextFactorySecretEncryption } from '../../../secret-encryption.js';\nimport type { FactorySecretEncryption } from '../../../secret-encryption.js';\n\n/**\n * A user-defined OpenAI-compatible provider. The DB-backed counterpart of the\n * local `settings.json` `customProviders` entries: org-scoped rows keyed by the\n * derived provider id (name slug), API key stored alongside so a deployed\n * server never reads the shared settings file.\n */\nexport interface CustomProviderRecord {\n id: string;\n orgId: string;\n createdBy: string;\n /** Stable slug derived from the name (`getCustomProviderId`). */\n providerId: string;\n name: string;\n url: string;\n apiKey: string | null;\n models: string[];\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface UpsertCustomProviderInput {\n providerId: string;\n name: string;\n url: string;\n apiKey?: string;\n models: string[];\n}\n\nexport const CUSTOM_PROVIDERS_SCHEMA: CollectionSchema = {\n name: 'custom_providers',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n created_by: { type: 'text' },\n provider_id: { type: 'text' },\n name: { type: 'text' },\n url: { type: 'text' },\n api_key: { type: 'text', nullable: true },\n models: { type: 'json' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [{ name: 'custom_providers_org_provider_key', columns: ['org_id', 'provider_id'] }],\n};\n\ninterface CustomProviderDbRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n created_by: string;\n provider_id: string;\n name: string;\n url: string;\n api_key: string | null;\n models: string[];\n created_at: Date;\n updated_at: Date;\n}\n\nexport class CustomProvidersStorage extends FactoryStorageDomain {\n constructor(private readonly encryption: FactorySecretEncryption = createPlaintextFactorySecretEncryption()) {\n super('custom-providers');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([CUSTOM_PROVIDERS_SCHEMA]);\n const rows = await this.ops.findMany<CustomProviderDbRow>('custom_providers', {});\n await Promise.all(rows.filter(row => row.api_key !== null).map(row => this.#migrateApiKey(row.id)));\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('custom_providers', {});\n }\n\n get #db(): FactoryStorageOps {\n return this.ops;\n }\n\n async #toRecord(row: CustomProviderDbRow): Promise<CustomProviderRecord> {\n const apiKey = row.api_key === null ? null : (await this.encryption.decrypt<string>(row.api_key)).value;\n return {\n id: row.id,\n orgId: row.org_id,\n createdBy: row.created_by,\n providerId: row.provider_id,\n name: row.name,\n url: row.url,\n apiKey,\n models: Array.isArray(row.models) ? row.models : [],\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n }\n\n async #encryptApiKey(apiKey: string | undefined): Promise<string | null> {\n return apiKey === undefined ? null : this.encryption.encrypt(apiKey);\n }\n\n async #migrateApiKey(id: string): Promise<void> {\n await this.#db.updateAtomic<CustomProviderDbRow>('custom_providers', { id }, async row => {\n if (row.api_key === null) return null;\n const decrypted = await this.encryption.decrypt<string>(row.api_key);\n return decrypted.needsReencryption ? { api_key: await this.encryption.encrypt(decrypted.value) } : null;\n });\n }\n\n /**\n * Create or wholesale-replace a provider by `(orgId, providerId)` — mirrors\n * the settings.json upsert semantics (no key retention: an absent `apiKey`\n * clears the stored key). `previousProviderId` renames the provider: the\n * common path is a single atomic in-place update of the old row; renaming\n * onto an id that already exists overwrites the target first and removes the\n * old row last, so no interleaving or failure can lose the provider.\n */\n async upsert({\n orgId,\n userId,\n input,\n previousProviderId,\n }: {\n orgId: string;\n userId: string;\n input: UpsertCustomProviderInput;\n previousProviderId?: string;\n }): Promise<CustomProviderRecord> {\n const now = new Date();\n const encryptedApiKey = await this.#encryptApiKey(input.apiKey);\n const renameFrom = previousProviderId && previousProviderId !== input.providerId ? previousProviderId : undefined;\n\n if (renameFrom) {\n const target = await this.#db.findOne<CustomProviderDbRow>('custom_providers', {\n org_id: orgId,\n provider_id: input.providerId,\n });\n if (!target) {\n // In-place rename: one atomic write with no delete/insert gap, so a\n // failure can never drop the provider (and `created_at`/`created_by`\n // are preserved). If a concurrent create grabs the new id between the\n // lookup and this update, the unique index rejects the update and the\n // old row stays intact — the request fails cleanly and a retry\n // converges on the rename-onto-existing path below.\n const renamed = await this.#db.updateAtomic<CustomProviderDbRow>(\n 'custom_providers',\n { org_id: orgId, provider_id: renameFrom },\n () => ({\n provider_id: input.providerId,\n name: input.name,\n url: input.url,\n api_key: encryptedApiKey,\n models: input.models,\n updated_at: now,\n }),\n );\n if (renamed) return this.#toRecord(renamed);\n // Old row already gone — fall through to a plain create of the new id.\n }\n // Rename onto an existing id: overwrite the target below, then delete\n // the old row last — a failure in the gap leaves a redundant duplicate\n // (recoverable by re-submitting or deleting) instead of losing data.\n }\n\n const record = await this.#write({ orgId, userId, input, encryptedApiKey, now });\n if (renameFrom) {\n await this.#db.deleteMany('custom_providers', { org_id: orgId, provider_id: renameFrom });\n }\n return record;\n }\n\n /**\n * Update-first, then insert-and-catch-unique-violation (see `queue_health`):\n * concurrent creates of the same provider both succeed (last write wins on\n * the single row) instead of one failing on the unique index, and a row\n * deleted mid-flight is recreated rather than reported as a stale success.\n */\n async #write({\n orgId,\n userId,\n input,\n encryptedApiKey,\n now,\n }: {\n orgId: string;\n userId: string;\n input: UpsertCustomProviderInput;\n encryptedApiKey: string | null;\n now: Date;\n }): Promise<CustomProviderRecord> {\n const updateExisting = () =>\n this.#db.updateAtomic<CustomProviderDbRow>(\n 'custom_providers',\n { org_id: orgId, provider_id: input.providerId },\n () => ({\n name: input.name,\n url: input.url,\n api_key: encryptedApiKey,\n models: input.models,\n updated_at: now,\n }),\n );\n\n const updated = await updateExisting();\n if (updated) return this.#toRecord(updated);\n\n try {\n const row = await this.#db.insertOne<CustomProviderDbRow>('custom_providers', {\n org_id: orgId,\n created_by: userId,\n provider_id: input.providerId,\n name: input.name,\n url: input.url,\n api_key: encryptedApiKey,\n models: input.models,\n created_at: now,\n updated_at: now,\n });\n return this.#toRecord(row);\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n // Lost the insert race — apply this write to the winning row.\n const row = await updateExisting();\n if (!row) throw error;\n return this.#toRecord(row);\n }\n }\n\n async list({ orgId }: { orgId: string }): Promise<CustomProviderRecord[]> {\n const rows = await this.#db.findMany<CustomProviderDbRow>(\n 'custom_providers',\n { org_id: orgId },\n { orderBy: [['name', 'asc']] },\n );\n return Promise.all(rows.map(row => this.#toRecord(row)));\n }\n\n async delete({ orgId, providerId }: { orgId: string; providerId: string }): Promise<boolean> {\n return (await this.#db.deleteMany('custom_providers', { org_id: orgId, provider_id: providerId })) > 0;\n }\n}\n"],"mappings":";;;AAiCA,MAAa,0BAA4C;CACvD,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,QAAQ,EAAE,MAAM,OAAO;EACvB,YAAY,EAAE,MAAM,OAAO;EAC3B,aAAa,EAAE,MAAM,OAAO;EAC5B,MAAM,EAAE,MAAM,OAAO;EACrB,KAAK,EAAE,MAAM,OAAO;EACpB,SAAS;GAAE,MAAM;GAAQ,UAAU;EAAK;EACxC,QAAQ,EAAE,MAAM,OAAO;EACvB,YAAY,EAAE,MAAM,YAAY;EAChC,YAAY,EAAE,MAAM,YAAY;CAClC;CACA,eAAe,CAAC;EAAE,MAAM;EAAqC,SAAS,CAAC,UAAU,aAAa;CAAE,CAAC;AACnG;AAeA,IAAa,yBAAb,cAA4C,qBAAqB;CAClC;CAA7B,YAAY,aAAuD,uCAAuC,GAAG;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;GACd,IAAI,EAAE,iBAAiB,uBAAuB,MAAM;GAEpD,MAAM,MAAM,MAAM,eAAe;GACjC,IAAI,CAAC,KAAK,MAAM;GAChB,OAAO,KAAKA,UAAU,GAAG;EAC3B;CACF;CAEA,MAAM,KAAK,EAAE,SAA6D;EACxE,MAAM,OAAO,MAAM,KAAKD,IAAI,SAC1B,oBACA,EAAE,QAAQ,MAAM,GAChB,EAAE,SAAS,CAAC,CAAC,QAAQ,KAAK,CAAC,EAAE,CAC/B;EACA,OAAO,QAAQ,IAAI,KAAK,KAAI,QAAO,KAAKC,UAAU,GAAG,CAAC,CAAC;CACzD;CAEA,MAAM,OAAO,EAAE,OAAO,cAAuE;EAC3F,OAAQ,MAAM,KAAKD,IAAI,WAAW,oBAAoB;GAAE,QAAQ;GAAO,aAAa;EAAW,CAAC,IAAK;CACvG;AACF"}
1
+ {"version":3,"file":"base.js","names":["#migrateApiKey","#db","#toRecord","#decryptApiKey","#encryptApiKey","#write"],"sources":["../../../../src/storage/domains/custom-providers/base.ts"],"sourcesContent":["import { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\nimport type { CollectionSchema, FactoryStorageOps } from '@mastra/core/storage';\nimport { createPlaintextFactorySecretEncryption } from '../../../secret-encryption.js';\nimport type { FactorySecretEncryption } from '../../../secret-encryption.js';\n\n/**\n * A user-defined OpenAI-compatible provider. The DB-backed counterpart of the\n * local `settings.json` `customProviders` entries: org-scoped rows keyed by the\n * derived provider id (name slug), API key stored alongside so a deployed\n * server never reads the shared settings file.\n */\nexport interface CustomProviderRecord {\n id: string;\n orgId: string;\n createdBy: string;\n /** Stable slug derived from the name (`getCustomProviderId`). */\n providerId: string;\n name: string;\n url: string;\n apiKey: string | null;\n models: string[];\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface UpsertCustomProviderInput {\n providerId: string;\n name: string;\n url: string;\n apiKey?: string;\n models: string[];\n}\n\nexport const CUSTOM_PROVIDERS_SCHEMA: CollectionSchema = {\n name: 'custom_providers',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n created_by: { type: 'text' },\n provider_id: { type: 'text' },\n name: { type: 'text' },\n url: { type: 'text' },\n api_key: { type: 'text', nullable: true },\n models: { type: 'json' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [{ name: 'custom_providers_org_provider_key', columns: ['org_id', 'provider_id'] }],\n};\n\ninterface CustomProviderDbRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n created_by: string;\n provider_id: string;\n name: string;\n url: string;\n api_key: string | null;\n models: string[];\n created_at: Date;\n updated_at: Date;\n}\n\nexport class CustomProvidersStorage extends FactoryStorageDomain {\n constructor(private readonly encryption: FactorySecretEncryption = createPlaintextFactorySecretEncryption()) {\n super('custom-providers');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([CUSTOM_PROVIDERS_SCHEMA]);\n const rows = await this.ops.findMany<CustomProviderDbRow>('custom_providers', {});\n await Promise.all(rows.filter(row => row.api_key !== null).map(row => this.#migrateApiKey(row.id)));\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('custom_providers', {});\n }\n\n get #db(): FactoryStorageOps {\n return this.ops;\n }\n\n async #toRecord(row: CustomProviderDbRow): Promise<CustomProviderRecord> {\n const apiKey = row.api_key === null ? null : (await this.#decryptApiKey(row.api_key)).value;\n return {\n id: row.id,\n orgId: row.org_id,\n createdBy: row.created_by,\n providerId: row.provider_id,\n name: row.name,\n url: row.url,\n apiKey,\n models: Array.isArray(row.models) ? row.models : [],\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n }\n\n /**\n * API keys are always strings. A legacy raw key that happens to be valid JSON\n * (e.g. `12345`) decodes to a non-string, so keep the stored text instead.\n */\n async #decryptApiKey(stored: string): Promise<{ value: string; needsReencryption: boolean }> {\n const decrypted = await this.encryption.decrypt<unknown>(stored);\n return {\n value: typeof decrypted.value === 'string' ? decrypted.value : stored,\n needsReencryption: decrypted.needsReencryption,\n };\n }\n\n async #encryptApiKey(apiKey: string | undefined): Promise<string | null> {\n return apiKey === undefined ? null : this.encryption.encrypt(apiKey);\n }\n\n async #migrateApiKey(id: string): Promise<void> {\n await this.#db.updateAtomic<CustomProviderDbRow>('custom_providers', { id }, async row => {\n if (row.api_key === null) return null;\n const decrypted = await this.#decryptApiKey(row.api_key);\n return decrypted.needsReencryption ? { api_key: await this.encryption.encrypt(decrypted.value) } : null;\n });\n }\n\n /**\n * Create or wholesale-replace a provider by `(orgId, providerId)` — mirrors\n * the settings.json upsert semantics (no key retention: an absent `apiKey`\n * clears the stored key). `previousProviderId` renames the provider: the\n * common path is a single atomic in-place update of the old row; renaming\n * onto an id that already exists overwrites the target first and removes the\n * old row last, so no interleaving or failure can lose the provider.\n */\n async upsert({\n orgId,\n userId,\n input,\n previousProviderId,\n }: {\n orgId: string;\n userId: string;\n input: UpsertCustomProviderInput;\n previousProviderId?: string;\n }): Promise<CustomProviderRecord> {\n const now = new Date();\n const encryptedApiKey = await this.#encryptApiKey(input.apiKey);\n const renameFrom = previousProviderId && previousProviderId !== input.providerId ? previousProviderId : undefined;\n\n if (renameFrom) {\n const target = await this.#db.findOne<CustomProviderDbRow>('custom_providers', {\n org_id: orgId,\n provider_id: input.providerId,\n });\n if (!target) {\n // In-place rename: one atomic write with no delete/insert gap, so a\n // failure can never drop the provider (and `created_at`/`created_by`\n // are preserved). If a concurrent create grabs the new id between the\n // lookup and this update, the unique index rejects the update and the\n // old row stays intact — the request fails cleanly and a retry\n // converges on the rename-onto-existing path below.\n const renamed = await this.#db.updateAtomic<CustomProviderDbRow>(\n 'custom_providers',\n { org_id: orgId, provider_id: renameFrom },\n () => ({\n provider_id: input.providerId,\n name: input.name,\n url: input.url,\n api_key: encryptedApiKey,\n models: input.models,\n updated_at: now,\n }),\n );\n if (renamed) return this.#toRecord(renamed);\n // Old row already gone — fall through to a plain create of the new id.\n }\n // Rename onto an existing id: overwrite the target below, then delete\n // the old row last — a failure in the gap leaves a redundant duplicate\n // (recoverable by re-submitting or deleting) instead of losing data.\n }\n\n const record = await this.#write({ orgId, userId, input, encryptedApiKey, now });\n if (renameFrom) {\n await this.#db.deleteMany('custom_providers', { org_id: orgId, provider_id: renameFrom });\n }\n return record;\n }\n\n /**\n * Update-first, then insert-and-catch-unique-violation (see `queue_health`):\n * concurrent creates of the same provider both succeed (last write wins on\n * the single row) instead of one failing on the unique index, and a row\n * deleted mid-flight is recreated rather than reported as a stale success.\n */\n async #write({\n orgId,\n userId,\n input,\n encryptedApiKey,\n now,\n }: {\n orgId: string;\n userId: string;\n input: UpsertCustomProviderInput;\n encryptedApiKey: string | null;\n now: Date;\n }): Promise<CustomProviderRecord> {\n const updateExisting = () =>\n this.#db.updateAtomic<CustomProviderDbRow>(\n 'custom_providers',\n { org_id: orgId, provider_id: input.providerId },\n () => ({\n name: input.name,\n url: input.url,\n api_key: encryptedApiKey,\n models: input.models,\n updated_at: now,\n }),\n );\n\n const updated = await updateExisting();\n if (updated) return this.#toRecord(updated);\n\n try {\n const row = await this.#db.insertOne<CustomProviderDbRow>('custom_providers', {\n org_id: orgId,\n created_by: userId,\n provider_id: input.providerId,\n name: input.name,\n url: input.url,\n api_key: encryptedApiKey,\n models: input.models,\n created_at: now,\n updated_at: now,\n });\n return this.#toRecord(row);\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n // Lost the insert race — apply this write to the winning row.\n const row = await updateExisting();\n if (!row) throw error;\n return this.#toRecord(row);\n }\n }\n\n async list({ orgId }: { orgId: string }): Promise<CustomProviderRecord[]> {\n const rows = await this.#db.findMany<CustomProviderDbRow>(\n 'custom_providers',\n { org_id: orgId },\n { orderBy: [['name', 'asc']] },\n );\n return Promise.all(rows.map(row => this.#toRecord(row)));\n }\n\n async delete({ orgId, providerId }: { orgId: string; providerId: string }): Promise<boolean> {\n return (await this.#db.deleteMany('custom_providers', { org_id: orgId, provider_id: providerId })) > 0;\n }\n}\n"],"mappings":";;;AAiCA,MAAa,0BAA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@@
1
1
  {
2
2
  "name": "@mastra/factory",
3
- "version": "0.21.1-alpha.2",
3
+ "version": "0.21.1-alpha.3",
4
4
  "description": "Mastra Software Factory module: the server core behind the Mastra Software Factory — storage domains, integrations, and surfaces for agent-powered software delivery",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -58,10 +58,10 @@
58
58
  "posthog-node": "^5.46.1",
59
59
  "zod": "^4.6.4",
60
60
  "@mastra/auth-studio": "1.3.9",
61
- "@mastra/auth-workos": "1.6.6",
62
- "@mastra/code-sdk": "1.12.1-alpha.2",
63
- "@mastra/core": "1.77.0-alpha.2",
64
- "@mastra/slack": "1.7.2"
61
+ "@mastra/code-sdk": "1.13.0-alpha.3",
62
+ "@mastra/core": "1.77.0-alpha.3",
63
+ "@mastra/slack": "1.7.2",
64
+ "@mastra/auth-workos": "1.6.6"
65
65
  },
66
66
  "devDependencies": {
67
67
  "@types/node": "22.20.1",
@@ -73,8 +73,8 @@
73
73
  "@internal/lint": "0.0.142",
74
74
  "@mastra/libsql": "1.26.1-alpha.0",
75
75
  "@mastra/pg": "1.31.1-alpha.0",
76
- "@internal/types-builder": "0.0.117",
77
- "@internal/workspace": "0.0.14"
76
+ "@internal/workspace": "0.0.14",
77
+ "@internal/types-builder": "0.0.117"
78
78
  },
79
79
  "engines": {
80
80
  "node": ">=22.19.0"