@intx/db 0.2.2 → 0.3.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.
Files changed (170) hide show
  1. package/README.md +2 -2
  2. package/dist/approval-store.d.ts +52 -0
  3. package/dist/approval-store.js +79 -0
  4. package/dist/asset-resolution.d.ts +2 -2
  5. package/dist/client.d.ts +10 -0
  6. package/dist/connection.js +11 -8
  7. package/dist/credential-resolution.d.ts +130 -18
  8. package/dist/credential-resolution.js +142 -3
  9. package/dist/grant-store.js +35 -13
  10. package/dist/index.d.ts +13 -4
  11. package/dist/index.js +11 -3
  12. package/dist/model-source-resolution.d.ts +52 -6
  13. package/dist/model-source-resolution.js +145 -19
  14. package/dist/parse-row.d.ts +212 -32
  15. package/dist/parse-row.js +109 -18
  16. package/dist/rekey-credential-secrets.d.ts +13 -0
  17. package/dist/rekey-credential-secrets.js +61 -0
  18. package/dist/schema/approvals.d.ts +245 -0
  19. package/dist/schema/approvals.js +52 -0
  20. package/dist/schema/catalog.d.ts +17 -0
  21. package/dist/schema/catalog.js +7 -1
  22. package/dist/schema/credentials.d.ts +1 -1
  23. package/dist/schema/git-tokens.js +1 -1
  24. package/dist/schema/grants.js +8 -2
  25. package/dist/schema/index.d.ts +8 -4
  26. package/dist/schema/index.js +8 -4
  27. package/dist/schema/messages.d.ts +5 -5
  28. package/dist/schema/messages.js +20 -9
  29. package/dist/schema/offerings.js +8 -2
  30. package/dist/schema/principals.d.ts +2 -2
  31. package/dist/schema/principals.js +7 -5
  32. package/dist/schema/providers.d.ts +17 -0
  33. package/dist/schema/providers.js +5 -0
  34. package/dist/schema/roles.js +6 -2
  35. package/dist/schema/session-assets.d.ts +1 -38
  36. package/dist/schema/session-assets.js +36 -19
  37. package/dist/schema/sessions.js +7 -2
  38. package/dist/schema/sidecar-allocation.d.ts +406 -0
  39. package/dist/schema/sidecar-allocation.js +57 -0
  40. package/dist/schema/sidecar.d.ts +19 -2
  41. package/dist/schema/sidecar.js +13 -3
  42. package/dist/schema/signal-correlations.d.ts +177 -0
  43. package/dist/schema/signal-correlations.js +31 -0
  44. package/dist/schema/wallets.d.ts +3 -3
  45. package/dist/schema/wallets.js +4 -2
  46. package/dist/schema/{agents.d.ts → workflow-definitions.d.ts} +79 -113
  47. package/dist/schema/workflow-definitions.js +97 -0
  48. package/dist/schema/workflow-run-dispatch.d.ts +328 -0
  49. package/dist/schema/workflow-run-dispatch.js +56 -0
  50. package/dist/schema/{workflow-deployments.d.ts → workflow-run-execution.d.ts} +43 -46
  51. package/dist/schema/workflow-run-execution.js +48 -0
  52. package/dist/schema/workflow-run-launch-spec.d.ts +200 -0
  53. package/dist/schema/workflow-run-launch-spec.js +26 -0
  54. package/dist/schema/{instances.d.ts → workflow-run.d.ts} +39 -71
  55. package/dist/schema/workflow-run.js +102 -0
  56. package/dist/sidecar-allocation-store.d.ts +171 -0
  57. package/dist/sidecar-allocation-store.js +512 -0
  58. package/dist/signal-correlation-store.d.ts +36 -0
  59. package/dist/signal-correlation-store.js +63 -0
  60. package/dist/tenant-hierarchy.d.ts +2 -1
  61. package/dist/tenant-hierarchy.js +10 -5
  62. package/dist/workflow-definition-store.d.ts +55 -0
  63. package/dist/workflow-definition-store.js +93 -0
  64. package/dist/workflow-run-dispatch-store.d.ts +80 -0
  65. package/dist/workflow-run-dispatch-store.js +298 -0
  66. package/dist/workflow-run-launch-spec-store.d.ts +13 -0
  67. package/dist/workflow-run-launch-spec-store.js +30 -0
  68. package/dist/workflow-run-store.d.ts +54 -0
  69. package/dist/workflow-run-store.js +85 -0
  70. package/migrations/0037_credential_use_backfill.sql +39 -0
  71. package/migrations/0038_chilly_blacklash.sql +37 -0
  72. package/migrations/0039_quick_carnage.sql +2 -0
  73. package/migrations/0040_reshape_approval_origin.sql +24 -0
  74. package/migrations/0041_make_approval_timeout_at_nullable.sql +1 -0
  75. package/migrations/0042_youthful_mantis.sql +2 -0
  76. package/migrations/0043_signal_correlation_deployment_fk.sql +1 -0
  77. package/migrations/0044_model_offering_quirks.sql +1 -0
  78. package/migrations/0045_create_workflow_run.sql +13 -0
  79. package/migrations/0046_approval_signal_correlation_run_fk.sql +2 -0
  80. package/migrations/0047_create_workflow_definition.sql +30 -0
  81. package/migrations/0048_workflow_definition_origin_agent_id.sql +2 -0
  82. package/migrations/0049_curly_omega_flight.sql +2 -0
  83. package/migrations/0050_late_crystal.sql +10 -0
  84. package/migrations/0051_funny_madelyne_pryor.sql +1 -0
  85. package/migrations/0052_drop_inference_turn_instance_fk.sql +1 -0
  86. package/migrations/0053_session_mail_session_id_index.sql +1 -0
  87. package/migrations/0054_rekey_instance_grants_to_workflow_run.sql +10 -0
  88. package/migrations/0055_backfill_anchor_workflow_runs.sql +69 -0
  89. package/migrations/0056_repoint_deployment_fks_to_anchor_run.sql +32 -0
  90. package/migrations/0057_drop_workflow_deployment_projection.sql +22 -0
  91. package/migrations/0058_repoint_offering_fk_to_definition.sql +41 -0
  92. package/migrations/0059_repoint_transaction_fk_to_run.sql +10 -0
  93. package/migrations/0060_drop_session_mail_instance_fk.sql +6 -0
  94. package/migrations/0061_drop_session_asset_instance_fk.sql +7 -0
  95. package/migrations/0062_drop_agent_asset_table.sql +11 -0
  96. package/migrations/0063_repoint_agent_role_fk_to_definition.sql +39 -0
  97. package/migrations/0064_repoint_agent_session_fk_to_definition.sql +47 -0
  98. package/migrations/0065_add_workflow_definition_model_requirements.sql +37 -0
  99. package/migrations/0066_rekey_agent_definition_principals_to_workflow.sql +27 -0
  100. package/migrations/0067_add_workflow_definition_kind.sql +10 -0
  101. package/migrations/0068_drop_agent_tables_and_origin_agent_id.sql +31 -0
  102. package/migrations/0069_drop_workflow_definition_kind.sql +10 -0
  103. package/migrations/0070_flashy_proteus.sql +13 -0
  104. package/migrations/0072_add_workflow_definition_credential_bindings.sql +1 -0
  105. package/migrations/0073_grant_target_exactly_one_check.sql +13 -0
  106. package/migrations/0074_add_provider_api_base_url.sql +1 -0
  107. package/migrations/0075_workflow_run_launch_spec.sql +17 -0
  108. package/migrations/0076_sidecar_allocation.sql +40 -0
  109. package/migrations/0077_workflow_run_dispatch.sql +29 -0
  110. package/migrations/0078_workflow_run_dispatch_kind.sql +2 -0
  111. package/migrations/0079_rename_workflow_run_deployment_id_to_anchor_run_id.sql +4 -0
  112. package/migrations/0080_rename_correlation_approval_deployment_id_to_anchor_run_id.sql +9 -0
  113. package/migrations/0081_workflow_definition_content_hash_and_approved_wire_hash.sql +4 -0
  114. package/migrations/0082_blue_black_queen.sql +1 -0
  115. package/migrations/0083_replace_launch_spec_snapshot_with_frozen_bundle.sql +3 -0
  116. package/migrations/0084_delete_orphaned_credential_grants.sql +22 -0
  117. package/migrations/meta/0037_snapshot.json +3237 -0
  118. package/migrations/meta/0038_snapshot.json +3470 -0
  119. package/migrations/meta/0039_snapshot.json +3470 -0
  120. package/migrations/meta/0040_snapshot.json +3489 -0
  121. package/migrations/meta/0041_snapshot.json +3489 -0
  122. package/migrations/meta/0042_snapshot.json +3489 -0
  123. package/migrations/meta/0043_snapshot.json +3498 -0
  124. package/migrations/meta/0044_snapshot.json +3504 -0
  125. package/migrations/meta/0045_snapshot.json +3589 -0
  126. package/migrations/meta/0046_snapshot.json +3607 -0
  127. package/migrations/meta/0047_snapshot.json +3832 -0
  128. package/migrations/meta/0048_snapshot.json +3853 -0
  129. package/migrations/meta/0049_snapshot.json +3854 -0
  130. package/migrations/meta/0050_snapshot.json +3924 -0
  131. package/migrations/meta/0051_snapshot.json +3940 -0
  132. package/migrations/meta/0052_snapshot.json +3931 -0
  133. package/migrations/meta/0053_snapshot.json +3952 -0
  134. package/migrations/meta/0054_snapshot.json +3952 -0
  135. package/migrations/meta/0055_snapshot.json +3952 -0
  136. package/migrations/meta/0056_snapshot.json +3952 -0
  137. package/migrations/meta/0057_snapshot.json +3839 -0
  138. package/migrations/meta/0058_snapshot.json +3839 -0
  139. package/migrations/meta/0059_snapshot.json +3839 -0
  140. package/migrations/meta/0060_snapshot.json +3830 -0
  141. package/migrations/meta/0061_snapshot.json +3821 -0
  142. package/migrations/meta/0062_snapshot.json +3723 -0
  143. package/migrations/meta/0063_snapshot.json +3723 -0
  144. package/migrations/meta/0064_snapshot.json +3723 -0
  145. package/migrations/meta/0065_snapshot.json +3729 -0
  146. package/migrations/meta/0066_snapshot.json +3729 -0
  147. package/migrations/meta/0067_snapshot.json +3736 -0
  148. package/migrations/meta/0068_snapshot.json +3347 -0
  149. package/migrations/meta/0069_snapshot.json +3340 -0
  150. package/migrations/meta/0070_snapshot.json +3444 -0
  151. package/migrations/meta/0072_snapshot.json +3450 -0
  152. package/migrations/meta/0073_snapshot.json +3455 -0
  153. package/migrations/meta/0074_snapshot.json +3461 -0
  154. package/migrations/meta/0075_snapshot.json +3567 -0
  155. package/migrations/meta/0076_snapshot.json +3851 -0
  156. package/migrations/meta/0077_snapshot.json +4067 -0
  157. package/migrations/meta/0078_snapshot.json +4078 -0
  158. package/migrations/meta/0079_snapshot.json +4078 -0
  159. package/migrations/meta/0080_snapshot.json +4078 -0
  160. package/migrations/meta/0081_snapshot.json +4096 -0
  161. package/migrations/meta/0082_snapshot.json +4102 -0
  162. package/migrations/meta/0083_snapshot.json +4096 -0
  163. package/migrations/meta/0084_snapshot.json +4096 -0
  164. package/migrations/meta/_journal.json +329 -0
  165. package/package.json +6 -3
  166. package/dist/schema/agent-assets.d.ts +0 -109
  167. package/dist/schema/agent-assets.js +0 -15
  168. package/dist/schema/agents.js +0 -57
  169. package/dist/schema/instances.js +0 -39
  170. package/dist/schema/workflow-deployments.js +0 -37
