@lepistabioinformatics/mycelium-sdk 2.0.0 → 2.1.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/README.md CHANGED
@@ -106,12 +106,138 @@ app.get("/whoami", async (request) => ({
106
106
  Same environment-gated behavior as the Express adapter (`request.profile` is
107
107
  `Profile | undefined`, with the same 403/401/500 status codes in production).
108
108
 
109
+ ## Profile signature verification (opt-in)
110
+
111
+ When the gateway is configured with `[core.profileSigning]`, it adds
112
+ `x-mycelium-profile-signature` to every request that carries
113
+ `x-mycelium-profile`: a compact JWS (`alg: EdDSA`, `kid: <key version>`) over
114
+ `{iat, ph, aud}`, where `ph` is the SHA-256 of the exact profile header and
115
+ `aud` the downstream service name. The gateway publishes its public keys as a
116
+ JWKS at `/.well-known/mycelium-profile-jwks.json`; this SDK downloads them
117
+ (Node's built-in `fetch`), caches them and verifies every signature locally.
118
+
119
+ > **Rollout order is mandatory.** Confirm the gateway in front of this service
120
+ > is already signing **before** setting `MYCELIUM_JWKS_URL` here. A service
121
+ > that verifies behind a gateway that does not sign rejects every request
122
+ > (403). To roll back, unset `MYCELIUM_JWKS_URL` here first, then disable
123
+ > signing in the gateway.
124
+
125
+ Point the SDK at the gateway JWKS before creating the middleware or
126
+ registering the plugin:
127
+
128
+ ```bash
129
+ export MYCELIUM_JWKS_URL="https://gateway.internal/.well-known/mycelium-profile-jwks.json"
130
+ export MYC_PROFILE_SIGNATURE_AUDIENCE=billing-api # required: this service's name in the gateway
131
+ export MYC_PROFILE_SIGNATURE_TOLERANCE_SECONDS=60 # optional, default 60, at most 300
132
+ # export MYCELIUM_JWKS_ALLOW_INSECURE_HTTP=true # local development only (http:// URL)
133
+ ```
134
+
135
+ `MYCELIUM_JWKS_URL` accepts either the complete endpoint (as above) or just
136
+ the gateway address, to which `/.well-known/mycelium-profile-jwks.json` is
137
+ appended: `mycelium.example.com` or `https://mycelium.example.com/prod` (a
138
+ path prefix is kept). `https://` is assumed when no scheme is given. A gateway
139
+ address must not carry a query or fragment.
140
+
141
+ The environment is read when `profileMiddleware()` /
142
+ `getProfileFromHeaderRequired()` are called or `fastifyProfilePlugin` is
143
+ registered. The verifier it configures is created once per process and shared
144
+ by every later call (one key cache, even with a middleware per route). Invalid configuration (non-`https` URL without the development
145
+ switch, URL with credentials, missing audience, invalid tolerance) throws
146
+ `ProfileSignatureConfigurationError` there, so the application does not
147
+ start. Load `.env` files before that point.
148
+
149
+ **When the keys are downloaded:** on the first signed request, in both
150
+ Express and Fastify. Requests only reach this service through the gateway, so
151
+ when one arrives the gateway (and its JWKS) is up: the service never depends
152
+ on the gateway to start, and the two can be started in any order. Until the
153
+ keys are downloaded, requests fail closed (403) and the download is retried at
154
+ most every 5 seconds.
155
+
156
+ To download the keys at startup instead (and refuse to start when the
157
+ gateway keys cannot be fetched), prepare the verifier yourself and pass it in
158
+ (`fastifyProfilePlugin` takes the same `signatureVerifier` option):
159
+
160
+ ```ts
161
+ import { prepareProfileSignatureVerifier } from "@lepistabioinformatics/mycelium-sdk"
162
+
163
+ // validates the settings and downloads the JWKS; rejects with
164
+ // ProfileJwksFetchError when the keys cannot be downloaded
165
+ const signatureVerifier = await prepareProfileSignatureVerifier()
166
+ app.use(profileMiddleware({ signatureVerifier }))
167
+ ```
168
+
169
+ With verification enabled, the Express middlewares and the Fastify plugin
170
+ verify before decoding and answer **403** `Unable to verify Mycelium profile`
171
+ on signature rejection, in every environment (the development leniency never
172
+ applies). Duplicate headers are rejected. `next()` / the route handler only
173
+ run after the signature is accepted. Unexpected internal failures return generic
174
+ 500 without invoking the handler. Without `MYCELIUM_JWKS_URL` nothing changes,
175
+ except that a signed profile logs one `console.warn` per process
176
+ (`MYCELIUM_JWKS_URL` is not set, so nothing is verified). Tolerance must be an
177
+ integer between 1 and 300 seconds (it is the replay window of a signature);
178
+ any other value is a configuration error.
179
+
180
+ Key handling follows the gateway contract (`jwks-vectors.json`):
181
+
182
+ - the set is cached for the `max-age` sent by the gateway (bounded to
183
+ 1 minute..1 day, 12 hours when absent), then refreshed;
184
+ - a signature with an unknown `kid` triggers one refetch, at most every
185
+ 30 seconds and shared by concurrent requests, so gateway key rotation needs
186
+ no change or restart here;
187
+ - if a refresh fails, the last valid set is kept and the failure is logged
188
+ (`console.warn`, prefixed `[mycelium-sdk]`); a set that expired more than
189
+ 1 day ago is no longer trusted, so requests fail closed (403) until a
190
+ refresh succeeds;
191
+ - requests never wait for a refresh another request already started while
192
+ keys are cached;
193
+ - the fetch is bounded (5 seconds, 64 KiB, redirects never followed) and a
194
+ set with private material, another key type, a wrong key length or a
195
+ non-canonical/repeated `kid` is refused as a whole.
196
+
197
+ The JWKS URL comes only from configuration, never from a request.
198
+
199
+ ```ts
200
+ app.use(
201
+ profileMiddleware({
202
+ // optional: observe rejections (log-safe reason, never the token)
203
+ onSignatureRejected: (reason) => logger.warn({ reason }, "profile rejected"),
204
+ })
205
+ )
206
+ ```
207
+
208
+ Custom integrations can use the verifier directly. It is asynchronous: always
209
+ `await` it. `decodeAndDecompressProfileFromBase64` does **not** verify:
210
+
211
+ ```ts
212
+ import { prepareProfileSignatureVerifier } from "@lepistabioinformatics/mycelium-sdk"
213
+
214
+ const verifier = await prepareProfileSignatureVerifier() // once, at startup
215
+ if (!verifier) throw new Error("Profile verification must be configured for this service")
216
+ const profile = await verifier.verifyAndDecode(profileHeader, signatureHeader)
217
+ ```
218
+
219
+ Diagnostic callbacks may return a promise. The SDK awaits it and contains both
220
+ synchronous exceptions and promise rejections, returning generic 500 without
221
+ executing the handler. Keep application callbacks bounded.
222
+
223
+ Limits (by design): a captured valid pair can be replayed to the same service
224
+ during the tolerance window; only `x-mycelium-profile` is signed. Mount the
225
+ middleware only on routes that require a profile.
226
+
227
+ Rust wire permissions `"read"` / `"write"` are accepted and normalized to the
228
+ SDK's existing numeric `Permission.READ = 0` / `Permission.WRITE = 1` API.
229
+ The optional Rust `verboseStatus: null` is accepted without weakening enum checks.
230
+
109
231
  ## Error handling
110
232
 
111
- All SDK errors extend `MyceliumError` (`message`, `code`, `expTrue`):
233
+ All SDK errors extend `MyceliumError` (`message`, `code`, `expTrue`), except
234
+ `ProfileJwksFetchError` (a plain `Error`, raised when the gateway JWKS cannot be
235
+ downloaded):
112
236
 
113
237
  | Error | Code | Thrown by |
114
238
  |---|---|---|
239
+ | `ProfileSignatureError` | `MYC_PROFILE_SIGNATURE_INVALID` | `verifyProfileSignature` / `verifyAndDecodeProfile` (carries a log-safe `reason`) |
240
+ | `ProfileSignatureConfigurationError` | `MYC_PROFILE_SIGNATURE_CONFIG_INVALID` | Invalid `MYCELIUM_JWKS_*` / `MYC_PROFILE_SIGNATURE_*` setting, or an unsafe JWKS |
115
241
  | `ProfileDecodingError` | `MYC00020` | `decodeAndDecompressProfileFromBase64` on any decode/validation failure |
116
242
  | `InsufficientLicensesError` | `MYC00019` | `getRelatedAccountOrError()` when licensed resources are present but empty |
117
243
  | `InsufficientPrivilegesError` | `MYC00019` | Any fluent method that requires a privilege the profile lacks (carries `filteringState` for debugging) |