graphile-bucket-provisioner-plugin 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,23 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Dan Lynch <pyramation@gmail.com>
4
+ Copyright (c) 2025 Constructive <developers@constructive.io>
5
+ Copyright (c) 2020-present, Interweb, Inc.
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,228 @@
1
+ # graphile-bucket-provisioner-plugin
2
+
3
+ <p align="center" width="100%">
4
+ <img height="250" src="https://raw.githubusercontent.com/constructive-io/constructive/refs/heads/main/assets/outline-logo.svg" />
5
+ </p>
6
+
7
+ <p align="center" width="100%">
8
+ <a href="https://github.com/constructive-io/constructive/actions/workflows/run-tests.yaml">
9
+ <img height="20" src="https://github.com/constructive-io/constructive/actions/workflows/run-tests.yaml/badge.svg" />
10
+ </a>
11
+ <a href="https://github.com/constructive-io/constructive/blob/main/LICENSE"><img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/></a>
12
+ <a href="https://www.npmjs.com/package/graphile-bucket-provisioner-plugin"><img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/constructive?filename=graphile%2Fgraphile-bucket-provisioner-plugin%2Fpackage.json"/></a>
13
+ </p>
14
+
15
+ PostGraphile v5 plugin that automatically provisions S3-compatible buckets when bucket rows are created in the database. Wraps bucket creation mutations to call [`@constructive-io/bucket-provisioner`](../packages/bucket-provisioner) after the database row is inserted.
16
+
17
+ ## Features
18
+
19
+ - **Auto-provisioning hook** — Wraps `create*` mutations on tables tagged with `@storageBuckets` to automatically provision S3 buckets after row creation
20
+ - **CORS update hook** — Wraps `update*` mutations to detect `allowed_origins` changes and re-apply CORS rules to the S3 bucket
21
+ - **3-tier CORS resolution** — Bucket-level `allowed_origins` → storage module-level `allowed_origins` → plugin config `allowedOrigins`
22
+ - **Wildcard CORS** — Set `allowed_origins = ['*']` on a bucket for fully open CDN/public deployments
23
+ - **Explicit `provisionBucket` mutation** — GraphQL mutation for manual/retry provisioning of any bucket
24
+ - **Per-database overrides** — Reads `endpoint`, `provider`, `public_url_prefix`, and `allowed_origins` from the `storage_module` table for multi-tenant setups
25
+ - **Lazy S3 config** — Connection config can be a function (evaluated once, cached) to avoid eager env-var reads at import time
26
+ - **Graceful error handling** — Provisioning and CORS update failures are logged but never fail the mutation (admin can retry via `provisionBucket`)
27
+ - **Custom bucket naming** — Supports prefix-based naming or a fully custom `resolveBucketName` function
28
+
29
+ ## Installation
30
+
31
+ ```bash
32
+ pnpm add graphile-bucket-provisioner-plugin
33
+ ```
34
+
35
+ ## Quick Start
36
+
37
+ ```typescript
38
+ import { createBucketProvisionerPlugin } from 'graphile-bucket-provisioner-plugin';
39
+
40
+ const BucketProvisionerPlugin = createBucketProvisionerPlugin({
41
+ connection: {
42
+ provider: 'minio',
43
+ region: 'us-east-1',
44
+ endpoint: 'http://minio:9000',
45
+ accessKeyId: process.env.S3_ACCESS_KEY_ID!,
46
+ secretAccessKey: process.env.S3_SECRET_ACCESS_KEY!,
47
+ },
48
+ allowedOrigins: ['https://app.example.com'],
49
+ });
50
+
51
+ // Add to your PostGraphile preset
52
+ const preset: GraphileConfig.Preset = {
53
+ plugins: [BucketProvisionerPlugin],
54
+ };
55
+ ```
56
+
57
+ Or use the convenience preset:
58
+
59
+ ```typescript
60
+ import { BucketProvisionerPreset } from 'graphile-bucket-provisioner-plugin';
61
+
62
+ const preset: GraphileConfig.Preset = {
63
+ extends: [
64
+ BucketProvisionerPreset({
65
+ connection: () => ({
66
+ provider: 'minio',
67
+ region: 'us-east-1',
68
+ endpoint: process.env.S3_ENDPOINT!,
69
+ accessKeyId: process.env.S3_ACCESS_KEY_ID!,
70
+ secretAccessKey: process.env.S3_SECRET_ACCESS_KEY!,
71
+ }),
72
+ allowedOrigins: ['https://app.example.com'],
73
+ }),
74
+ ],
75
+ };
76
+ ```
77
+
78
+ ## How It Works
79
+
80
+ ### Auto-Provisioning (default)
81
+
82
+ When a `createBucket` mutation runs on a table tagged with `@storageBuckets`:
83
+
84
+ 1. The original resolver runs first (creates the DB row via RLS)
85
+ 2. The plugin reads the bucket's `key` and `type` from the mutation input
86
+ 3. It reads the `storage_module` config for per-database endpoint/provider overrides
87
+ 4. It calls `BucketProvisioner.provision()` to create and configure the S3 bucket
88
+ 5. If provisioning fails, the error is logged but the mutation result is returned normally
89
+
90
+ ### Explicit Mutation
91
+
92
+ The plugin also adds a `provisionBucket` mutation for manual provisioning or retrying failed provisions:
93
+
94
+ ```graphql
95
+ mutation {
96
+ provisionBucket(input: { bucketKey: "public" }) {
97
+ success
98
+ bucketName
99
+ accessType
100
+ provider
101
+ endpoint
102
+ error
103
+ }
104
+ }
105
+ ```
106
+
107
+ This mutation:
108
+ 1. Reads the bucket row from the database (protected by RLS)
109
+ 2. Reads the storage module config for the current database
110
+ 3. Provisions the S3 bucket with the appropriate settings
111
+ 4. Returns a success/error payload
112
+
113
+ ## API
114
+
115
+ ### `createBucketProvisionerPlugin(options)`
116
+
117
+ Creates the plugin instance. Returns a `GraphileConfig.Plugin`.
118
+
119
+ | Option | Type | Description |
120
+ |--------|------|-------------|
121
+ | `connection` | `StorageConnectionConfig \| () => StorageConnectionConfig` | S3 connection config (static or lazy getter) |
122
+ | `allowedOrigins` | `string[]` | CORS allowed origins for bucket configuration |
123
+ | `bucketNamePrefix` | `string?` | Prefix for S3 bucket names (e.g., `"myapp"` → `"myapp-public"`) |
124
+ | `resolveBucketName` | `(bucketKey, databaseId) => string` | Custom bucket name resolver (takes precedence over prefix) |
125
+ | `versioning` | `boolean?` | Enable S3 versioning on provisioned buckets (default: `false`) |
126
+ | `autoProvision` | `boolean?` | Enable auto-provisioning hook on create mutations (default: `true`) |
127
+
128
+ ### `BucketProvisionerPreset(options)`
129
+
130
+ Convenience function that wraps the plugin in a `GraphileConfig.Preset`.
131
+
132
+ ### Connection Config
133
+
134
+ ```typescript
135
+ interface StorageConnectionConfig {
136
+ provider: 's3' | 'minio' | 'r2' | 'gcs' | 'spaces';
137
+ region: string;
138
+ endpoint?: string;
139
+ accessKeyId: string;
140
+ secretAccessKey: string;
141
+ }
142
+ ```
143
+
144
+ ### Smart Tag Detection
145
+
146
+ The plugin detects tables tagged with `@storageBuckets` (set by the storage module generator in constructive-db):
147
+
148
+ ```sql
149
+ COMMENT ON TABLE app_public.buckets IS E'@storageBuckets\nStorage buckets table';
150
+ ```
151
+
152
+ The plugin wraps `create*` mutations for auto-provisioning and `update*` mutations for CORS change detection. Delete mutations are not wrapped.
153
+
154
+ ## Error Handling
155
+
156
+ The plugin is designed to never break mutations:
157
+
158
+ - **Auto-provisioning errors** are caught and logged. The mutation result is returned normally. The admin can retry via the `provisionBucket` mutation.
159
+ - **Explicit `provisionBucket` errors** return a structured payload with `success: false` and an `error` message.
160
+ - **Validation errors** (`INVALID_BUCKET_KEY`, `DATABASE_NOT_FOUND`, `STORAGE_MODULE_NOT_PROVISIONED`, `BUCKET_NOT_FOUND`) are thrown as exceptions since they indicate configuration issues.
161
+
162
+ ## Multi-Tenant Support
163
+
164
+ The plugin reads per-database overrides from the `storage_module` table:
165
+
166
+ - `endpoint` — Override the S3 endpoint for this database
167
+ - `provider` — Override the storage provider for this database
168
+ - `public_url_prefix` — CDN/public URL prefix for public buckets
169
+
170
+ This allows different tenants to use different storage backends while sharing the same plugin configuration.
171
+
172
+ ---
173
+
174
+ ## Education and Tutorials
175
+
176
+ 1. 🚀 [Quickstart: Getting Up and Running](https://constructive.io/learn/quickstart)
177
+ Get started with modular databases in minutes. Install prerequisites and deploy your first module.
178
+
179
+ 2. 📦 [Modular PostgreSQL Development with Database Packages](https://constructive.io/learn/modular-postgres)
180
+ Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
181
+
182
+ 3. ✏️ [Authoring Database Changes](https://constructive.io/learn/authoring-database-changes)
183
+ Master the workflow for adding, organizing, and managing database changes with pgpm.
184
+
185
+ 4. 🧪 [End-to-End PostgreSQL Testing with TypeScript](https://constructive.io/learn/e2e-postgres-testing)
186
+ Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
187
+
188
+ 5. ⚡ [Supabase Testing](https://constructive.io/learn/supabase)
189
+ Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
190
+
191
+ 6. 💧 [Drizzle ORM Testing](https://constructive.io/learn/drizzle-testing)
192
+ Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
193
+
194
+ 7. 🔧 [Troubleshooting](https://constructive.io/learn/troubleshooting)
195
+ Common issues and solutions for pgpm, PostgreSQL, and testing.
196
+
197
+ ## Related Constructive Tooling
198
+
199
+ ### 📦 Package Management
200
+
201
+ * [pgpm](https://github.com/constructive-io/constructive/tree/main/pgpm/pgpm): **🖥️ PostgreSQL Package Manager** for modular Postgres development. Works with database workspaces, scaffolding, migrations, seeding, and installing database packages.
202
+
203
+ ### 🧪 Testing
204
+
205
+ * [pgsql-test](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-test): **📊 Isolated testing environments** with per-test transaction rollbacks—ideal for integration tests, complex migrations, and RLS simulation.
206
+ * [pgsql-seed](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-seed): **🌱 PostgreSQL seeding utilities** for CSV, JSON, SQL data loading, and pgpm deployment.
207
+ * [supabase-test](https://github.com/constructive-io/constructive/tree/main/postgres/supabase-test): **🧪 Supabase-native test harness** preconfigured for the local Supabase stack—per-test rollbacks, JWT/role context helpers, and CI/GitHub Actions ready.
208
+ * [graphile-test](https://github.com/constructive-io/constructive/tree/main/graphile/graphile-test): **🔐 Authentication mocking** for Graphile-focused test helpers and emulating row-level security contexts.
209
+ * [pg-query-context](https://github.com/constructive-io/constructive/tree/main/postgres/pg-query-context): **🔒 Session context injection** to add session-local context (e.g., `SET LOCAL`) into queries—ideal for setting `role`, `jwt.claims`, and other session settings.
210
+
211
+ ### 🧠 Parsing & AST
212
+
213
+ * [pgsql-parser](https://www.npmjs.com/package/pgsql-parser): **🔄 SQL conversion engine** that interprets and converts PostgreSQL syntax.
214
+ * [libpg-query-node](https://www.npmjs.com/package/libpg-query): **🌉 Node.js bindings** for `libpg_query`, converting SQL into parse trees.
215
+ * [pg-proto-parser](https://www.npmjs.com/package/pg-proto-parser): **📦 Protobuf parser** for parsing PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
216
+ * [@pgsql/enums](https://www.npmjs.com/package/@pgsql/enums): **🏷️ TypeScript enums** for PostgreSQL AST for safe and ergonomic parsing logic.
217
+ * [@pgsql/types](https://www.npmjs.com/package/@pgsql/types): **📝 Type definitions** for PostgreSQL AST nodes in TypeScript.
218
+ * [@pgsql/utils](https://www.npmjs.com/package/@pgsql/utils): **🛠️ AST utilities** for constructing and transforming PostgreSQL syntax trees.
219
+
220
+ ## Credits
221
+
222
+ **🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
223
+
224
+ ## Disclaimer
225
+
226
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
227
+
228
+ No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
package/esm/index.d.ts ADDED
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Bucket Provisioner Plugin for PostGraphile v5
3
+ *
4
+ * Provides automatic S3 bucket provisioning for PostGraphile v5.
5
+ * When bucket rows are created via GraphQL mutations, this plugin
6
+ * automatically provisions the corresponding S3 bucket with the
7
+ * correct privacy policies, CORS rules, and lifecycle settings.
8
+ *
9
+ * Also provides an explicit `provisionBucket` mutation for manual
10
+ * provisioning or re-provisioning of S3 buckets.
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * import { BucketProvisionerPreset } from 'graphile-bucket-provisioner-plugin';
15
+ * import { getEnvOptions } from '@constructive-io/graphql-env';
16
+ *
17
+ * // Use a lazy getter so env vars are read at runtime, not import time
18
+ * function getConnection() {
19
+ * const { cdn } = getEnvOptions();
20
+ * return {
21
+ * provider: cdn?.provider || 'minio',
22
+ * region: cdn?.awsRegion || 'us-east-1',
23
+ * endpoint: cdn?.endpoint || 'http://minio:9000',
24
+ * accessKeyId: cdn?.awsAccessKey!,
25
+ * secretAccessKey: cdn?.awsSecretKey!,
26
+ * };
27
+ * }
28
+ *
29
+ * const preset = {
30
+ * extends: [
31
+ * BucketProvisionerPreset({
32
+ * connection: getConnection, // pass function ref, NOT getConnection()
33
+ * allowedOrigins: ['https://app.example.com'],
34
+ * bucketNamePrefix: 'myapp',
35
+ * }),
36
+ * ],
37
+ * };
38
+ * ```
39
+ */
40
+ export { BucketProvisionerPlugin, createBucketProvisionerPlugin } from './plugin';
41
+ export { BucketProvisionerPreset } from './preset';
42
+ export type { BucketProvisionerPluginOptions, ConnectionConfigOrGetter, BucketNameResolver, ProvisionBucketInput, ProvisionBucketPayload, StorageConnectionConfig, StorageProvider, BucketAccessType, ProvisionResult, } from './types';
package/esm/index.js ADDED
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Bucket Provisioner Plugin for PostGraphile v5
3
+ *
4
+ * Provides automatic S3 bucket provisioning for PostGraphile v5.
5
+ * When bucket rows are created via GraphQL mutations, this plugin
6
+ * automatically provisions the corresponding S3 bucket with the
7
+ * correct privacy policies, CORS rules, and lifecycle settings.
8
+ *
9
+ * Also provides an explicit `provisionBucket` mutation for manual
10
+ * provisioning or re-provisioning of S3 buckets.
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * import { BucketProvisionerPreset } from 'graphile-bucket-provisioner-plugin';
15
+ * import { getEnvOptions } from '@constructive-io/graphql-env';
16
+ *
17
+ * // Use a lazy getter so env vars are read at runtime, not import time
18
+ * function getConnection() {
19
+ * const { cdn } = getEnvOptions();
20
+ * return {
21
+ * provider: cdn?.provider || 'minio',
22
+ * region: cdn?.awsRegion || 'us-east-1',
23
+ * endpoint: cdn?.endpoint || 'http://minio:9000',
24
+ * accessKeyId: cdn?.awsAccessKey!,
25
+ * secretAccessKey: cdn?.awsSecretKey!,
26
+ * };
27
+ * }
28
+ *
29
+ * const preset = {
30
+ * extends: [
31
+ * BucketProvisionerPreset({
32
+ * connection: getConnection, // pass function ref, NOT getConnection()
33
+ * allowedOrigins: ['https://app.example.com'],
34
+ * bucketNamePrefix: 'myapp',
35
+ * }),
36
+ * ],
37
+ * };
38
+ * ```
39
+ */
40
+ export { BucketProvisionerPlugin, createBucketProvisionerPlugin } from './plugin';
41
+ export { BucketProvisionerPreset } from './preset';
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Bucket Provisioner Plugin for PostGraphile v5
3
+ *
4
+ * Adds S3 bucket provisioning support to PostGraphile v5:
5
+ *
6
+ * 1. `provisionBucket` mutation — explicitly provision an S3 bucket for a
7
+ * logical bucket row in the database. Reads the bucket config via RLS,
8
+ * then calls BucketProvisioner to create and configure the S3 bucket.
9
+ *
10
+ * 2. Auto-provisioning hook — wraps `create*` mutations on tables tagged
11
+ * with `@storageBuckets` to automatically provision the S3 bucket after
12
+ * the database row is created.
13
+ *
14
+ * 3. CORS update hook — wraps `update*` mutations on `@storageBuckets` tables
15
+ * to detect changes to `allowed_origins` and re-apply CORS rules to the
16
+ * S3 bucket.
17
+ *
18
+ * CORS resolution hierarchy (most specific wins):
19
+ * 1. Bucket-level `allowed_origins` column (per-bucket override)
20
+ * 2. Storage-module-level `allowed_origins` column (per-database default)
21
+ * 3. Plugin config `allowedOrigins` (global fallback)
22
+ * Supports `['*']` for open/CDN mode (wildcard CORS).
23
+ *
24
+ * Both pathways use `@constructive-io/bucket-provisioner` for the actual
25
+ * S3 operations (bucket creation, Block Public Access, CORS, policies,
26
+ * versioning, lifecycle rules).
27
+ *
28
+ * Detection: Uses the `@storageBuckets` smart tag on the codec (table).
29
+ * The storage module generator in constructive-db sets this tag on the
30
+ * generated buckets table via a smart comment:
31
+ * COMMENT ON TABLE buckets IS E'@storageBuckets\nStorage buckets table';
32
+ */
33
+ import type { GraphileConfig } from 'graphile-config';
34
+ import type { BucketProvisionerPluginOptions } from './types';
35
+ /**
36
+ * Creates the bucket provisioner plugin.
37
+ *
38
+ * This plugin provides two provisioning pathways:
39
+ *
40
+ * 1. **Explicit `provisionBucket` mutation** — Call this mutation with a
41
+ * bucket key to provision (or re-provision) the S3 bucket. Protected
42
+ * by RLS on the buckets table.
43
+ *
44
+ * 2. **Auto-provisioning hook** — When `autoProvision` is true (default),
45
+ * wraps `create*` mutation resolvers on tables tagged with `@storageBuckets`
46
+ * to automatically provision the S3 bucket after the row is created.
47
+ *
48
+ * @param options - Plugin configuration (S3 credentials, CORS origins, naming)
49
+ */
50
+ export declare function createBucketProvisionerPlugin(options: BucketProvisionerPluginOptions): GraphileConfig.Plugin;
51
+ export declare const BucketProvisionerPlugin: typeof createBucketProvisionerPlugin;
52
+ export default BucketProvisionerPlugin;