package/README.md CHANGED
@@ -31,8 +31,8 @@ const row = await db.query.agent.findFirst({
31
31
  });
32
32
  ```
33
33
 
34
- The `parseRow` functions (`parseAgentRow`, `parseGrantRow`, and so
35
- on) validate each table's `jsonb` columns once and return fully
34
+ The `parseRow` functions (`parseWorkflowDefinitionRow`, `parseGrantRow`,
35
+ and so on) validate each table's `jsonb` columns once and return fully
36
36
  typed values; downstream code uses those values without
37
37
  re-casting. See `CONVENTIONS.md` for the project-wide rule against
38
38
  cast-at-callsite in DB consumers.
@@ -0,0 +1,52 @@
1
+ import type { DB, DBExecutor } from "./client.js";
2
+ import { approval } from "./schema/approvals.js";
3
+ import { parseApprovalRow } from "./parse-row.js";
4
+ type DBHandle = DB["db"];
5
+ type ApprovalRow = typeof approval.$inferSelect;
6
+ type ApprovalInsert = typeof approval.$inferInsert;
7
+ type ParsedApproval = ReturnType<typeof parseApprovalRow>;
8
+ type ApprovalResolution = Exclude<ApprovalRow["status"], "pending">;
9
+ type ApprovalScope = NonNullable<ApprovalRow["scope"]>;
10
+ export type ResolveApprovalArgs = {
11
+ status: ApprovalResolution;
12
+ scope?: ApprovalScope;
13
+ resolvedAt: Date;
14
+ };
15
+ /**
16
+ * Store for the `approval` table backing the approval round-trip. Each method
17
+ * accepts an optional transaction handle so the resolver can flip the approval
18
+ * and its signal correlation in a single `db.transaction`; when omitted the
19
+ * method runs against the store's own connection.
20
+ */
21
+ export declare function createApprovalStore(db: DBHandle): {
22
+ create(row: ApprovalInsert, tx?: DBExecutor): Promise<ParsedApproval>;
23
+ /**
24
+ * Idempotent variant of `create`. On a `correlationId` unique conflict the
25
+ * insert is a no-op and this returns `null` rather than throwing, so a
26
+ * redelivered register frame (sidecar reconnect, workflow-log replay,
27
+ * supervisor restart re-emitting) does not fail the co-write. Conflicts
28
+ * on `correlationId` -- not the `id` primary key -- because the register
29
+ * co-write mints a fresh `id` per frame while the correlation is the stable
30
+ * dedup key. Returns the parsed row only when this call performed the
31
+ * insert.
32
+ */
33
+ createIfAbsent(row: ApprovalInsert, tx?: DBExecutor): Promise<ParsedApproval | null>;
34
+ findByCorrelationId(correlationId: string, tx?: DBExecutor): Promise<ParsedApproval | null>;
35
+ /**
36
+ * Look up an approval by its primary key. The resolve/reject routes key on
37
+ * the `approvalId` path parameter, which is the row's `id`, so they need a
38
+ * by-id read distinct from the by-correlation read the register co-write
39
+ * uses. Returns null when no row carries the id.
40
+ */
41
+ findById(id: string, tx?: DBExecutor): Promise<ParsedApproval | null>;
42
+ /**
43
+ * Conditionally resolve a pending approval. The `WHERE status = 'pending'`
44
+ * guard makes resolution terminal at the database: the first caller to
45
+ * resolve a given correlation gets the updated row back; any later caller
46
+ * (a duplicate delivery, a timeout racing an approval) matches no row and
47
+ * receives null.
48
+ */
49
+ resolve(correlationId: string, args: ResolveApprovalArgs, tx?: DBExecutor): Promise<ParsedApproval | null>;
50
+ };
51
+ export type ApprovalStore = ReturnType<typeof createApprovalStore>;
52
+ export {};
@@ -0,0 +1,79 @@
1
+ import { and, eq } from "drizzle-orm";
2
+ import { approval } from "./schema/approvals.js";
3
+ import { parseApprovalRow } from "./parse-row.js";
4
+ /**
5
+ * Store for the `approval` table backing the approval round-trip. Each method
6
+ * accepts an optional transaction handle so the resolver can flip the approval
7
+ * and its signal correlation in a single `db.transaction`; when omitted the
8
+ * method runs against the store's own connection.
9
+ */
10
+ export function createApprovalStore(db) {
11
+ return {
12
+ async create(row, tx) {
13
+ const [inserted] = await (tx ?? db)
14
+ .insert(approval)
15
+ .values(row)
16
+ .returning();
17
+ if (inserted === undefined) {
18
+ throw new Error(`approvalStore.create: insert returned no row for ${row.id}`);
19
+ }
20
+ return parseApprovalRow(inserted);
21
+ },
22
+ /**
23
+ * Idempotent variant of `create`. On a `correlationId` unique conflict the
24
+ * insert is a no-op and this returns `null` rather than throwing, so a
25
+ * redelivered register frame (sidecar reconnect, workflow-log replay,
26
+ * supervisor restart re-emitting) does not fail the co-write. Conflicts
27
+ * on `correlationId` -- not the `id` primary key -- because the register
28
+ * co-write mints a fresh `id` per frame while the correlation is the stable
29
+ * dedup key. Returns the parsed row only when this call performed the
30
+ * insert.
31
+ */
32
+ async createIfAbsent(row, tx) {
33
+ const [inserted] = await (tx ?? db)
34
+ .insert(approval)
35
+ .values(row)
36
+ .onConflictDoNothing({ target: approval.correlationId })
37
+ .returning();
38
+ return inserted === undefined ? null : parseApprovalRow(inserted);
39
+ },
40
+ async findByCorrelationId(correlationId, tx) {
41
+ const row = await (tx ?? db).query.approval.findFirst({
42
+ where: eq(approval.correlationId, correlationId),
43
+ });
44
+ return row === undefined ? null : parseApprovalRow(row);
45
+ },
46
+ /**
47
+ * Look up an approval by its primary key. The resolve/reject routes key on
48
+ * the `approvalId` path parameter, which is the row's `id`, so they need a
49
+ * by-id read distinct from the by-correlation read the register co-write
50
+ * uses. Returns null when no row carries the id.
51
+ */
52
+ async findById(id, tx) {
53
+ const row = await (tx ?? db).query.approval.findFirst({
54
+ where: eq(approval.id, id),
55
+ });
56
+ return row === undefined ? null : parseApprovalRow(row);
57
+ },
58
+ /**
59
+ * Conditionally resolve a pending approval. The `WHERE status = 'pending'`
60
+ * guard makes resolution terminal at the database: the first caller to
61
+ * resolve a given correlation gets the updated row back; any later caller
62
+ * (a duplicate delivery, a timeout racing an approval) matches no row and
63
+ * receives null.
64
+ */
65
+ async resolve(correlationId, args, tx) {
66
+ const [updated] = await (tx ?? db)
67
+ .update(approval)
68
+ .set({
69
+ status: args.status,
70
+ scope: args.scope ?? null,
71
+ resolvedAt: args.resolvedAt,
72
+ updatedAt: new Date(),
73
+ })
74
+ .where(and(eq(approval.correlationId, correlationId), eq(approval.status, "pending")))
75
+ .returning();
76
+ return updated === undefined ? null : parseApprovalRow(updated);
77
+ },
78
+ };
79
+ }
@@ -23,8 +23,8 @@ export declare function resolveAssetByName(db: DB["db"], tenantId: string, kind:
23
23
  createdAt: Date;
24
24
  updatedAt: Date;
25
25
  tenantId: string;
26
- creatorPrincipalId: string | null;
27
26
  displayName: string | null;
27
+ creatorPrincipalId: string | null;
28
28
  } | null>;
29
29
  /**
30
30
  * Resolves an asset by ID, validating that it belongs to the given
@@ -38,8 +38,8 @@ export declare function resolveAssetById(db: DB["db"], tenantId: string, assetId
38
38
  createdAt: Date;
39
39
  updatedAt: Date;
40
40
  tenantId: string;
41
- creatorPrincipalId: string | null;
42
41
  displayName: string | null;
42
+ creatorPrincipalId: string | null;
43
43
  } | null>;
44
44
  /**
45
45
  * Lists assets visible to the tenant, including those inherited from
package/dist/client.d.ts CHANGED
@@ -7,3 +7,13 @@ export declare function createDB(raw: unknown): {
7
7
  close: () => Promise<void>;
8
8
  };
9
9
  export type DB = ReturnType<typeof createDB>;
10
+ /**
11
+ * A handle that can execute queries: either the top-level `db` or a
12
+ * transaction handle passed into a `db.transaction` callback. Store methods
13
+ * that accept an optional `tx` type it against this so a caller can hand in
14
+ * the transaction object and have the write join the surrounding transaction.
15
+ * `DB["db"]` alone rejects a `PgTransaction` (it lacks the `$client` field the
16
+ * top-level database carries), so a bare `DB["db"]` parameter cannot accept a
17
+ * tx.
18
+ */
19
+ export type DBExecutor = DB["db"] | Parameters<Parameters<DB["db"]["transaction"]>[0]>[0];
@@ -11,13 +11,16 @@ export function createConnection(config) {
11
11
  database: config.database,
12
12
  max: config.max ?? 10,
13
13
  ...(config.ssl !== undefined && { ssl: config.ssl }),
14
- ...(config.schema !== undefined && {
15
- // Pin the connection's search_path so unqualified table
16
- // references resolve to the caller's schema. The migration
17
- // runner emits SQL with the schema baked into FK references,
18
- // but ORM-issued queries bind table names without a schema
19
- // qualifier and rely on this setting.
20
- connection: { search_path: quoteIdentifier(config.schema) },
21
- }),
14
+ connection: {
15
+ TimeZone: "UTC",
16
+ ...(config.schema !== undefined && {
17
+ // Pin the connection's search_path so unqualified table
18
+ // references resolve to the caller's schema. The migration
19
+ // runner emits SQL with the schema baked into FK references,
20
+ // but ORM-issued queries bind table names without a schema
21
+ // qualifier and rely on this setting.
22
+ search_path: quoteIdentifier(config.schema),
23
+ }),
24
+ },
22
25
  });
23
26
  }
@@ -1,4 +1,46 @@
1
+ import type { CredentialBinding, CredentialCipher } from "@intx/types";
2
+ import type { CredentialDelivery } from "@intx/types/sidecar";
1
3
  import type { DB } from "./client.js";
4
+ /**
5
+ * Thrown by `resolveCredentialRequirement` when more than one credential
6
+ * matches a requirement and no name disambiguates them. A distinct type so
7
+ * callers can catch *this* condition (a launch-blocking configuration error)
8
+ * without also swallowing the DB reads the resolver performs first -- an
9
+ * infrastructure failure must surface, not be mislabeled as ambiguity.
10
+ */
11
+ export declare class AmbiguousCredentialError extends Error {
12
+ constructor(message: string);
13
+ }
14
+ /**
15
+ * Resolve a credential USABLE by the launching tenant purely through ownership:
16
+ * it exists, is reachable in the tenant's ancestor chain, and is tenant-owned
17
+ * (`principalId IS NULL`). Returns the row -- the proof of authority -- or null.
18
+ *
19
+ * This is the one "usable by ownership" resolver: a tenant may use what it (or
20
+ * an ancestor) owns, and descendants inherit; a principal-owned credential is
21
+ * never usable this way, its delegation flowing from its owner instead. It
22
+ * wraps `resolveCredentialById` (the ancestor-chain check) with the tenant-owned
23
+ * gate, so callers do not re-implement the predicate. `buildSource` expands it
24
+ * inline only to distinguish an unresolved reference from a principal-owned one.
25
+ */
26
+ export declare function resolveTenantOwnedCredentialById(db: DB["db"], tenantId: string, credentialId: string): Promise<{
27
+ id: string;
28
+ name: string;
29
+ createdAt: Date;
30
+ updatedAt: Date;
31
+ expiresAt: Date | null;
32
+ providerId: string;
33
+ tenantId: string;
34
+ status: "active" | "error" | "expired" | "revoked";
35
+ description: string | null;
36
+ principalId: string | null;
37
+ scopes: string[] | null;
38
+ metadata: unknown;
39
+ oauthClientId: string | null;
40
+ type: "api_key" | "oauth_token" | "certificate" | "other";
41
+ secret: string;
42
+ refreshSecret: string | null;
43
+ } | null>;
2
44
  /**
3
45
  * Resolves a provider by name, walking up the tenant hierarchy.
4
46
  * Returns the first match (child shadows parent).
@@ -10,6 +52,7 @@ export declare function resolveProviderByName(db: DB["db"], tenantId: string, na
10
52
  updatedAt: Date;
11
53
  tenantId: string;
12
54
  plugin: string;
55
+ apiBaseUrl: string | null;
13
56
  authorizationUrl: string | null;
14
57
  tokenUrl: string | null;
15
58
  userInfoUrl: string | null;
@@ -45,7 +88,7 @@ export declare function resolveCredentialByName(db: DB["db"], tenantId: string,
45
88
  expiresAt: Date | null;
46
89
  providerId: string;
47
90
  tenantId: string;
48
- status: "active" | "expired" | "revoked" | "error";
91
+ status: "active" | "error" | "expired" | "revoked";
49
92
  description: string | null;
50
93
  principalId: string | null;
51
94
  scopes: string[] | null;
@@ -67,7 +110,7 @@ export declare function resolveCredentialById(db: DB["db"], tenantId: string, cr
67
110
  expiresAt: Date | null;
68
111
  providerId: string;
69
112
  tenantId: string;
70
- status: "active" | "expired" | "revoked" | "error";
113
+ status: "active" | "error" | "expired" | "revoked";
71
114
  description: string | null;
72
115
  principalId: string | null;
73
116
  scopes: string[] | null;
@@ -90,21 +133,90 @@ type CredentialRequirement = {
90
133
  * catalog, not this path).
91
134
  */
92
135
  export declare function resolveCredentialRequirement(db: DB["db"], tenantId: string, requirement: CredentialRequirement, creatorPrincipalId: string | null, invokerPrincipalId: string | null): Promise<{
93
- id: string;
94
- name: string;
95
- createdAt: Date;
96
- updatedAt: Date;
97
- expiresAt: Date | null;
98
- providerId: string;
99
- tenantId: string;
100
- status: "active" | "expired" | "revoked" | "error";
101
- description: string | null;
102
- principalId: string | null;
103
- scopes: string[] | null;
104
- metadata: unknown;
105
- oauthClientId: string | null;
106
- type: "api_key" | "oauth_token" | "certificate" | "other";
107
- secret: string;
108
- refreshSecret: string | null;
136
+ credential: {
137
+ id: string;
138
+ name: string;
139
+ createdAt: Date;
140
+ updatedAt: Date;
141
+ expiresAt: Date | null;
142
+ providerId: string;
143
+ tenantId: string;
144
+ status: "active" | "error" | "expired" | "revoked";
145
+ description: string | null;
146
+ principalId: string | null;
147
+ scopes: string[] | null;
148
+ metadata: unknown;
149
+ oauthClientId: string | null;
150
+ type: "api_key" | "oauth_token" | "certificate" | "other";
151
+ secret: string;
152
+ refreshSecret: string | null;
153
+ };
154
+ provider: {
155
+ id: string;
156
+ name: string;
157
+ createdAt: Date;
158
+ updatedAt: Date;
159
+ tenantId: string;
160
+ plugin: string;
161
+ apiBaseUrl: string | null;
162
+ authorizationUrl: string | null;
163
+ tokenUrl: string | null;
164
+ userInfoUrl: string | null;
165
+ scopes: string[] | null;
166
+ metadata: unknown;
167
+ };
109
168
  } | null>;
169
+ /**
170
+ * A launch-blocking CONFIGURATION failure for one binding: a binding no
171
+ * credential resolves, a provider with no API origin (can't pin an http
172
+ * handle), or an ambiguous match. Distinct from an infrastructure failure (a DB
173
+ * read fault), which `buildCredentialDelivery` THROWS rather than returning --
174
+ * so a caller never mistakes a transient fault for revocation.
175
+ */
176
+ export type CredentialDeliveryFailure = {
177
+ code: "unresolved" | "no_origin" | "ambiguous";
178
+ binding: {
179
+ provider: string;
180
+ package: string;
181
+ handle: string;
182
+ };
183
+ message: string;
184
+ };
185
+ /**
186
+ * Outcome of `buildCredentialDelivery`. `ok: true` carries the material +
187
+ * descriptors delivered to the tools; `delivery` is `undefined` when there are
188
+ * no bindings. `ok: false` carries the first launch-blocking configuration
189
+ * failure for the caller to map to a fail-closed response.
190
+ */
191
+ export type BuildCredentialDeliveryResult = {
192
+ ok: true;
193
+ delivery: CredentialDelivery | undefined;
194
+ } | {
195
+ ok: false;
196
+ reason: CredentialDeliveryFailure;
197
+ };
198
+ /**
199
+ * Resolve a definition's credential bindings into the material + per-handle
200
+ * descriptors delivered to its tools. Each credential's secret is decrypted
201
+ * once, keyed by credentialId (a credential backing several handles is
202
+ * decrypted once).
203
+ *
204
+ * This path delivers credential material only; it does not mint, stamp, or
205
+ * carry any grant. Credential-use authorization is enforced by a separate grant
206
+ * layer.
207
+ *
208
+ * The workflow-deploy path (`deployCodeSourcedWorkflow`) is the only caller
209
+ * today, using `delivery`. Returning a discriminated result rather than an HTTP
210
+ * response keeps it safe to call off the request path: a configuration failure
211
+ * is `ok: false`, and a transient DB read fault THROWS so the caller surfaces it
212
+ * rather than silently dropping a still-valid credential.
213
+ */
214
+ export declare function buildCredentialDelivery(args: {
215
+ db: DB["db"];
216
+ tenantId: string;
217
+ bindings: readonly CredentialBinding[];
218
+ creatorPrincipalId: string | null;
219
+ invokerPrincipalId: string | null;
220
+ credentialCipher: CredentialCipher;
221
+ }): Promise<BuildCredentialDeliveryResult>;
110
222
  export {};
@@ -1,8 +1,39 @@
1
1
  import { eq, and, isNull } from "drizzle-orm";
2
+ import { toolConsumer } from "@intx/authz";
3
+ import { credentialAad } from "@intx/types";
2
4
  import { credential } from "./schema/credentials.js";
3
5
  import { oauthClient } from "./schema/oauth-clients.js";
4
6
  import { provider } from "./schema/providers.js";
5
7
  import { getAncestorChain } from "./tenant-hierarchy.js";
8
+ /**
9
+ * Thrown by `resolveCredentialRequirement` when more than one credential
10
+ * matches a requirement and no name disambiguates them. A distinct type so
11
+ * callers can catch *this* condition (a launch-blocking configuration error)
12
+ * without also swallowing the DB reads the resolver performs first -- an
13
+ * infrastructure failure must surface, not be mislabeled as ambiguity.
14
+ */
15
+ export class AmbiguousCredentialError extends Error {
16
+ constructor(message) {
17
+ super(message);
18
+ this.name = "AmbiguousCredentialError";
19
+ }
20
+ }
21
+ /**
22
+ * Resolve a credential USABLE by the launching tenant purely through ownership:
23
+ * it exists, is reachable in the tenant's ancestor chain, and is tenant-owned
24
+ * (`principalId IS NULL`). Returns the row -- the proof of authority -- or null.
25
+ *
26
+ * This is the one "usable by ownership" resolver: a tenant may use what it (or
27
+ * an ancestor) owns, and descendants inherit; a principal-owned credential is
28
+ * never usable this way, its delegation flowing from its owner instead. It
29
+ * wraps `resolveCredentialById` (the ancestor-chain check) with the tenant-owned
30
+ * gate, so callers do not re-implement the predicate. `buildSource` expands it
31
+ * inline only to distinguish an unresolved reference from a principal-owned one.
32
+ */
33
+ export async function resolveTenantOwnedCredentialById(db, tenantId, credentialId) {
34
+ const row = await resolveCredentialById(db, tenantId, credentialId);
35
+ return row !== null && row.principalId === null ? row : null;
36
+ }
6
37
  /**
7
38
  * Resolves a provider by name, walking up the tenant hierarchy.
8
39
  * Returns the first match (child shadows parent).
@@ -104,13 +135,121 @@ export async function resolveCredentialRequirement(db, tenantId, requirement, cr
104
135
  return requirement.scopes.every((s) => rowScopes.includes(s));
105
136
  });
106
137
  const [sole] = matching;
107
- if (matching.length === 1 && sole)
108
- return sole;
138
+ // Return the resolved provider alongside the credential. The provider was
139
+ // already fetched above to constrain the credential query, so surfacing it
140
+ // spares the caller a second lookup for the provider facts (plugin, base
141
+ // URL) a resolved credential is always paired with.
142
+ if (matching.length === 1 && sole) {
143
+ return { credential: sole, provider: resolvedProvider };
144
+ }
109
145
  if (matching.length > 1) {
110
- throw new Error(`Ambiguous credential match: ${matching.length} credentials match ` +
146
+ throw new AmbiguousCredentialError(`Ambiguous credential match: ${matching.length} credentials match ` +
111
147
  `provider=${requirement.providerName} source=${requirement.source} ` +
112
148
  `in tenant ${tid}. Specify a name to disambiguate.`);
113
149
  }
114
150
  }
115
151
  return null;
116
152
  }
153
+ /**
154
+ * Resolve a definition's credential bindings into the material + per-handle
155
+ * descriptors delivered to its tools. Each credential's secret is decrypted
156
+ * once, keyed by credentialId (a credential backing several handles is
157
+ * decrypted once).
158
+ *
159
+ * This path delivers credential material only; it does not mint, stamp, or
160
+ * carry any grant. Credential-use authorization is enforced by a separate grant
161
+ * layer.
162
+ *
163
+ * The workflow-deploy path (`deployCodeSourcedWorkflow`) is the only caller
164
+ * today, using `delivery`. Returning a discriminated result rather than an HTTP
165
+ * response keeps it safe to call off the request path: a configuration failure
166
+ * is `ok: false`, and a transient DB read fault THROWS so the caller surfaces it
167
+ * rather than silently dropping a still-valid credential.
168
+ */
169
+ export async function buildCredentialDelivery(args) {
170
+ const materials = new Map();
171
+ const descriptors = [];
172
+ for (const binding of args.bindings) {
173
+ const context = {
174
+ provider: binding.provider,
175
+ package: binding.package,
176
+ handle: binding.handle,
177
+ };
178
+ let resolved;
179
+ try {
180
+ resolved = await resolveCredentialRequirement(args.db, args.tenantId, {
181
+ providerName: binding.provider,
182
+ source: binding.locator,
183
+ ...(binding.name !== undefined ? { name: binding.name } : {}),
184
+ }, args.creatorPrincipalId, args.invokerPrincipalId);
185
+ }
186
+ catch (e) {
187
+ // AmbiguousCredentialError is a launch-blocking config failure; any other
188
+ // throw is a DB read fault the resolver performs first -- surface it, do
189
+ // not mislabel it as revocation.
190
+ if (!(e instanceof AmbiguousCredentialError))
191
+ throw e;
192
+ return {
193
+ ok: false,
194
+ reason: {
195
+ code: "ambiguous",
196
+ binding: context,
197
+ message: `Ambiguous credential for the binding on provider ${binding.provider} (package ${binding.package}, handle ${binding.handle}): ${e.message}`,
198
+ },
199
+ };
200
+ }
201
+ if (resolved === null) {
202
+ return {
203
+ ok: false,
204
+ reason: {
205
+ code: "unresolved",
206
+ binding: context,
207
+ message: `No credential resolves the binding for provider ${binding.provider} (package ${binding.package}, handle ${binding.handle})`,
208
+ },
209
+ };
210
+ }
211
+ // The credential is delivered as an origin-pinned http handle, so its
212
+ // provider must declare an API origin. A provider without one (OAuth-login
213
+ // only) cannot back a tool credential; fail closed rather than deliver an
214
+ // un-pinnable secret.
215
+ const providerOrigin = resolved.provider.apiBaseUrl;
216
+ if (providerOrigin === null || providerOrigin === "") {
217
+ return {
218
+ ok: false,
219
+ reason: {
220
+ code: "no_origin",
221
+ binding: context,
222
+ message: `Provider ${binding.provider} has no API base URL; cannot deliver an origin-pinned credential (package ${binding.package}, handle ${binding.handle})`,
223
+ },
224
+ };
225
+ }
226
+ const credentialId = resolved.credential.id;
227
+ // A binding resolves only a tenant-owned credential (the `tenant` locator
228
+ // filters `principalId IS NULL` in resolveCredentialRequirement), so its use
229
+ // is authorized by ownership -- already proven by this walk-up resolution,
230
+ // not re-checked here. This path delivers credential material only; it does
231
+ // not mint or carry any grant. Credential-use authorization is enforced by a
232
+ // separate grant layer.
233
+ descriptors.push({
234
+ handle: binding.handle,
235
+ credentialId,
236
+ consumer: toolConsumer(binding.package),
237
+ });
238
+ if (!materials.has(credentialId)) {
239
+ // Decrypt at the single point of use. A decrypt failure propagates and
240
+ // fails the caller closed; there is no placeholder secret.
241
+ materials.set(credentialId, {
242
+ credentialId,
243
+ providerKey: resolved.provider.plugin,
244
+ origin: providerOrigin,
245
+ secret: await args.credentialCipher.decrypt(resolved.credential.secret, credentialAad(credentialId, "secret")),
246
+ });
247
+ }
248
+ }
249
+ return {
250
+ ok: true,
251
+ delivery: descriptors.length > 0
252
+ ? { bindings: descriptors, materials: [...materials.values()] }
253
+ : undefined,
254
+ };
255
+ }
@@ -2,6 +2,7 @@ import { eq, and, or, isNull, gt, inArray } from "drizzle-orm";
2
2
  import { grant } from "./schema/grants.js";
3
3
  import { principalRole } from "./schema/roles.js";
4
4
  import { parseGrantRow } from "./parse-row.js";
5
+ import { getAncestorChain } from "./tenant-hierarchy.js";
5
6
  function toGrantRule(row) {
6
7
  const parsed = parseGrantRow(row);
7
8
  return {
@@ -16,22 +17,43 @@ function toGrantRule(row) {
16
17
  principalId: parsed.principalId,
17
18
  };
18
19
  }
20
+ /**
21
+ * Collects a principal's live (non-expired) grants — the ones the principal
22
+ * owns directly plus the ones granted to any role it holds — restricted to
23
+ * the tenants matched by `tenantScope`. The scope is the sole knob that
24
+ * decides single-tenant versus chain-aware collection.
25
+ */
26
+ async function collectGrantsScoped(db, principalId, tenantScope) {
27
+ const roleAssignments = await db.query.principalRole.findMany({
28
+ where: eq(principalRole.principalId, principalId),
29
+ });
30
+ const roleIds = roleAssignments.map((a) => a.roleId);
31
+ const now = new Date();
32
+ const ownership = [eq(grant.principalId, principalId)];
33
+ if (roleIds.length > 0) {
34
+ ownership.push(inArray(grant.roleId, roleIds));
35
+ }
36
+ const rows = await db.query.grant.findMany({
37
+ where: and(tenantScope, or(...ownership), or(isNull(grant.expiresAt), gt(grant.expiresAt, now))),
38
+ });
39
+ return rows.map(toGrantRule);
40
+ }
19
41
  export function createGrantStore(db) {
20
42
  return {
21
43
  async collectGrants(principalId, tenantId) {
22
- const roleAssignments = await db.query.principalRole.findMany({
23
- where: eq(principalRole.principalId, principalId),
24
- });
25
- const roleIds = roleAssignments.map((a) => a.roleId);
26
- const now = new Date();
27
- const ownership = [eq(grant.principalId, principalId)];
28
- if (roleIds.length > 0) {
29
- ownership.push(inArray(grant.roleId, roleIds));
30
- }
31
- const rows = await db.query.grant.findMany({
32
- where: and(eq(grant.tenantId, tenantId), or(...ownership), or(isNull(grant.expiresAt), gt(grant.expiresAt, now))),
33
- });
34
- return rows.map(toGrantRule);
44
+ return collectGrantsScoped(db, principalId, eq(grant.tenantId, tenantId));
45
+ },
46
+ // Union the principal's grants across the tenant ancestor chain — the
47
+ // acting tenant plus every ancestor up to the root. Mirrors the
48
+ // ancestor-chain resolution credential lookup already performs, so a
49
+ // `credential:{id}` / `use` grant stamped with an ancestor tenant (as the
50
+ // mint path and 0037 backfill do) still authorizes use of a credential
51
+ // inherited down the chain. Kept distinct from the single-tenant
52
+ // `collectGrants` so only the source-resolution credential-use check
53
+ // widens to the chain; the general RBAC path stays single-tenant.
54
+ async collectGrantsInChain(principalId, tenantId) {
55
+ const chain = await getAncestorChain(db, tenantId);
56
+ return collectGrantsScoped(db, principalId, inArray(grant.tenantId, chain));
35
57
  },
36
58
  };
37
59
  }
package/dist/index.d.ts CHANGED
@@ -1,13 +1,22 @@
1
- export { createDB, type DB } from "./client.js";
1
+ export { createDB, type DB, type DBExecutor } from "./client.js";
2
2
  export { pgErrorCode, PG_UNIQUE_VIOLATION, PG_FOREIGN_KEY_VIOLATION, } from "./pg-error.js";
3
3
  export type { DBConfig } from "./config.js";
4
4
  export { runMigrations, dropSchema } from "./migrate.js";
5
+ export { rekeyCredentialSecrets, type RekeyReport, } from "./rekey-credential-secrets.js";
5
6
  export { createGrantStore } from "./grant-store.js";
7
+ export { createApprovalStore, type ApprovalStore, type ResolveApprovalArgs, } from "./approval-store.js";
8
+ export { createSignalCorrelationStore, type SignalCorrelationStore, } from "./signal-correlation-store.js";
9
+ export { createWorkflowRunStore, type WorkflowRunStore, } from "./workflow-run-store.js";
10
+ export { createWorkflowRunLaunchSpecStore, type WorkflowRunLaunchSpecStore, } from "./workflow-run-launch-spec-store.js";
11
+ export { createWorkflowRunDispatchStore, WorkflowRunDispatchPayloadConflictError, type AcknowledgeWorkflowRunDispatchArgs, type ClaimWorkflowRunDispatchArgs, type EnqueueWorkflowRunDispatchArgs, type EnqueueWorkflowRunDispatchResult, type EnqueueWorkflowSignalDispatchArgs, type RetryWorkflowRunDispatchArgs, type WorkflowRunDispatchStore, } from "./workflow-run-dispatch-store.js";
12
+ export { createSidecarAllocationStore, type BeginSidecarReleaseArgs, type BeginSidecarReplacementArgs, type BindInitialSidecarArgs, type BindReplacementSidecarArgs, type ClaimSidecarAllocationArgs, type CreatePendingSidecarAllocationArgs, type FailSidecarAllocationArgs, type MarkSidecarAllocatedArgs, type MarkSidecarConnectionLostArgs, type MarkSidecarConnectionReadyArgs, type MarkSidecarReleasedArgs, type ParkSidecarReconciliationPolicy, type ScheduleSidecarAllocationRetryArgs, type SidecarAllocation, type SidecarAllocationStore, } from "./sidecar-allocation-store.js";
13
+ export { createWorkflowDefinitionStore, loadFrozenGrantSnapshot, resolveDefinitionIdForAsset, type WorkflowDefinitionRollbackResult, type WorkflowDefinitionSelector, } from "./workflow-definition-store.js";
6
14
  export { getAncestorChain, getDescendantTenants } from "./tenant-hierarchy.js";
7
15
  export { resolveActivePrice, type ModelPricingRow } from "./pricing.js";
8
- export { resolveProviderByName, resolveOAuthClient, resolveCredentialByName, resolveCredentialById, resolveCredentialRequirement, } from "./credential-resolution.js";
16
+ export { resolveProviderByName, resolveOAuthClient, resolveCredentialByName, resolveCredentialById, resolveCredentialRequirement, resolveTenantOwnedCredentialById, AmbiguousCredentialError, buildCredentialDelivery, } from "./credential-resolution.js";
17
+ export type { BuildCredentialDeliveryResult, CredentialDeliveryFailure, } from "./credential-resolution.js";
9
18
  export { resolveAssetByName, resolveAssetById, listAssetsForTenant, type AssetRow, type AssetWithOrigin, } from "./asset-resolution.js";
10
19
  export { listVisibleModels, listVisibleProviders, listVisibleOfferings, type ModelRow, type ModelProviderRow, type ModelOfferingRow, type Origin, type VisibleModel, type VisibleProvider, type ResolvedOffering, } from "./catalog-resolution.js";
11
- export { resolveModelSources, resolveInstanceModelSources, type CatalogSourceResolution, type SourceSkip, } from "./model-source-resolution.js";
12
- export { parseAgentRow, parseAgentVersionRow, parseGrantRow, parseOfferingRow, parseCredentialRow, parseProviderRow, parseTenantRow, parseWalletRow, parseTransactionRow, parseOAuthClientRow, parseGitTokenRow, parseTurnPartType, } from "./parse-row.js";
20
+ export { resolveModelSources, resolveInferencePreferences, resolveInstanceModelSources, resolveSourcesByOfferingIds, type CatalogSourceResolution, type OfferingSourceResolution, type SourceSkip, } from "./model-source-resolution.js";
21
+ export { parseGrantRow, parseApprovalRow, parsePrincipalRow, parseSignalCorrelationRow, parseWorkflowRunRow, parseWorkflowRunDispatchRow, parseWorkflowRunLaunchSpecRow, parseWorkflowDefinitionRow, parseWorkflowDefinitionVersionRow, parseOfferingRow, parseModelOfferingRow, parseCredentialRow, parseProviderRow, parseTenantRow, parseWalletRow, parseTransactionRow, parseOAuthClientRow, parseGitTokenRow, parseTurnPartType, } from "./parse-row.js";
13
22
  export * as schema from "./schema/index.js";