| 1 | --- |
| 2 | title: Protect and process uploads |
| 3 | description: Verify JWTs, sign private uploads, and record real bucket events in Postgres. |
| 4 | --- |
| 5 | |
| 6 | The complete Effect implementation is `src/Api.ts`. Its class props resolve the shared resources and set `main: import.meta.url`; its initialization Effect builds clients without opening database pools. The Function bridge supplies a fresh request scope when handling HTTP or a bucket event. |
| 7 | |
| 8 | ## Bind the database |
| 9 | |
| 10 | ```diff lang="typescript" |
| 11 | +const db = yield* Neon.Connect(branch); |
| 12 | ``` |
| 13 | |
| 14 | The callable `Binding.Service` returns lazy, redacted connection accessors and uses the Function's same-branch injected database configuration. |
| 15 | |
| 16 | ## Create the SQL client |
| 17 | |
| 18 | ```diff lang="typescript" |
| 19 | +const sql = yield* SQL.Postgres({ url: db.connectionString }); |
| 20 | ``` |
| 21 | |
| 22 | The client opens its pool lazily in the current request scope, rather than acquiring a disposable connection during Function initialization. |
| 23 | |
| 24 | ## Bind the bucket |
| 25 | |
| 26 | ```diff lang="typescript" |
| 27 | +const files = yield* Neon.ReadWriteBucket(uploads); |
| 28 | ``` |
| 29 | |
| 30 | This client can inspect uploaded metadata and generate signed PUT and GET URLs without receiving the deployment account's API key. |
| 31 | |
| 32 | ## Compose the implementation layers |
| 33 | |
| 34 | ```diff lang="typescript" |
| 35 | +}).pipe(Effect.provide(Layer.mergeAll( |
| 36 | + Neon.ConnectHttp, |
| 37 | + Neon.ReadWriteBucketHttp, |
| 38 | + Neon.BucketEventSourceHttp, |
| 39 | +))), |
| 40 | ``` |
| 41 | |
| 42 | The Function initialization pipeline supplies all binding implementations in one `Effect.provide`; do not chain separate provider calls. |
| 43 | |
| 44 | ## Verify the caller |
| 45 | |
| 46 | ```diff lang="typescript" |
| 47 | +const verify = yield* authenticate; |
| 48 | +const owner = yield* Effect.tryPromise(() => verify(request.headers.get("authorization"))); |
| 49 | +if (!owner) return yield* respond({ error: "Sign in again: your token is missing, invalid, or expired." }, 401); |
| 50 | ``` |
| 51 | |
| 52 | The shared `makeAuthenticate` helper uses `jose` to verify EdDSA signatures against managed Auth's JWKS, the issuer and audience derived from its base URL, required subject and expiry claims, and a 15-minute maximum token age. A Neon Function URL is public; neither obscuring the URL nor requesting `functions:invoke` replaces this check. |
| 53 | |
| 54 | ## Scope the journal to its owner |
| 55 | |
| 56 | ```diff lang="typescript" |
| 57 | +const rows = yield* sql<UploadRecord>` |
| 58 | + SELECT id, filename, object_key, content_type, expected_bytes, actual_bytes, status, created_at |
| 59 | + FROM uploads WHERE owner_id = ${owner} ORDER BY created_at DESC LIMIT 100 |
| 60 | +`; |
| 61 | ``` |
| 62 | |
| 63 | Every read filters by the verified JWT subject; the API does not accept an owner ID from the request body. `UploadRecord` in `src/policy.ts` describes the native driver's database values. |
| 64 | |
| 65 | ## Encode the journal response |
| 66 | |
| 67 | ```diff lang="typescript" |
| 68 | +return yield* respond(yield* Effect.sync(() => rows.map(serializeUploadRow))); |
| 69 | ``` |
| 70 | |
| 71 | The shared `serializeUploadRow` helper converts Postgres `bigint` byte counts to strings without losing precision and epoch-millisecond timestamps to ISO strings. Returning database rows directly fails once the journal contains a `bigint`, because JSON cannot encode it. |
| 72 | |
| 73 | ## Validate a proposed upload |
| 74 | |
| 75 | ```diff lang="typescript" |
| 76 | +const input = parseUpload(json); |
| 77 | +if (!input) return yield* respond({ error: "Choose a nonempty file up to 10 MiB with a valid content type." }, 400); |
| 78 | ``` |
| 79 | |
| 80 | The shared pure validator checks filename, MIME type, and integer size before a row or a signed upload URL is created. |
| 81 | |
| 82 | ## Generate the object identity |
| 83 | |
| 84 | ```diff lang="typescript" |
| 85 | +const id = yield* Effect.sync(() => crypto.randomUUID()); |
| 86 | +const key = objectKey(owner, id); |
| 87 | ``` |
| 88 | |
| 89 | Application uploads receive random UUIDs under an encoded owner prefix; user-supplied filenames never become storage paths. These are runtime data IDs, not nondeterministic infrastructure names. |
| 90 | |
| 91 | ## Sign the upload |
| 92 | |
| 93 | ```diff lang="typescript" |
| 94 | +const url = yield* files.presignPut(key, { contentType: input.contentType, expiresIn: 120 }); |
| 95 | ``` |
| 96 | |
| 97 | The browser must PUT with that exact content type before the two-minute expiry. Do not log signed URLs or store them as permanent file addresses. |
| 98 | |
| 99 | ## Persist the pending record |
| 100 | |
| 101 | ```diff lang="typescript" |
| 102 | +yield* sql` |
| 103 | + INSERT INTO uploads (id, owner_id, object_key, filename, content_type, expected_bytes) |
| 104 | + VALUES (${id}, ${owner}, ${key}, ${input.filename}, ${input.contentType}, ${input.size}) |
| 105 | +`; |
| 106 | ``` |
| 107 | |
| 108 | The API commits the record before returning the signed URL, so the browser cannot upload before the event processor has a row to update. |
| 109 | |
| 110 | ## Subscribe to actual uploads |
| 111 | |
| 112 | ```diff lang="typescript" |
| 113 | +yield* Neon.BucketEventSource(uploads, { |
| 114 | + name: "ProcessUploads", |
| 115 | + prefix: "incoming/", |
| 116 | +}, processUpload); |
| 117 | ``` |
| 118 | |
| 119 | The binding provisions a storage-object-created trigger and dispatches Neon's attested HTTP event to `processUpload`. This is not a browser callback, a fabricated event, or an undocumented queue guarantee. |
| 120 | |
| 121 | ## Inspect stored metadata |
| 122 | |
| 123 | ```diff lang="typescript" |
| 124 | +const object = yield* files.head(event.objectKey); |
| 125 | +if (!object) return yield* Effect.fail(new Error("Uploaded object is not readable yet")); |
| 126 | +const bytes = object.ContentLength ?? 0; |
| 127 | ``` |
| 128 | |
| 129 | Inside `processUpload`, read the actual object before accepting its declared size and content type. A failed inspection remains a failed event invocation rather than a false success. |
| 130 | |
| 131 | ## Commit the processing result |
| 132 | |
| 133 | ```diff lang="typescript" |
| 134 | +yield* sql` |
| 135 | + WITH delivery AS ( |
| 136 | + INSERT INTO upload_events (invocation_id, object_key) |
| 137 | + VALUES (${event.invocationId}, ${event.objectKey}) |
| 138 | + ON CONFLICT DO NOTHING RETURNING invocation_id |
| 139 | + ) |
| 140 | + UPDATE uploads SET actual_bytes = ${bytes}, processed_at = now(), |
| 141 | + status = CASE WHEN expected_bytes = ${bytes} AND content_type = ${object.ContentType ?? ""} |
| 142 | + THEN 'ready' ELSE 'rejected' END |
| 143 | + WHERE object_key = ${event.objectKey} AND EXISTS (SELECT 1 FROM delivery) |
| 144 | +`; |
| 145 | ``` |
| 146 | |
| 147 | This single atomic statement deduplicates the delivery and records `ready` or `rejected`; replaying the same invocation cannot apply the database transition twice. |
| 148 | |
| 149 | ## Authorize the download lookup |
| 150 | |
| 151 | ```diff lang="typescript" |
| 152 | +const [row] = yield* sql<UploadRecord>`SELECT * FROM uploads WHERE id = ${id} AND owner_id = ${owner}`; |
| 153 | ``` |
| 154 | |
| 155 | After validating the UUID, require the row's owner to match the caller. Return 404 when absent and 409 unless its status is `ready`. |
| 156 | |
| 157 | ## Sign a private download |
| 158 | |
| 159 | ```diff lang="typescript" |
| 160 | +const url = yield* files.presignGet(row.object_key, { expiresIn: 60 }); |
| 161 | ``` |
| 162 | |
| 163 | Only an authorized, processed row receives a one-minute download capability; this does not make the bucket public. |
| 164 | |
| 165 | ## Choose a native Fetch Function |
| 166 | |
| 167 | ```diff lang="typescript" |
| 168 | +const api = yield* Neon.Function("Api", { |
| 169 | + branch, |
| 170 | + main: "./src/native.ts", |
| 171 | + env: { APP_ORIGIN: appOrigin, UPLOAD_BUCKET: uploads.bucketName, AUTH_URL: auth.baseUrl, AUTH_JWKS_URL: auth.jwksUrl }, |
| 172 | +}); |
| 173 | ``` |
| 174 | |
| 175 | The alternative in `alchemy.native.ts` uses ordinary `@neondatabase/serverless`, AWS S3 SDK clients, and `jose` in an asynchronous Fetch handler. Neon supplies the same-branch database and storage variables; only resource names and public Auth configuration are passed explicitly. |
| 176 | |
| 177 | ## Wire the native upload route |
| 178 | |
| 179 | ```diff lang="typescript" |
| 180 | +yield* Neon.FunctionTrigger("ProcessUploads", { |
| 181 | + function: api, |
| 182 | + name: "ProcessUploads", |
| 183 | + type: "storage_object_created", |
| 184 | + storageObjectCreated: { bucket: uploads, prefix: "incoming/" }, |
| 185 | + path: "/jobs/upload", |
| 186 | +}); |
| 187 | ``` |
| 188 | |
| 189 | The native `/jobs/upload` route validates the version, discriminator, bucket, prefix, trigger name, and invocation header before processing. Trusting `X-Neon-*` depends on Neon's edge stripping caller-supplied headers; it is not authentication for a generic local HTTP server. |
| 190 | |
| 191 | Continue with the [browser frontend](/neon/tutorial/frontend/). |