@venizia/ignis 0.4.8-3 → 0.4.8-5

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 (49) hide show
  1. package/dist/esm/base/middlewares/request-spy/request-spy.middleware.d.ts +1 -0
  2. package/dist/esm/base/middlewares/request-spy/request-spy.middleware.js +9 -2
  3. package/dist/esm/base/middlewares/request-spy/request-spy.middleware.js.map +1 -1
  4. package/dist/esm/components/auth/authenticate/component.js +37 -1
  5. package/dist/esm/components/auth/authenticate/component.js.map +1 -1
  6. package/dist/esm/components/auth/authenticate/services/bearer/abstract.service.d.ts +56 -5
  7. package/dist/esm/components/auth/authenticate/services/bearer/abstract.service.js +115 -11
  8. package/dist/esm/components/auth/authenticate/services/bearer/abstract.service.js.map +1 -1
  9. package/dist/esm/components/auth/authenticate/services/bearer/jwks/issuer.service.js +2 -2
  10. package/dist/esm/components/auth/authenticate/services/bearer/jwks/issuer.service.js.map +1 -1
  11. package/dist/esm/components/auth/authenticate/services/bearer/jwks/verifier.service.js +10 -3
  12. package/dist/esm/components/auth/authenticate/services/bearer/jwks/verifier.service.js.map +1 -1
  13. package/dist/esm/components/auth/authenticate/services/bearer/jws.service.d.ts +11 -0
  14. package/dist/esm/components/auth/authenticate/services/bearer/jws.service.js +25 -3
  15. package/dist/esm/components/auth/authenticate/services/bearer/jws.service.js.map +1 -1
  16. package/dist/esm/components/auth/authenticate/services/index.d.ts +1 -0
  17. package/dist/esm/components/auth/authenticate/services/index.js +1 -0
  18. package/dist/esm/components/auth/authenticate/services/index.js.map +1 -1
  19. package/dist/esm/components/auth/authenticate/services/jwks-url-policy.d.ts +31 -0
  20. package/dist/esm/components/auth/authenticate/services/jwks-url-policy.js +99 -0
  21. package/dist/esm/components/auth/authenticate/services/jwks-url-policy.js.map +1 -0
  22. package/dist/esm/components/auth/authenticate/services/service/verifier.service.js +7 -1
  23. package/dist/esm/components/auth/authenticate/services/service/verifier.service.js.map +1 -1
  24. package/dist/esm/components/auth/authenticate/strategies/service.strategy.js +2 -4
  25. package/dist/esm/components/auth/authenticate/strategies/service.strategy.js.map +1 -1
  26. package/dist/esm/components/health-check/reporter.js +2 -2
  27. package/dist/esm/components/health-check/reporter.js.map +1 -1
  28. package/dist/esm/components/static-asset/common/constants.d.ts +2 -0
  29. package/dist/esm/components/static-asset/common/constants.js +2 -0
  30. package/dist/esm/components/static-asset/common/constants.js.map +1 -1
  31. package/dist/esm/components/static-asset/common/types.d.ts +6 -0
  32. package/dist/esm/components/static-asset/common/types.js.map +1 -1
  33. package/dist/esm/components/static-asset/controller/base.definition.d.ts +2 -0
  34. package/dist/esm/components/static-asset/controller/base.definition.js +6 -4
  35. package/dist/esm/components/static-asset/controller/base.definition.js.map +1 -1
  36. package/dist/esm/components/static-asset/controller/factory.js +16 -8
  37. package/dist/esm/components/static-asset/controller/factory.js.map +1 -1
  38. package/dist/esm/components/static-asset/controller/route-options.d.ts +9 -0
  39. package/dist/esm/components/static-asset/controller/route-options.js +16 -3
  40. package/dist/esm/components/static-asset/controller/route-options.js.map +1 -1
  41. package/dist/esm/components/static-asset/ingest.d.ts +2 -2
  42. package/dist/esm/components/static-asset/ingest.js +2 -2
  43. package/dist/esm/components/static-asset/ingest.js.map +1 -1
  44. package/dist/esm/testing/assert-application-boots.d.ts +9 -0
  45. package/dist/esm/testing/assert-application-boots.js +11 -1
  46. package/dist/esm/testing/assert-application-boots.js.map +1 -1
  47. package/dist/presets/app/preset.json +3 -3
  48. package/dist/presets/lib/preset.json +2 -2
  49. package/package.json +6 -6
@@ -1 +1 @@
1
- {"version":3,"file":"verifier.service.js","sourceRoot":"","sources":["../../../../../../../src/components/auth/authenticate/services/service/verifier.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AACzC,OAAO,EACL,uBAAuB,EACvB,oBAAoB,EACpB,WAAW,EACX,gBAAgB,GACjB,MAAM,uBAAuB,CAAC;A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AG,GAAG,OAAO,CAAC,GAAG,IAAI,OAAO,CAAC,GAAG,EAAE,CAAC;QAC/C,MAAM,MAAM,GAAG,GAAG,MAAM,CAAC,WAAW,EAAE,IAAI,IAAI,EAAE,CAAC;QAEjD,IAAI,MAAM,KAAK,MAAM,EAAE,CAAC;YACtB,OAAO;QACT,CAAC;QAED,IAAI,CAAC,MAAM;aACR,GAAG,CAAC,IAAI,CAAC,oBAAoB,CAAC,IAAI,CAAC;aACnC,IAAI,CAAC,oDAAoD,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;QAE9E,MAAM,QAAQ,CAAC,EAAE,KAAK,EAAE,oBAAoB,CAAC,wBAAwB,EAAE,CAAC,CAAC;IAC3E,CAAC;CACF,CAAA;AAhLY,+BAA+B;IAQvC,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,uBAAuB,CAAC,eAAe,EAAE,CAAC,CAAA;;GARhD,+BAA+B,CAgL3C","sourcesContent":["import { inject } from '@/base/metadata';\nimport {\n AuthenticateBindingKeys,\n AuthenticationErrors,\n BaseService,\n ServiceAssertion,\n} from '@venizia/ignis-kernel';\nimport type { IServiceAssertionClaims, IServiceAuthOptions } from '@venizia/ignis-kernel';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type { createRemoteJWKSet } from 'jose';\nimport { JoseLoader } from '../jose-loader';\n\ntype TRemoteKeySet = ReturnType<typeof createRemoteJWKSet>;\n\n/**\n * Verifies an incoming service assertion against the CALLER's own JWKS.\n *\n * What the assertion covers, and nothing else: the HTTP method and the percent-encoded path. It does\n * NOT cover the query string, any header, or the body. Tenant selectors in particular are usually a\n * header or a query parameter, so an assertion alone does not authenticate which tenant a call acts\n * on - the caller allowlist and the application's own scoping have to do that. Stated because the\n * gap is invisible from the call site.\n */\nexport class ServiceAssertionVerifierService extends BaseService {\n /** One remote key set per caller, kept because `createRemoteJWKSet` owns its own cache. */\n private readonly keySets = new Map<string, TRemoteKeySet>();\n\n /** Per-caller accepted age, resolved once alongside its key set. */\n private readonly acceptMaxAges = new Map<string, number>();\n\n constructor(\n @inject({ key: AuthenticateBindingKeys.SERVICE_OPTIONS })\n private readonly options: IServiceAuthOptions,\n ) {\n super({ scope: ServiceAssertionVerifierService.name });\n }\n\n /**\n * @param path The percent-ENCODED pathname, from `new URL(context.req.url).pathname`. Never\n * `context.req.path` - Hono decodes that one, and the caller signed the encoded form.\n */\n async verify(opts: { token: string; method: string; path: string }): Promise<{ issuer: string }> {\n const { token, method, path } = opts;\n\n const jose = await JoseLoader.load();\n const issuer = this.readIssuer({ token, jose });\n const keySet = this.resolveKeySet({ issuer, jose });\n const payload = await this.runVerify({ token, issuer, keySet, jose });\n\n this.assertRequestBinding({ payload, method, path });\n\n return { issuer };\n }\n\n /**\n * Reads `iss` WITHOUT verifying, only to choose which key set checks the signature. The same value\n * is then enforced as the expected issuer, so a forged `iss` buys nothing beyond selecting the key\n * set that will reject it.\n */\n private readIssuer(opts: { token: string; jose: typeof import('jose') }): string {\n let issuer: unknown;\n\n try {\n ({ iss: issuer } = opts.jose.decodeJwt(opts.token));\n } catch (error) {\n this.logger.for(this.readIssuer.name).warn('Undecodable assertion | error: %s', error);\n throw getError({ error: AuthenticationErrors.ASSERTION_INVALID });\n }\n\n // Typed, not merely present: a numeric `iss` would index the caller map by coercion.\n if (typeof issuer !== 'string' || issuer.length === 0) {\n this.logger\n .for(this.readIssuer.name)\n .warn('Undecodable assertion | iss is missing or not a string');\n throw getError({ error: AuthenticationErrors.ASSERTION_INVALID });\n }\n\n return issuer;\n }\n\n private resolveKeySet(opts: { issuer: string; jose: typeof import('jose') }): TRemoteKeySet {\n const { issuer, jose } = opts;\n\n const cached = this.keySets.get(issuer);\n\n if (cached) {\n return cached;\n }\n\n const callers = this.options.callers ?? {};\n\n // `Object.hasOwn`, never a truthiness check on the index: the map arrives as a plain object, so\n // `iss: 'constructor'` would otherwise return `Function` - truthy - walk past this guard, and\n // reach `new URL(<function>)` as an uncaught TypeError.\n if (!Object.hasOwn(callers, issuer)) {\n this.logger\n .for(this.resolveKeySet.name)\n .warn('Caller not on the allowlist | iss: %s', issuer);\n throw getError({ error: AuthenticationErrors.CALLER_NOT_ALLOWED });\n }\n\n const entry = callers[issuer];\n const jwksUrl = typeof entry === 'string' ? entry : entry.jwksUrl;\n\n this.acceptMaxAges.set(\n issuer,\n ServiceAssertion.resolveAcceptMaxAge({\n callerOverride: typeof entry === 'string' ? undefined : entry.acceptMaxAgeSeconds,\n serviceDefault: this.options.acceptMaxAgeSeconds,\n }),\n );\n\n const keySet = jose.createRemoteJWKSet(new URL(jwksUrl), {\n cacheMaxAge:\n this.options.jwks?.cacheMaxAgeMs ?? ServiceAssertion.DEFAULT_JWKS_CACHE_MAX_AGE_MS,\n cooldownDuration: this.options.jwks?.cooldownMs ?? ServiceAssertion.DEFAULT_JWKS_COOLDOWN_MS,\n });\n\n this.keySets.set(issuer, keySet);\n\n return keySet;\n }\n\n private async runVerify(opts: {\n token: string;\n issuer: string;\n keySet: TRemoteKeySet;\n jose: typeof import('jose');\n }): Promise<IServiceAssertionClaims> {\n const { token, issuer, keySet, jose } = opts;\n\n // Resolved when the key set was, so a per-caller override is already folded in.\n const maxTokenAge =\n this.acceptMaxAges.get(issuer) ??\n ServiceAssertion.resolveAcceptMaxAge({\n serviceDefault: this.options.acceptMaxAgeSeconds,\n });\n\n const clockTolerance =\n this.options.clockToleranceSeconds ?? ServiceAssertion.DEFAULT_CLOCK_TOLERANCE_SECONDS;\n\n try {\n const { payload } = await jose.jwtVerify<IServiceAssertionClaims>(token, keySet, {\n algorithms: [ServiceAssertion.ALGORITHM],\n typ: ServiceAssertion.TYP,\n issuer,\n audience: this.options.name,\n // NOT redundant with `exp`, though it looks it. An honest caller stamps `exp = iat +\n // lifetime`, so the two are numerically tied and jose reaches `exp` first - measured.\n // `maxTokenAge` is the only bound that still holds when the CALLER is the attacker and picks\n // its own `exp`, which is precisely the case it exists for. Do not delete it as dead config.\n //\n // And it is the CALLEE's number, never one the caller may request: a caller that could ask\n // for a longer window would be choosing its own replay window, which is the whole thing this\n // is here to deny.\n //\n // TWO NUMBERS, and they answer different questions. Measured at the defaults, 60 + 5:\n // - 65s is the ACCEPTANCE window on this machine's clock. Age 64 passes, 65 does not.\n // - 70s is the REPLAY window in wall-clock time, when the caller's clock runs the full\n // tolerance fast: we accept an `iat` up to 5s in our future, then keep accepting for\n // another 64. Measured: still accepted 69s after minting.\n // The second is the one a threat model asks for. Widening `clockToleranceSeconds` widens it\n // second for second, so it is a security knob, not an operational one.\n maxTokenAge,\n clockTolerance,\n requiredClaims: ['htm', 'htu', 'jti'],\n });\n\n return payload;\n } catch (error) {\n // One code out, the reason on `cause`: a wrong audience, clock skew and a rotated key are\n // otherwise the same string to whoever is reading the log at 2am.\n const reason = (error as { cause?: unknown })?.cause ?? error;\n this.logger.for(this.runVerify.name).warn('Rejected | iss: %s | reason: %s', issuer, reason);\n\n throw getError({ error: AuthenticationErrors.ASSERTION_INVALID, cause: error });\n }\n }\n\n private assertRequestBinding(opts: {\n payload: IServiceAssertionClaims;\n method: string;\n path: string;\n }): void {\n const { payload, method, path } = opts;\n\n const signed = `${payload.htm} ${payload.htu}`;\n const actual = `${method.toUpperCase()} ${path}`;\n\n if (signed === actual) {\n return;\n }\n\n this.logger\n .for(this.assertRequestBinding.name)\n .warn('Request binding mismatch | signed: %s | actual: %s', signed, actual);\n\n throw getError({ error: AuthenticationErrors.REQUEST_BINDING_MISMATCH });\n }\n}\n"]}
1
+ {"version":3,"file":"verifier.service.js","sourceRoot":"","sources":["../../../../../../../src/components/auth/authenticate/services/service/verifier.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AACzC,OAAO,EACL,uBAAuB,EACvB,oBAAoB,EACpB,WAAW,EACX,gBAAgB,GACjB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAEvD,OAAO,EAAE,UAAU,E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CAAC;IACH,CAAC;IAEO,oBAAoB,CAAC,IAI5B;QACC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC;QAEvC,MAAM,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,IAAI,OAAO,CAAC,GAAG,EAAE,CAAC;QAC/C,MAAM,MAAM,GAAG,GAAG,MAAM,CAAC,WAAW,EAAE,IAAI,IAAI,EAAE,CAAC;QAEjD,IAAI,MAAM,KAAK,MAAM,EAAE,CAAC;YACtB,OAAO;QACT,CAAC;QAED,IAAI,CAAC,MAAM;aACR,GAAG,CAAC,IAAI,CAAC,oBAAoB,CAAC,IAAI,CAAC;aACnC,IAAI,CAAC,oDAAoD,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;QAE9E,MAAM,QAAQ,CAAC,EAAE,KAAK,EAAE,oBAAoB,CAAC,wBAAwB,EAAE,CAAC,CAAC;IAC3E,CAAC;CACF,CAAA;AAzLY,+BAA+B;IAQvC,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,uBAAuB,CAAC,eAAe,EAAE,CAAC,CAAA;;GARhD,+BAA+B,CAyL3C","sourcesContent":["import { inject } from '@/base/metadata';\nimport {\n AuthenticateBindingKeys,\n AuthenticationErrors,\n BaseService,\n ServiceAssertion,\n} from '@venizia/ignis-kernel';\nimport type { IServiceAssertionClaims, IServiceAuthOptions } from '@venizia/ignis-kernel';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type { createRemoteJWKSet } from 'jose';\nimport { JoseLoader } from '../jose-loader';\nimport { JWKSUrlPolicy } from '../jwks-url-policy';\n\ntype TRemoteKeySet = ReturnType<typeof createRemoteJWKSet>;\n\n/**\n * Verifies an incoming service assertion against the CALLER's own JWKS.\n *\n * What the assertion covers, and nothing else: the HTTP method and the percent-encoded path. It does\n * NOT cover the query string, any header, or the body. Tenant selectors in particular are usually a\n * header or a query parameter, so an assertion alone does not authenticate which tenant a call acts\n * on - the caller allowlist and the application's own scoping have to do that. Stated because the\n * gap is invisible from the call site.\n */\nexport class ServiceAssertionVerifierService extends BaseService {\n /** One remote key set per caller, kept because `createRemoteJWKSet` owns its own cache. */\n private readonly keySets = new Map<string, TRemoteKeySet>();\n\n /** Per-caller accepted age, resolved once alongside its key set. */\n private readonly acceptMaxAges = new Map<string, number>();\n\n constructor(\n @inject({ key: AuthenticateBindingKeys.SERVICE_OPTIONS })\n private readonly options: IServiceAuthOptions,\n ) {\n super({ scope: ServiceAssertionVerifierService.name });\n }\n\n /**\n * @param path The percent-ENCODED pathname, from `new URL(context.req.url).pathname`. Never\n * `context.req.path` - Hono decodes that one, and the caller signed the encoded form.\n */\n async verify(opts: { token: string; method: string; path: string }): Promise<{ issuer: string }> {\n const { token, method, path } = opts;\n\n const jose = await JoseLoader.load();\n const issuer = this.readIssuer({ token, jose });\n const keySet = this.resolveKeySet({ issuer, jose });\n const payload = await this.runVerify({ token, issuer, keySet, jose });\n\n this.assertRequestBinding({ payload, method, path });\n\n return { issuer };\n }\n\n /**\n * Reads `iss` WITHOUT verifying, only to choose which key set checks the signature. The same value\n * is then enforced as the expected issuer, so a forged `iss` buys nothing beyond selecting the key\n * set that will reject it.\n */\n private readIssuer(opts: { token: string; jose: typeof import('jose') }): string {\n let issuer: unknown;\n\n try {\n ({ iss: issuer } = opts.jose.decodeJwt(opts.token));\n } catch (error) {\n this.logger.for(this.readIssuer.name).warn('Undecodable assertion | error: %s', error);\n throw getError({ error: AuthenticationErrors.ASSERTION_INVALID });\n }\n\n // Typed, not merely present: a numeric `iss` would index the caller map by coercion.\n if (typeof issuer !== 'string' || issuer.length === 0) {\n this.logger\n .for(this.readIssuer.name)\n .warn('Undecodable assertion | iss is missing or not a string');\n throw getError({ error: AuthenticationErrors.ASSERTION_INVALID });\n }\n\n return issuer;\n }\n\n private resolveKeySet(opts: { issuer: string; jose: typeof import('jose') }): TRemoteKeySet {\n const { issuer, jose } = opts;\n\n const cached = this.keySets.get(issuer);\n\n if (cached) {\n return cached;\n }\n\n const callers = this.options.callers ?? {};\n\n // `Object.hasOwn`, never a truthiness check on the index: the map arrives as a plain object, so\n // `iss: 'constructor'` would otherwise return `Function` - truthy - walk past this guard, and\n // reach `new URL(<function>)` as an uncaught TypeError.\n if (!Object.hasOwn(callers, issuer)) {\n this.logger\n .for(this.resolveKeySet.name)\n .warn('Caller not on the allowlist | iss: %s', issuer);\n throw getError({ error: AuthenticationErrors.CALLER_NOT_ALLOWED });\n }\n\n const entry = callers[issuer];\n const jwksUrl = typeof entry === 'string' ? entry : entry.jwksUrl;\n\n this.acceptMaxAges.set(\n issuer,\n ServiceAssertion.resolveAcceptMaxAge({\n callerOverride: typeof entry === 'string' ? undefined : entry.acceptMaxAgeSeconds,\n serviceDefault: this.options.acceptMaxAgeSeconds,\n }),\n );\n\n const keySet = jose.createRemoteJWKSet(\n JWKSUrlPolicy.assertUrl({\n scope: ServiceAssertionVerifierService.name,\n label: 'the caller jwksUrl',\n url: jwksUrl,\n hosts: this.options.jwks?.hosts?.http,\n }),\n {\n cacheMaxAge:\n this.options.jwks?.cacheMaxAgeMs ?? ServiceAssertion.DEFAULT_JWKS_CACHE_MAX_AGE_MS,\n cooldownDuration:\n this.options.jwks?.cooldownMs ?? ServiceAssertion.DEFAULT_JWKS_COOLDOWN_MS,\n },\n );\n\n this.keySets.set(issuer, keySet);\n\n return keySet;\n }\n\n private async runVerify(opts: {\n token: string;\n issuer: string;\n keySet: TRemoteKeySet;\n jose: typeof import('jose');\n }): Promise<IServiceAssertionClaims> {\n const { token, issuer, keySet, jose } = opts;\n\n // Resolved when the key set was, so a per-caller override is already folded in.\n const maxTokenAge =\n this.acceptMaxAges.get(issuer) ??\n ServiceAssertion.resolveAcceptMaxAge({\n serviceDefault: this.options.acceptMaxAgeSeconds,\n });\n\n const clockTolerance =\n this.options.clockToleranceSeconds ?? ServiceAssertion.DEFAULT_CLOCK_TOLERANCE_SECONDS;\n\n try {\n const { payload } = await jose.jwtVerify<IServiceAssertionClaims>(token, keySet, {\n algorithms: [ServiceAssertion.ALGORITHM],\n typ: ServiceAssertion.TYP,\n issuer,\n audience: this.options.name,\n // NOT redundant with `exp`, though it looks it. An honest caller stamps `exp = iat +\n // lifetime`, so the two are numerically tied and jose reaches `exp` first - measured.\n // `maxTokenAge` is the only bound that still holds when the CALLER is the attacker and picks\n // its own `exp`, which is precisely the case it exists for. Do not delete it as dead config.\n //\n // And it is the CALLEE's number, never one the caller may request: a caller that could ask\n // for a longer window would be choosing its own replay window, which is the whole thing this\n // is here to deny.\n //\n // TWO NUMBERS, and they answer different questions. Measured at the defaults, 60 + 5:\n // - 65s is the ACCEPTANCE window on this machine's clock. Age 64 passes, 65 does not.\n // - 70s is the REPLAY window in wall-clock time, when the caller's clock runs the full\n // tolerance fast: we accept an `iat` up to 5s in our future, then keep accepting for\n // another 64. Measured: still accepted 69s after minting.\n // The second is the one a threat model asks for. Widening `clockToleranceSeconds` widens it\n // second for second, so it is a security knob, not an operational one.\n maxTokenAge,\n clockTolerance,\n requiredClaims: ['htm', 'htu', 'jti'],\n });\n\n return payload;\n } catch (error) {\n // One code out, the reason on `cause`: a wrong audience, clock skew and a rotated key are\n // otherwise the same string to whoever is reading the log at 2am.\n const reason = (error as { cause?: unknown })?.cause ?? error;\n this.logger.for(this.runVerify.name).warn('Rejected | iss: %s | reason: %s', issuer, reason);\n\n throw getError({ error: AuthenticationErrors.ASSERTION_INVALID, cause: error });\n }\n }\n\n private assertRequestBinding(opts: {\n payload: IServiceAssertionClaims;\n method: string;\n path: string;\n }): void {\n const { payload, method, path } = opts;\n\n const signed = `${payload.htm} ${payload.htu}`;\n const actual = `${method.toUpperCase()} ${path}`;\n\n if (signed === actual) {\n return;\n }\n\n this.logger\n .for(this.assertRequestBinding.name)\n .warn('Request binding mismatch | signed: %s | actual: %s', signed, actual);\n\n throw getError({ error: AuthenticationErrors.REQUEST_BINDING_MISMATCH });\n }\n}\n"]}
@@ -42,10 +42,8 @@ let ServiceAuthenticationStrategy = ServiceAuthenticationStrategy_1 = class Serv
42
42
  path: new URL(context.req.url).pathname,
43
43
  });
44
44
  const principal = await this.options.resolvePrincipal({ issuer, context });
45
- // Validated rather than trusted. `executeAnyMode` calls `setCurrentUser` unconditionally, so an
46
- // application returning a principal without a `userId` would authenticate the request and then
47
- // fail at the first write, far from here. `executeAllMode` already refuses it; this closes the
48
- // gap between the two modes.
45
+ // Validated rather than trusted. The provider also refuses an answer without a `userId`, but a principal an
46
+ // application resolves wrongly is reported here, at the cause, with the issuer and the strategy named.
49
47
  if (!principal?.userId) {
50
48
  this.logger
51
49
  .for(this.authenticate.name)
@@ -1 +1 @@
1
- {"version":3,"file":"service.strategy.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authenticate/strategies/service.strategy.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAEvD,OAAO,EACL,uBAAuB,EACvB,cAAc,EACd,oBAAoB,EACpB,iBAAiB,EACjB,gBAAgB,EAChB,MAAM,GACP,MAAM,uBAAuB,CAAC;AAO/B,OAAO,EAAE,+BAA+B,EAAE,MAAM,sCAAsC,CAAC;AAEvF;;;;;;GAMG;AACH,IAAa,6BAA6B,qCAA1C,MAAa,6BACX,SAAQ,UAAU;IAKlB,YAOE,QAA0D,EAE1D,OAAgD;QAEhD,KAAK,CAAC,EAAE,KAAK,EAAE,+BAA6B,CAAC,IAAI,EAAE,CAAC,CAAC;QAJpC,aAAQ,GAAR,QAAQ,CAAiC;QAEzC,YAAO,GAAP,OAAO,CAAwB;QAXlD,SAAI,GAAG,cAAc,CAAC,gBAAgB,CAAC;IAcvC,CAAC;IAED,KAAK,CAAC,YAAY,CAAC,OAA4B;QAC7C,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,gBAAgB,CAAC,MAAM,CAAC,CAAC;QAE1D,IAAI,C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jD,6BAA6B,CAmDzC","sourcesContent":["import { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport { BindingKeys } from '@venizia/ignis-inversion';\nimport type { Env } from 'hono';\nimport {\n AuthenticateBindingKeys,\n Authentication,\n AuthenticationErrors,\n BindingNamespaces,\n ServiceAssertion,\n inject,\n} from '@venizia/ignis-kernel';\nimport type {\n IAuthUser,\n IAuthenticationStrategy,\n IServiceAuthOptions,\n TContext,\n} from '@venizia/ignis-kernel';\nimport { ServiceAssertionVerifierService } from '../services/service/verifier.service';\n\n/**\n * Proves the CALLING SERVICE, from a per-request Ed25519 assertion verified against that caller's\n * own JWKS. No identity round trip and no shared password.\n *\n * It proves which service called, never which user. `resolvePrincipal` is where the application\n * turns a caller name into one of its own principals.\n */\nexport class ServiceAuthenticationStrategy<E extends Env = Env>\n extends BaseHelper\n implements IAuthenticationStrategy<E>\n{\n name = Authentication.STRATEGY_SERVICE;\n\n constructor(\n @inject({\n key: BindingKeys.build({\n namespace: BindingNamespaces.SERVICE,\n key: ServiceAssertionVerifierService.name,\n }),\n })\n private readonly verifier: ServiceAssertionVerifierService,\n @inject({ key: AuthenticateBindingKeys.SERVICE_OPTIONS })\n private readonly options: IServiceAuthOptions<E>,\n ) {\n super({ scope: ServiceAuthenticationStrategy.name });\n }\n\n async authenticate(context: TContext<E, string>): Promise<IAuthUser> {\n const token = context.req.header(ServiceAssertion.HEADER);\n\n if (!token) {\n throw getError({ error: AuthenticationErrors.ASSERTION_MISSING });\n }\n\n // The raw url, NOT `context.req.path`: Hono hands that back percent-DECODED, so a route carrying\n // a space or a non-ASCII slug would never match the encoded path the caller signed.\n const { issuer } = await this.verifier.verify({\n token,\n method: context.req.method,\n path: new URL(context.req.url).pathname,\n });\n\n const principal = await this.options.resolvePrincipal({ issuer, context });\n\n // Validated rather than trusted. `executeAnyMode` calls `setCurrentUser` unconditionally, so an\n // application returning a principal without a `userId` would authenticate the request and then\n // fail at the first write, far from here. `executeAllMode` already refuses it; this closes the\n // gap between the two modes.\n if (!principal?.userId) {\n this.logger\n .for(this.authenticate.name)\n .warn('resolvePrincipal returned no usable principal | iss: %s', issuer);\n throw getError({ error: AuthenticationErrors.PRINCIPAL_UNRESOLVED });\n }\n\n // Which service called is audit-relevant even when the principal is shared across callers.\n return { ...principal, callerService: issuer };\n }\n}\n"]}
1
+ {"version":3,"file":"service.strategy.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authenticate/strategies/service.strategy.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAEvD,OAAO,EACL,uBAAuB,EACvB,cAAc,EACd,oBAAoB,EACpB,iBAAiB,EACjB,gBAAgB,EAChB,MAAM,GACP,MAAM,uBAAuB,CAAC;AAO/B,OAAO,EAAE,+BAA+B,EAAE,MAAM,sCAAsC,CAAC;AAEvF;;;;;;GAMG;AACH,IAAa,6BAA6B,qCAA1C,MAAa,6BACX,SAAQ,UAAU;IAKlB,YAOE,QAA0D,EAE1D,OAAgD;QAEhD,KAAK,CAAC,EAAE,KAAK,EAAE,+BAA6B,CAAC,IAAI,EAAE,CAAC,CAAC;QAJpC,aAAQ,GAAR,QAAQ,CAAiC;QAEzC,YAAO,GAAP,OAAO,CAAwB;QAXlD,SAAI,GAAG,cAAc,CAAC,gBAAgB,CAAC;IAcvC,CAAC;IAED,KAAK,CAAC,YAAY,CAAC,OAA4B;QAC7C,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,gBAAgB,CAAC,MAAM,CAAC,CAAC;QAE1D,IAAI,CAAC,KAAK,EAAE,CAAC;YACX,MAAM,QAAQ,CAAC,EAAE,KAAK,EAAE,oBAAoB,CAAC,iBAAiB,EAAE,CAAC,CAAC;QACpE,CAAC;QAED,iGAAiG;QACjG,oFAAoF;QACpF,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;YAC5C,KAAK;YACL,MAAM,EAAE,OAAO,CAAC,GAAG,CAAC,MAAM;YAC1B,IAAI,EAAE,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,QAAQ;SACxC,CAAC,CAAC;QAEH,MAAM,SAAS,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,gBAAgB,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,CAAC;QAE3E,4GAA4G;QAC5G,uGAAuG;QACvG,IAAI,CAAC,SAAS,EAAE,MAAM,EAAE,CAAC;YACvB,IAAI,CAAC,MAAM;iBACR,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC;iBAC3B,IAAI,CAAC,yDAAyD,EAAE,MAAM,CAAC,CAAC;YAC3E,MAAM,QAAQ,CAAC,EAAE,KAAK,EAAE,oBAAoB,CAAC,oBAAoB,EAAE,CAAC,CAAC;QACvE,CAAC;QAED,2FAA2F;QAC3F,OAAO,EAAE,GAAG,SAAS,EAAE,aAAa,EAAE,MAAM,EAAE,CAAC;IACjD,CAAC;CACF,CAAA;AAjDY,6BAA6B;IAOrC,WAAA,MAAM,CAAC;QACN,GAAG,EAAE,WAAW,CAAC,KAAK,CAAC;YACrB,SAAS,EAAE,iBAAiB,CAAC,OAAO;YACpC,GAAG,EAAE,+BAA+B,CAAC,IAAI;SAC1C,CAAC;KACH,CAAC,CAAA;IAED,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,uBAAuB,CAAC,eAAe,EAAE,CAAC,CAAA;qCAD9B,+BAA+B;GAbjD,6BAA6B,CAiDzC","sourcesContent":["import { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport { BindingKeys } from '@venizia/ignis-inversion';\nimport type { Env } from 'hono';\nimport {\n AuthenticateBindingKeys,\n Authentication,\n AuthenticationErrors,\n BindingNamespaces,\n ServiceAssertion,\n inject,\n} from '@venizia/ignis-kernel';\nimport type {\n IAuthUser,\n IAuthenticationStrategy,\n IServiceAuthOptions,\n TContext,\n} from '@venizia/ignis-kernel';\nimport { ServiceAssertionVerifierService } from '../services/service/verifier.service';\n\n/**\n * Proves the CALLING SERVICE, from a per-request Ed25519 assertion verified against that caller's\n * own JWKS. No identity round trip and no shared password.\n *\n * It proves which service called, never which user. `resolvePrincipal` is where the application\n * turns a caller name into one of its own principals.\n */\nexport class ServiceAuthenticationStrategy<E extends Env = Env>\n extends BaseHelper\n implements IAuthenticationStrategy<E>\n{\n name = Authentication.STRATEGY_SERVICE;\n\n constructor(\n @inject({\n key: BindingKeys.build({\n namespace: BindingNamespaces.SERVICE,\n key: ServiceAssertionVerifierService.name,\n }),\n })\n private readonly verifier: ServiceAssertionVerifierService,\n @inject({ key: AuthenticateBindingKeys.SERVICE_OPTIONS })\n private readonly options: IServiceAuthOptions<E>,\n ) {\n super({ scope: ServiceAuthenticationStrategy.name });\n }\n\n async authenticate(context: TContext<E, string>): Promise<IAuthUser> {\n const token = context.req.header(ServiceAssertion.HEADER);\n\n if (!token) {\n throw getError({ error: AuthenticationErrors.ASSERTION_MISSING });\n }\n\n // The raw url, NOT `context.req.path`: Hono hands that back percent-DECODED, so a route carrying\n // a space or a non-ASCII slug would never match the encoded path the caller signed.\n const { issuer } = await this.verifier.verify({\n token,\n method: context.req.method,\n path: new URL(context.req.url).pathname,\n });\n\n const principal = await this.options.resolvePrincipal({ issuer, context });\n\n // Validated rather than trusted. The provider also refuses an answer without a `userId`, but a principal an\n // application resolves wrongly is reported here, at the cause, with the issuer and the strategy named.\n if (!principal?.userId) {\n this.logger\n .for(this.authenticate.name)\n .warn('resolvePrincipal returned no usable principal | iss: %s', issuer);\n throw getError({ error: AuthenticationErrors.PRINCIPAL_UNRESOLVED });\n }\n\n // Which service called is audit-relevant even when the principal is shared across callers.\n return { ...principal, callerService: issuer };\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { Environment } from '@venizia/ignis-helpers';
1
+ import { Environment, Hash } from '@venizia/ignis-helpers';
2
2
  import { BuildInfoRegistry } from '@venizia/ignis-helpers/core';
3
3
  /**
4
4
  * Assembles what `GET /health` and `GET /health/stats` answer.
@@ -76,7 +76,7 @@ export class HealthCheckReporter {
76
76
  if (typeof secretKey !== 'string' || secretKey.trim().length === 0) {
77
77
  return false;
78
78
  }
79
- return opts.header === secretKey;
79
+ return Hash.equals({ value: opts.header ?? '', expected: secretKey });
80
80
  }
81
81
  /** The slot is a process-wide `globalThis` entry any dependency can write, and `IBuildInfo` types it without checking - so a non-string never reaches the response schema, which declares `z.string()`. */
82
82
  static extractText(opts) {
@@ -1 +1 @@
1
- {"version":3,"file":"reporter.js","sourceRoot":"","sources":["../../../../src/components/health-check/reporter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAE,iBAAiB,EAAyB,MAAM,6BAA6B,CAAC;AAIvF;;;;;;;GAOG;AACH,MAAM,OAAO,mBAAmB;aACN,iBAAY,GAAG,IAAI,GAAG,IAAI,CAAC;IAEnD,iGAAiG;IACjG,MAAM,CAAC,YAAY;QACjB,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,EAAE,CAAC;IAC/D,CAAC;IAED;;;;;;;;;;OAUG;IACH,MAAM,CAAC,cAAc,CAAC,IAIrB;QACC,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,IAAI,EAAE,CAAC;QAE5C,IAAI,OAAO,MAAM,KAAK,SAAS,EAAE,CAAC;YAChC,OAAO,MAAM,CAAC;QAChB,CAAC;QAED,MAAM,OAAO,GAAG,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,WAAW,CAAC,OAAO,CAAC;QAE5E,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;YAC1B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';\nimport { BuildInfoRegistry, type TBuildInfoRecord } from '@venizia/ignis-helpers/core';\nimport type { IApplicationInfo } from '@venizia/ignis-kernel';\nimport type { IHealthCheckOptions } from './common';\n\n/**\n * Assembles what `GET /health` and `GET /health/stats` answer.\n *\n * Never reads the filesystem and never spawns `git`: the build stamp is PUSHED in at the\n * entrypoint through {@link BuildInfoRegistry} (or the component's own options), so a\n * `bun build --compile` binary and a Distroless image - neither of which has `node_modules`,\n * `.git` or a readable `package.json` - report exactly what a dev machine does.\n */\nexport class HealthCheckReporter {\n private static readonly BYTES_PER_MB = 1024 * 1024;\n\n /** Public liveness answer: liveness and the server clock, nothing a probe cannot already see. */\n static buildSummary(): { status: string; timestamp: string } {\n return { status: 'ok', timestamp: new Date().toISOString() };\n }\n\n /**\n * Fail-closed, copying `AppErrorMiddleware.isProduction`: the default is MEMBERSHIP in\n * `DEVELOPMENT_ENVS`, never inequality against `production`. `staging`, `uat`, `alpha` and a\n * typo all keep this route shut, because the runtime and release it names are what picks an\n * exploit. `ambient`, not `current`: an unset `NODE_ENV` is a host that cannot prove it is a dev\n * machine, and `current` would mask it as `development`.\n *\n * `enable` is compared to `true`/`false` rather than read through `??`: this binding is\n * env/config driven, and a JSON-derived `\"false\"` is truthy - an operator who wrote false would\n * otherwise get the route mounted.\n */\n static isStatsEnabled(opts: {\n options: IHealthCheckOptions;\n /** Reads the ambient environment; injected by tests so nothing has to write `process.env`. */\n environment?: () => string | undefined;\n }): boolean {\n const { enable } = opts.options.stats ?? {};\n\n if (typeof enable === 'boolean') {\n return enable;\n }\n\n const ambient = opts.environment ? opts.environment() : Environment.ambient;\n\n if (ambient === undefined) {\n return false;\n }\n\n return Environment.DEVELOPMENT_ENVS.has(ambient.toLowerCase());\n }\n\n /**\n * No `secretKey` configured leaves the route open to whatever can reach the port - stated, not\n * implied. Anything that is not a non-blank string fails CLOSED: a blank or config-derived\n * non-string key is a pipeline that lost the variable, and reading it as \"no key\" would publish\n * the route the operator meant to lock.\n *\n * The comparison is a plain `===`: a remote timing attack on a header compare is not practical\n * through an HTTP stack, and a constant-time digest compare would buy nothing here.\n */\n /**\n * Whether the stats route is mounted, unauthenticated, and on a host that cannot be shown to be a\n * development one. That combination stays LEGAL - on a cluster-internal port it is often the right\n * call - so this reports rather than refuses, and the component turns it into one warning at boot.\n *\n * It exists because `enable: true` bypasses the environment gate entirely: an operator who sets it\n * for a local run and ships the same code publishes the runtime version, the release and the\n * memory profile to whatever can reach the port. A blank `secretKey` is NOT unguarded - that fails\n * closed in {@link isStatsAuthorized}.\n */\n static isStatsUnguarded(opts: {\n options: IHealthCheckOptions;\n environment?: () => string | undefined;\n }): boolean {\n if (!HealthCheckReporter.isStatsEnabled(opts)) {\n return false;\n }\n\n if (opts.options.stats?.secretKey !== undefined) {\n return false;\n }\n\n const ambient = opts.environment ? opts.environment() : Environment.ambient;\n\n if (ambient === undefined) {\n return true;\n }\n\n return !Environment.DEVELOPMENT_ENVS.has(ambient.toLowerCase());\n }\n\n static isStatsAuthorized(opts: { options: IHealthCheckOptions; header?: string }): boolean {\n const secretKey = opts.options.stats?.secretKey;\n\n if (secretKey === undefined) {\n return true;\n }\n\n if (typeof secretKey !== 'string' || secretKey.trim().length === 0) {\n return false;\n }\n\n return opts.header === secretKey;\n }\n\n /** The slot is a process-wide `globalThis` entry any dependency can write, and `IBuildInfo` types it without checking - so a non-string never reaches the response schema, which declares `z.string()`. */\n private static extractText(opts: { value: unknown }): string | undefined {\n return typeof opts.value === 'string' && opts.value.length > 0 ? opts.value : undefined;\n }\n\n /**\n * Explicit options win over the registry, and the application's own `getAppInfo()` fills what\n * neither carries - so a host that ran no generator still reports its real name and version.\n */\n static resolveBuildInfo(opts: {\n options: IHealthCheckOptions;\n appInfo?: IApplicationInfo;\n }): TBuildInfoRecord {\n const stamp = opts.options.stats?.buildInfo ?? BuildInfoRegistry.get() ?? {};\n const extract = HealthCheckReporter.extractText;\n\n return {\n service:\n extract({ value: stamp.service }) ?? opts.appInfo?.name ?? BuildInfoRegistry.UNSPECIFIED,\n version:\n extract({ value: stamp.version }) ?? opts.appInfo?.version ?? BuildInfoRegistry.UNSPECIFIED,\n commit: extract({ value: stamp.commit }) ?? BuildInfoRegistry.UNSPECIFIED,\n branch: extract({ value: stamp.branch }) ?? BuildInfoRegistry.UNSPECIFIED,\n builtAt: extract({ value: stamp.builtAt }) ?? BuildInfoRegistry.UNSPECIFIED,\n };\n }\n\n /** `3661` -> `1h 1m 1s`: an operator reads a restart out of this faster than out of a float. */\n static toHumanUptime(opts: { seconds: number }): string {\n const total = Math.floor(opts.seconds);\n const hours = Math.floor(total / 3600);\n const minutes = Math.floor((total % 3600) / 60);\n const seconds = total % 60;\n\n return `${hours}h ${minutes}m ${seconds}s`;\n }\n\n private static toMegabytes(opts: { bytes: number }): string {\n return `${(opts.bytes / HealthCheckReporter.BYTES_PER_MB).toFixed(1)} MB`;\n }\n\n static buildStats(opts: { options: IHealthCheckOptions; appInfo?: IApplicationInfo }) {\n const memory = process.memoryUsage();\n const uptime = process.uptime();\n\n return {\n ...HealthCheckReporter.buildSummary(),\n build: HealthCheckReporter.resolveBuildInfo(opts),\n process: {\n pid: process.pid,\n uptime,\n uptimeHuman: HealthCheckReporter.toHumanUptime({ seconds: uptime }),\n runtime: `bun ${Bun.version}`,\n // `ambient`, not `current`: an unset `NODE_ENV` is reported as such, never dressed up as `development`.\n environment: Environment.ambient ?? BuildInfoRegistry.UNSPECIFIED,\n },\n memory: {\n rss: HealthCheckReporter.toMegabytes({ bytes: memory.rss }),\n heapUsed: HealthCheckReporter.toMegabytes({ bytes: memory.heapUsed }),\n heapTotal: HealthCheckReporter.toMegabytes({ bytes: memory.heapTotal }),\n },\n };\n }\n}\n"]}
1
+ {"version":3,"file":"reporter.js","sourceRoot":"","sources":["../../../../src/components/health-check/reporter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EAAE,iBAAiB,EAAyB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;YACL,GAAG,mBAAmB,CAAC,YAAY,EAAE;YACrC,KAAK,EAAE,mBAAmB,CAAC,gBAAgB,CAAC,IAAI,CAAC;YACjD,OAAO,EAAE;gBACP,GAAG,EAAE,OAAO,CAAC,GAAG;gBAChB,MAAM;gBACN,WAAW,EAAE,mBAAmB,CAAC,aAAa,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC;gBACnE,OAAO,EAAE,OAAO,GAAG,CAAC,OAAO,EAAE;gBAC7B,wGAAwG;gBACxG,WAAW,EAAE,WAAW,CAAC,OAAO,IAAI,iBAAiB,CAAC,WAAW;aAClE;YACD,MAAM,EAAE;gBACN,GAAG,EAAE,mBAAmB,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,MAAM,CAAC,GAAG,EAAE,CAAC;gBAC3D,QAAQ,EAAE,mBAAmB,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,MAAM,CAAC,QAAQ,EAAE,CAAC;gBACrE,SAAS,EAAE,mBAAmB,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,MAAM,CAAC,SAAS,EAAE,CAAC;aACxE;SACF,CAAC;IACJ,CAAC","sourcesContent":["import { Environment, Hash } from '@venizia/ignis-helpers';\nimport { BuildInfoRegistry, type TBuildInfoRecord } from '@venizia/ignis-helpers/core';\nimport type { IApplicationInfo } from '@venizia/ignis-kernel';\nimport type { IHealthCheckOptions } from './common';\n\n/**\n * Assembles what `GET /health` and `GET /health/stats` answer.\n *\n * Never reads the filesystem and never spawns `git`: the build stamp is PUSHED in at the\n * entrypoint through {@link BuildInfoRegistry} (or the component's own options), so a\n * `bun build --compile` binary and a Distroless image - neither of which has `node_modules`,\n * `.git` or a readable `package.json` - report exactly what a dev machine does.\n */\nexport class HealthCheckReporter {\n private static readonly BYTES_PER_MB = 1024 * 1024;\n\n /** Public liveness answer: liveness and the server clock, nothing a probe cannot already see. */\n static buildSummary(): { status: string; timestamp: string } {\n return { status: 'ok', timestamp: new Date().toISOString() };\n }\n\n /**\n * Fail-closed, copying `AppErrorMiddleware.isProduction`: the default is MEMBERSHIP in\n * `DEVELOPMENT_ENVS`, never inequality against `production`. `staging`, `uat`, `alpha` and a\n * typo all keep this route shut, because the runtime and release it names are what picks an\n * exploit. `ambient`, not `current`: an unset `NODE_ENV` is a host that cannot prove it is a dev\n * machine, and `current` would mask it as `development`.\n *\n * `enable` is compared to `true`/`false` rather than read through `??`: this binding is\n * env/config driven, and a JSON-derived `\"false\"` is truthy - an operator who wrote false would\n * otherwise get the route mounted.\n */\n static isStatsEnabled(opts: {\n options: IHealthCheckOptions;\n /** Reads the ambient environment; injected by tests so nothing has to write `process.env`. */\n environment?: () => string | undefined;\n }): boolean {\n const { enable } = opts.options.stats ?? {};\n\n if (typeof enable === 'boolean') {\n return enable;\n }\n\n const ambient = opts.environment ? opts.environment() : Environment.ambient;\n\n if (ambient === undefined) {\n return false;\n }\n\n return Environment.DEVELOPMENT_ENVS.has(ambient.toLowerCase());\n }\n\n /**\n * No `secretKey` configured leaves the route open to whatever can reach the port - stated, not\n * implied. Anything that is not a non-blank string fails CLOSED: a blank or config-derived\n * non-string key is a pipeline that lost the variable, and reading it as \"no key\" would publish\n * the route the operator meant to lock.\n *\n * The comparison is a plain `===`: a remote timing attack on a header compare is not practical\n * through an HTTP stack, and a constant-time digest compare would buy nothing here.\n */\n /**\n * Whether the stats route is mounted, unauthenticated, and on a host that cannot be shown to be a\n * development one. That combination stays LEGAL - on a cluster-internal port it is often the right\n * call - so this reports rather than refuses, and the component turns it into one warning at boot.\n *\n * It exists because `enable: true` bypasses the environment gate entirely: an operator who sets it\n * for a local run and ships the same code publishes the runtime version, the release and the\n * memory profile to whatever can reach the port. A blank `secretKey` is NOT unguarded - that fails\n * closed in {@link isStatsAuthorized}.\n */\n static isStatsUnguarded(opts: {\n options: IHealthCheckOptions;\n environment?: () => string | undefined;\n }): boolean {\n if (!HealthCheckReporter.isStatsEnabled(opts)) {\n return false;\n }\n\n if (opts.options.stats?.secretKey !== undefined) {\n return false;\n }\n\n const ambient = opts.environment ? opts.environment() : Environment.ambient;\n\n if (ambient === undefined) {\n return true;\n }\n\n return !Environment.DEVELOPMENT_ENVS.has(ambient.toLowerCase());\n }\n\n static isStatsAuthorized(opts: { options: IHealthCheckOptions; header?: string }): boolean {\n const secretKey = opts.options.stats?.secretKey;\n\n if (secretKey === undefined) {\n return true;\n }\n\n if (typeof secretKey !== 'string' || secretKey.trim().length === 0) {\n return false;\n }\n\n return Hash.equals({ value: opts.header ?? '', expected: secretKey });\n }\n\n /** The slot is a process-wide `globalThis` entry any dependency can write, and `IBuildInfo` types it without checking - so a non-string never reaches the response schema, which declares `z.string()`. */\n private static extractText(opts: { value: unknown }): string | undefined {\n return typeof opts.value === 'string' && opts.value.length > 0 ? opts.value : undefined;\n }\n\n /**\n * Explicit options win over the registry, and the application's own `getAppInfo()` fills what\n * neither carries - so a host that ran no generator still reports its real name and version.\n */\n static resolveBuildInfo(opts: {\n options: IHealthCheckOptions;\n appInfo?: IApplicationInfo;\n }): TBuildInfoRecord {\n const stamp = opts.options.stats?.buildInfo ?? BuildInfoRegistry.get() ?? {};\n const extract = HealthCheckReporter.extractText;\n\n return {\n service:\n extract({ value: stamp.service }) ?? opts.appInfo?.name ?? BuildInfoRegistry.UNSPECIFIED,\n version:\n extract({ value: stamp.version }) ?? opts.appInfo?.version ?? BuildInfoRegistry.UNSPECIFIED,\n commit: extract({ value: stamp.commit }) ?? BuildInfoRegistry.UNSPECIFIED,\n branch: extract({ value: stamp.branch }) ?? BuildInfoRegistry.UNSPECIFIED,\n builtAt: extract({ value: stamp.builtAt }) ?? BuildInfoRegistry.UNSPECIFIED,\n };\n }\n\n /** `3661` -> `1h 1m 1s`: an operator reads a restart out of this faster than out of a float. */\n static toHumanUptime(opts: { seconds: number }): string {\n const total = Math.floor(opts.seconds);\n const hours = Math.floor(total / 3600);\n const minutes = Math.floor((total % 3600) / 60);\n const seconds = total % 60;\n\n return `${hours}h ${minutes}m ${seconds}s`;\n }\n\n private static toMegabytes(opts: { bytes: number }): string {\n return `${(opts.bytes / HealthCheckReporter.BYTES_PER_MB).toFixed(1)} MB`;\n }\n\n static buildStats(opts: { options: IHealthCheckOptions; appInfo?: IApplicationInfo }) {\n const memory = process.memoryUsage();\n const uptime = process.uptime();\n\n return {\n ...HealthCheckReporter.buildSummary(),\n build: HealthCheckReporter.resolveBuildInfo(opts),\n process: {\n pid: process.pid,\n uptime,\n uptimeHuman: HealthCheckReporter.toHumanUptime({ seconds: uptime }),\n runtime: `bun ${Bun.version}`,\n // `ambient`, not `current`: an unset `NODE_ENV` is reported as such, never dressed up as `development`.\n environment: Environment.ambient ?? BuildInfoRegistry.UNSPECIFIED,\n },\n memory: {\n rss: HealthCheckReporter.toMegabytes({ bytes: memory.rss }),\n heapUsed: HealthCheckReporter.toMegabytes({ bytes: memory.heapUsed }),\n heapTotal: HealthCheckReporter.toMegabytes({ bytes: memory.heapTotal }),\n },\n };\n }\n}\n"]}
@@ -27,6 +27,8 @@ export declare class MetaLinkRecreateActions {
27
27
  export type TMetaLinkRecreateAction = TConstValue<typeof MetaLinkRecreateActions>;
28
28
  /** Where a signed policy may write. The final key is never inside it, so content cannot be replaced after the commit. */
29
29
  export declare const DEFAULT_PENDING_PREFIX = "pending/";
30
+ /** The most file parts one upload request may carry unless `parseMultipartBody.maxFiles` says otherwise. */
31
+ export declare const DEFAULT_MAX_UPLOAD_FILES = 20;
30
32
  /** Reported in the body, never thrown: the bytes are stored, only the row is not. A CODE, because a 200 bypasses the middleware that strips the driver's `detail`/`table`/`constraint`. */
31
33
  export declare const META_LINK_CREATE_FAILED = "META_LINK_CREATE_FAILED";
32
34
  //# sourceMappingURL=constants.d.ts.map
@@ -48,6 +48,8 @@ export class MetaLinkRecreateActions {
48
48
  }
49
49
  /** Where a signed policy may write. The final key is never inside it, so content cannot be replaced after the commit. */
50
50
  export const DEFAULT_PENDING_PREFIX = 'pending/';
51
+ /** The most file parts one upload request may carry unless `parseMultipartBody.maxFiles` says otherwise. */
52
+ export const DEFAULT_MAX_UPLOAD_FILES = 20;
51
53
  /** Reported in the body, never thrown: the bytes are stored, only the row is not. A CODE, because a 200 bypasses the middleware that strips the driver's `detail`/`table`/`constraint`. */
52
54
  export const META_LINK_CREATE_FAILED = 'META_LINK_CREATE_FAILED';
53
55
  //# sourceMappingURL=constants.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/common/constants.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AAErD,uGAAuG;AACvG,MAAM,CAAC,MAAM,iBAAiB,GAAG;IAC/B,IAAI,CAAC,OAAO,CAAC,gBAAgB;IAC7B,IAAI,CAAC,OAAO,CAAC,aAAa;IAC1B,IAAI,CAAC,OAAO,CAAC,IAAI;IACjB,IAAI,CAAC,OAAO,CAAC,aAAa;CAClB,CAAC;AAEX;;;;GAIG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,IAAI,GAAG,CAAS;IACtD,WAAW;IACX,YAAY;IACZ,WAAW;IACX,YAAY;IACZ,YAAY;IACZ,WAAW;IACX,cAAc;IACd,WAAW;IACX,YAAY;IACZ,YAAY;IACZ,WAAW;IACX,WAAW;IACX,iBAAiB;IACjB,YAAY;IACZ,UAAU;CACX,CAAC,CAAC;AAEH,yGAAyG;AACzG,MAAM,OAAO,uBAAuB;aAClB,SAAI,GAAG,MAAM,CAAC;aACd,WAAM,GAAG,QAAQ,CAAC;aAElB,eAAU,GAAG,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC;IAE/D,MAAM,CAAC,OAAO,CAAC,OAAe;QAC5B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IACtC,CAAC;;AAMH,+FAA+F;AAC/F,MAAM,OAAO,uBAAuB;aAClB,YAAO,GAAG,SAAS,CAAC;aACpB,cAAS,GAAG,WAAW,CAAC;aAExB,eAAU,GAAG,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;IAErE,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;;AAMH,yHAAyH;AACzH,MAAM,CAAC,MAAM,sBAAsB,GAAG,UAAU,CAAC;AAEjD,2LAA2L;AAC3L,MAAM,CAAC,MAAM,uBAAuB,GAAG,yBAAyB,CAAC","sourcesContent":["import type { TConstValue } from '@venizia/ignis-helpers/common';\nimport { HTTP } from '@venizia/ignis-helpers/common';\n\n/** `content-type` is absent on purpose: it is decided from the object name, never from the backend. */\nexport const WHITELIST_HEADERS = [\n HTTP.Headers.CONTENT_ENCODING,\n HTTP.Headers.CACHE_CONTROL,\n HTTP.Headers.ETAG,\n HTTP.Headers.LAST_MODIFIED,\n] as const;\n\n/**\n * Types the controller will let a browser render, keyed off the object name. Anything absent here is\n * served as an attachment, because a renderable upload on the API origin is stored XSS - and `nosniff`\n * cannot stop a type we declared ourselves. `image/svg+xml` is deliberately excluded: SVG carries script.\n */\nexport const RENDERABLE_CONTENT_TYPES = new Set<string>([\n 'image/png',\n 'image/jpeg',\n 'image/gif',\n 'image/webp',\n 'image/avif',\n 'image/bmp',\n 'image/x-icon',\n 'video/mp4',\n 'video/webm',\n 'audio/mpeg',\n 'audio/wav',\n 'audio/ogg',\n 'application/pdf',\n 'text/plain',\n 'text/csv',\n]);\n\n/** Storage backends a static asset controller can serve from. `isValid` checks a string against them. */\nexport class StaticAssetStorageTypes {\n static readonly DISK = 'disk';\n static readonly BUN_S3 = 'bun-s3';\n\n static readonly SCHEME_SET = new Set([this.DISK, this.BUN_S3]);\n\n static isValid(orgType: string): boolean {\n return this.SCHEME_SET.has(orgType);\n }\n}\n\n/** One of the `StaticAssetStorageTypes` values. */\nexport type TStaticAssetStorageType = TConstValue<typeof StaticAssetStorageTypes>;\n\n/** What `recreate-metalink` did: refreshed the rows of an object, or created its first one. */\nexport class MetaLinkRecreateActions {\n static readonly CREATED = 'created';\n static readonly REFRESHED = 'refreshed';\n\n static readonly SCHEME_SET = new Set([this.CREATED, this.REFRESHED]);\n\n static isValid(value: string): boolean {\n return this.SCHEME_SET.has(value);\n }\n}\n\n/** One of the `MetaLinkRecreateActions` values. */\nexport type TMetaLinkRecreateAction = TConstValue<typeof MetaLinkRecreateActions>;\n\n/** Where a signed policy may write. The final key is never inside it, so content cannot be replaced after the commit. */\nexport const DEFAULT_PENDING_PREFIX = 'pending/';\n\n/** Reported in the body, never thrown: the bytes are stored, only the row is not. A CODE, because a 200 bypasses the middleware that strips the driver's `detail`/`table`/`constraint`. */\nexport const META_LINK_CREATE_FAILED = 'META_LINK_CREATE_FAILED';\n"]}
1
+ {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/common/constants.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AAErD,uGAAuG;AACvG,MAAM,CAAC,MAAM,iBAAiB,GAAG;IAC/B,IAAI,CAAC,OAAO,CAAC,gBAAgB;IAC7B,IAAI,CAAC,OAAO,CAAC,aAAa;IAC1B,IAAI,CAAC,OAAO,CAAC,IAAI;IACjB,IAAI,CAAC,OAAO,CAAC,aAAa;CAClB,CAAC;AAEX;;;;GAIG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,IAAI,GAAG,CAAS;IACtD,WAAW;IACX,YAAY;IACZ,WAAW;IACX,YAAY;IACZ,YAAY;IACZ,WAAW;IACX,cAAc;IACd,WAAW;IACX,YAAY;IACZ,YAAY;IACZ,WAAW;IACX,WAAW;IACX,iBAAiB;IACjB,YAAY;IACZ,UAAU;CACX,CAAC,CAAC;AAEH,yGAAyG;AACzG,MAAM,OAAO,uBAAuB;aAClB,SAAI,GAAG,MAAM,CAAC;aACd,WAAM,GAAG,QAAQ,CAAC;aAElB,eAAU,GAAG,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC;IAE/D,MAAM,CAAC,OAAO,CAAC,OAAe;QAC5B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IACtC,CAAC;;AAMH,+FAA+F;AAC/F,MAAM,OAAO,uBAAuB;aAClB,YAAO,GAAG,SAAS,CAAC;aACpB,cAAS,GAAG,WAAW,CAAC;aAExB,eAAU,GAAG,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;IAErE,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;;AAMH,yHAAyH;AACzH,MAAM,CAAC,MAAM,sBAAsB,GAAG,UAAU,CAAC;AAEjD,4GAA4G;AAC5G,MAAM,CAAC,MAAM,wBAAwB,GAAG,EAAE,CAAC;AAE3C,2LAA2L;AAC3L,MAAM,CAAC,MAAM,uBAAuB,GAAG,yBAAyB,CAAC","sourcesContent":["import type { TConstValue } from '@venizia/ignis-helpers/common';\nimport { HTTP } from '@venizia/ignis-helpers/common';\n\n/** `content-type` is absent on purpose: it is decided from the object name, never from the backend. */\nexport const WHITELIST_HEADERS = [\n HTTP.Headers.CONTENT_ENCODING,\n HTTP.Headers.CACHE_CONTROL,\n HTTP.Headers.ETAG,\n HTTP.Headers.LAST_MODIFIED,\n] as const;\n\n/**\n * Types the controller will let a browser render, keyed off the object name. Anything absent here is\n * served as an attachment, because a renderable upload on the API origin is stored XSS - and `nosniff`\n * cannot stop a type we declared ourselves. `image/svg+xml` is deliberately excluded: SVG carries script.\n */\nexport const RENDERABLE_CONTENT_TYPES = new Set<string>([\n 'image/png',\n 'image/jpeg',\n 'image/gif',\n 'image/webp',\n 'image/avif',\n 'image/bmp',\n 'image/x-icon',\n 'video/mp4',\n 'video/webm',\n 'audio/mpeg',\n 'audio/wav',\n 'audio/ogg',\n 'application/pdf',\n 'text/plain',\n 'text/csv',\n]);\n\n/** Storage backends a static asset controller can serve from. `isValid` checks a string against them. */\nexport class StaticAssetStorageTypes {\n static readonly DISK = 'disk';\n static readonly BUN_S3 = 'bun-s3';\n\n static readonly SCHEME_SET = new Set([this.DISK, this.BUN_S3]);\n\n static isValid(orgType: string): boolean {\n return this.SCHEME_SET.has(orgType);\n }\n}\n\n/** One of the `StaticAssetStorageTypes` values. */\nexport type TStaticAssetStorageType = TConstValue<typeof StaticAssetStorageTypes>;\n\n/** What `recreate-metalink` did: refreshed the rows of an object, or created its first one. */\nexport class MetaLinkRecreateActions {\n static readonly CREATED = 'created';\n static readonly REFRESHED = 'refreshed';\n\n static readonly SCHEME_SET = new Set([this.CREATED, this.REFRESHED]);\n\n static isValid(value: string): boolean {\n return this.SCHEME_SET.has(value);\n }\n}\n\n/** One of the `MetaLinkRecreateActions` values. */\nexport type TMetaLinkRecreateAction = TConstValue<typeof MetaLinkRecreateActions>;\n\n/** Where a signed policy may write. The final key is never inside it, so content cannot be replaced after the commit. */\nexport const DEFAULT_PENDING_PREFIX = 'pending/';\n\n/** The most file parts one upload request may carry unless `parseMultipartBody.maxFiles` says otherwise. */\nexport const DEFAULT_MAX_UPLOAD_FILES = 20;\n\n/** Reported in the body, never thrown: the bytes are stored, only the row is not. A CODE, because a 200 bypasses the middleware that strips the driver's `detail`/`table`/`constraint`. */\nexport const META_LINK_CREATE_FAILED = 'META_LINK_CREATE_FAILED';\n"]}
@@ -12,6 +12,12 @@ export type TStaticAssetExtraOptions = {
12
12
  parseMultipartBody?: {
13
13
  storage?: TMultipartStorage;
14
14
  uploadDir?: string;
15
+ /**
16
+ * The most file parts one upload request may carry; more is refused with 413 before anything is written. The upload-policy request is bounded by the same number (more is a 422).
17
+ *
18
+ * @default DEFAULT_MAX_UPLOAD_FILES (20)
19
+ */
20
+ maxFiles?: number;
15
21
  };
16
22
  /** `folderPath` carries the upload query's target folder - dropping it flattens nested uploads. */
17
23
  normalizeNameFn?: (opts: {
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { BaseRestController, IAuthRouteConfig, TRouteContext } from '@/base';\nimport type { IDuration } from '@venizia/ignis-helpers/common';\nimport type {\n BaseRelationalEntity,\n DefaultCRUDRepository,\n TTableObject,\n} from '@venizia/ignis-connectors/postgres';\nimport type {\n DiskHelper,\n IBucketRef,\n IFileStat,\n IObjectLocation,\n IObjectRef,\n IStorageHelper,\n IUploadResult,\n TUploadNaming,\n} from '@venizia/ignis-helpers';\nimport type { BunS3Helper } from '@venizia/ignis-helpers/bun-s3';\nimport type { AnyType, TValueOrAsyncResolver, ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport type { TMultipartStorage } from '@venizia/ignis-helpers';\nimport type { TMetaLinkCompatibleSchema, TMetaLinkSchema } from '../models';\nimport type { StaticAssetStorageTypes } from './constants';\n\n/** Per-controller upload tuning: multipart parsing, name and link normalization, folder depth and size ceiling. */\nexport type TStaticAssetExtraOptions = {\n parseMultipartBody?: {\n storage?: TMultipartStorage;\n uploadDir?: string;\n };\n\n /** `folderPath` carries the upload query's target folder - dropping it flattens nested uploads. */\n normalizeNameFn?: (opts: { file: TUploadNaming }) => string;\n normalizeLinkFn?: (opts: IObjectLocation) => string;\n\n /**\n * Maximum folder nesting depth allowed in object paths.\n *\n * @default BaseStorageHelper.DEFAULT_MAX_FOLDER_DEPTH\n */\n maxFolderDepth?: number;\n\n /** Largest file the UPLOAD route accepts. Absent means no ceiling. Checked against `content-length` before spooling, then per file after parsing. */\n maxBytes?: number;\n [key: string]: AnyType;\n};\n\n/** Decides the key one uploaded file is stored under. `defaultKey` is what IGNIS would have written. */\nexport type TObjectNameResolver = (opts: {\n bucket: IBucketRef;\n file: TUploadNaming;\n defaultKey: string;\n}) => string;\n\n/** Adds routes of the application's own to a generated asset controller. Runs after every built-in route, so a built-in route always wins a path collision. `basePath` is the mount path with exactly one leading slash. */\n/** Adds routes of the application's own. Registration order decides a path collision, so the same shape serves both the before and the after hook. */\nexport type TDefineExtraRoutes = (opts: {\n controller: BaseRestController;\n helper: IStorageHelper;\n basePath: string;\n}) => void;\n\n// Declared by hand rather than inferred: RouteHandler inference here is heavy.\n/** Path parameters of the bucket routes. */\nexport type TBucketParams = { bucketName: string };\n/** Path parameters of the object routes. */\nexport type TObjectParams = { bucketName: string; objectName: string };\n/** Labels recorded on the MetaLink row of an uploaded object. */\nexport type TUploadQuery = {\n principalType?: string;\n principalId?: string;\n variant?: string;\n /** Display order within the principal. Caller-supplied: deriving it would be a non-atomic read of `max(sequence)` then a write of `max + 1`. */\n sequence?: number;\n folderPath?: string;\n};\n/** Query of the list objects route. Every value arrives as a string. */\nexport type TListQuery = { prefix?: string; recursive?: string; maxKeys?: string };\n\n/** Enables the signed-policy upload flow, where the client posts bytes straight to the storage and IGNIS only signs the permission and verifies the commit. */\nexport type TDirectUploadOptions = {\n /** Who may ask for a policy. REQUIRED, not defaulted: this route hands out a write credential, and there is no safe default for that. */\n authorize: (opts: { context: TRouteContext }) => ValueOrPromise<boolean>;\n\n /** Signs the commit token. Keep it out of the repository and out of the client. */\n secretKey: string;\n\n /** The ceiling the policy carries as `content-length-range`. A signed PUT cannot express this at all, which is why this is a POST policy. */\n maxBytes: number;\n\n /**\n * Where a policy may write. The final key is NEVER in a policy, so content cannot be replaced after the commit.\n *\n * @default 'pending/'\n */\n pendingPrefix?: string;\n\n /**\n * How long a policy and its commit token stay good.\n *\n * @default StoragePresignDefaults.POST_EXPIRES_IN\n */\n expiresIn?: IDuration;\n\n /** Runs BEFORE the copy to the final key, so a hook that throws leaves the object under the pending prefix for a lifecycle rule to collect, rather than stranding it at the final key. */\n onCommit?: (opts: {\n bucket: IBucketRef;\n pendingObject: IObjectRef;\n object: IObjectRef;\n }) => ValueOrPromise<void>;\n};\n\n/** Body of the upload policy route: the files the client intends to upload. */\nexport type TUploadPolicyRequest = {\n files: Array<{ fileName: string; contentType?: string; size?: number }>;\n};\n\n/** The MetaLink table belongs to the application. `Schema` defaults to the table IGNIS ships, and widens to any table whose row carries the same fields. */\nexport type TMetaLinkConfig<Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema> = {\n model: TValueOrAsyncResolver<typeof BaseRelationalEntity<Schema>>;\n repository: TValueOrAsyncResolver<DefaultCRUDRepository<Schema>>;\n createMetaLink?: (opts: {\n uploadResult: IUploadResult;\n fileStat: IFileStat;\n /** The caller's labels. Named for where they used to travel - they arrive in the request BODY now, as form fields on an upload and beside the commit token on a direct one. */\n query: TUploadQuery;\n }) => ValueOrPromise<{ count: number; data: TTableObject<Schema> }>;\n};\n\n/** The part of a built-in route an application may change. */\nexport type TStaticAssetRouteConfig = Partial<\n Omit<IAuthRouteConfig, 'method' | 'request' | 'responses'>\n> & {\n /**\n * Whether this route is registered.\n *\n * @default true\n */\n enabled?: boolean;\n};\n\n/** Per-route overrides for the built-in routes of a generated asset controller. A key left out keeps that route as built. */\nexport type TStaticAssetRoutes = {\n getBuckets?: TStaticAssetRouteConfig;\n getBucketByName?: TStaticAssetRouteConfig;\n createBucket?: TStaticAssetRouteConfig;\n deleteBucket?: TStaticAssetRouteConfig;\n\n upload?: TStaticAssetRouteConfig;\n listObjects?: TStaticAssetRouteConfig;\n deleteObject?: TStaticAssetRouteConfig;\n getObjectByName?: TStaticAssetRouteConfig;\n downloadObjectByName?: TStaticAssetRouteConfig;\n\n uploadPolicy?: TStaticAssetRouteConfig;\n uploadCommit?: TStaticAssetRouteConfig;\n\n recreateMetaLink?: TStaticAssetRouteConfig;\n};\n\n/** Static asset controllers keyed by an application-chosen name. Each entry pairs a storage type with its matching helper, and `useMetaLink: true` requires a `metaLink` config. */\nexport type TStaticAssetsComponentOptions<\n Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema,\n> = {\n [key: string]: {\n controller: {\n name: string;\n basePath: string;\n\n /**\n * Whether `/path` and `/path/` are different routes on this controller.\n *\n * @default true\n */\n isStrict?: boolean;\n\n /**\n * `true` serves a raw nested object path (`/objects/photos/2024/f.jpg`) - a URL shape change; a percent-encoded path keeps working either way.\n *\n * @default false\n */\n rawObjectPath?: boolean;\n\n /** The single bucket every object route uses. It leaves the URL (`/objects/{objectName}`) and the four bucket-management routes are not registered. The function form is read per request, so an environment variable can be read lazily. */\n bucket?: TValueOrAsyncResolver<string>;\n\n /**\n * The key scope this controller owns, e.g. `inventory/`. Every route refuses a key outside it\n * as a 404 without calling the storage, `listObjects` lists only inside it, and an upload key\n * must land inside it: the default name is placed there, a `resolveObjectName` or\n * `extra.normalizeNameFn` key outside it is refused. `maxFolderDepth` counts the folders below\n * it.\n *\n * @default every key in the bucket\n */\n keyPrefix?: string;\n\n routes?: TStaticAssetRoutes;\n\n /** Direct upload: the browser posts the bytes to the storage and IGNIS only signs the permission. Absent leaves both routes unregistered. Requires `bucket` - a policy names one bucket, and a bucket in the URL is a bucket the caller chooses. */\n directUpload?: TDirectUploadOptions;\n };\n extra?: TStaticAssetExtraOptions;\n\n /** Decides the stored object name of each uploaded file; absent keeps the storage helper's own naming. */\n resolveObjectName?: TObjectNameResolver;\n\n /** Registers the application's own routes BEFORE every built-in one, so a literal path wins over the catch-all `rawObjectPath` produces. Hono matches in registration order. */\n defineRoutesBefore?: TDefineExtraRoutes;\n\n /** Registers the application's own routes on the generated controller, after every built-in one. */\n defineExtraRoutes?: TDefineExtraRoutes;\n } & (\n | { storage: typeof StaticAssetStorageTypes.BUN_S3; helper: BunS3Helper }\n | { storage: typeof StaticAssetStorageTypes.DISK; helper: DiskHelper }\n ) &\n (\n | { useMetaLink?: false | undefined }\n | { useMetaLink: true; metaLink: TMetaLinkConfig<Schema> }\n );\n};\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { BaseRestController, IAuthRouteConfig, TRouteContext } from '@/base';\nimport type { IDuration } from '@venizia/ignis-helpers/common';\nimport type {\n BaseRelationalEntity,\n DefaultCRUDRepository,\n TTableObject,\n} from '@venizia/ignis-connectors/postgres';\nimport type {\n DiskHelper,\n IBucketRef,\n IFileStat,\n IObjectLocation,\n IObjectRef,\n IStorageHelper,\n IUploadResult,\n TUploadNaming,\n} from '@venizia/ignis-helpers';\nimport type { BunS3Helper } from '@venizia/ignis-helpers/bun-s3';\nimport type { AnyType, TValueOrAsyncResolver, ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport type { TMultipartStorage } from '@venizia/ignis-helpers';\nimport type { TMetaLinkCompatibleSchema, TMetaLinkSchema } from '../models';\nimport type { StaticAssetStorageTypes } from './constants';\n\n/** Per-controller upload tuning: multipart parsing, name and link normalization, folder depth and size ceiling. */\nexport type TStaticAssetExtraOptions = {\n parseMultipartBody?: {\n storage?: TMultipartStorage;\n uploadDir?: string;\n /**\n * The most file parts one upload request may carry; more is refused with 413 before anything is written. The upload-policy request is bounded by the same number (more is a 422).\n *\n * @default DEFAULT_MAX_UPLOAD_FILES (20)\n */\n maxFiles?: number;\n };\n\n /** `folderPath` carries the upload query's target folder - dropping it flattens nested uploads. */\n normalizeNameFn?: (opts: { file: TUploadNaming }) => string;\n normalizeLinkFn?: (opts: IObjectLocation) => string;\n\n /**\n * Maximum folder nesting depth allowed in object paths.\n *\n * @default BaseStorageHelper.DEFAULT_MAX_FOLDER_DEPTH\n */\n maxFolderDepth?: number;\n\n /** Largest file the UPLOAD route accepts. Absent means no ceiling. Checked against `content-length` before spooling, then per file after parsing. */\n maxBytes?: number;\n [key: string]: AnyType;\n};\n\n/** Decides the key one uploaded file is stored under. `defaultKey` is what IGNIS would have written. */\nexport type TObjectNameResolver = (opts: {\n bucket: IBucketRef;\n file: TUploadNaming;\n defaultKey: string;\n}) => string;\n\n/** Adds routes of the application's own to a generated asset controller. Runs after every built-in route, so a built-in route always wins a path collision. `basePath` is the mount path with exactly one leading slash. */\n/** Adds routes of the application's own. Registration order decides a path collision, so the same shape serves both the before and the after hook. */\nexport type TDefineExtraRoutes = (opts: {\n controller: BaseRestController;\n helper: IStorageHelper;\n basePath: string;\n}) => void;\n\n// Declared by hand rather than inferred: RouteHandler inference here is heavy.\n/** Path parameters of the bucket routes. */\nexport type TBucketParams = { bucketName: string };\n/** Path parameters of the object routes. */\nexport type TObjectParams = { bucketName: string; objectName: string };\n/** Labels recorded on the MetaLink row of an uploaded object. */\nexport type TUploadQuery = {\n principalType?: string;\n principalId?: string;\n variant?: string;\n /** Display order within the principal. Caller-supplied: deriving it would be a non-atomic read of `max(sequence)` then a write of `max + 1`. */\n sequence?: number;\n folderPath?: string;\n};\n/** Query of the list objects route. Every value arrives as a string. */\nexport type TListQuery = { prefix?: string; recursive?: string; maxKeys?: string };\n\n/** Enables the signed-policy upload flow, where the client posts bytes straight to the storage and IGNIS only signs the permission and verifies the commit. */\nexport type TDirectUploadOptions = {\n /** Who may ask for a policy. REQUIRED, not defaulted: this route hands out a write credential, and there is no safe default for that. */\n authorize: (opts: { context: TRouteContext }) => ValueOrPromise<boolean>;\n\n /** Signs the commit token. Keep it out of the repository and out of the client. */\n secretKey: string;\n\n /** The ceiling the policy carries as `content-length-range`. A signed PUT cannot express this at all, which is why this is a POST policy. */\n maxBytes: number;\n\n /**\n * Where a policy may write. The final key is NEVER in a policy, so content cannot be replaced after the commit.\n *\n * @default 'pending/'\n */\n pendingPrefix?: string;\n\n /**\n * How long a policy and its commit token stay good.\n *\n * @default StoragePresignDefaults.POST_EXPIRES_IN\n */\n expiresIn?: IDuration;\n\n /** Runs BEFORE the copy to the final key, so a hook that throws leaves the object under the pending prefix for a lifecycle rule to collect, rather than stranding it at the final key. */\n onCommit?: (opts: {\n bucket: IBucketRef;\n pendingObject: IObjectRef;\n object: IObjectRef;\n }) => ValueOrPromise<void>;\n};\n\n/** Body of the upload policy route: the files the client intends to upload. */\nexport type TUploadPolicyRequest = {\n files: Array<{ fileName: string; contentType?: string; size?: number }>;\n};\n\n/** The MetaLink table belongs to the application. `Schema` defaults to the table IGNIS ships, and widens to any table whose row carries the same fields. */\nexport type TMetaLinkConfig<Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema> = {\n model: TValueOrAsyncResolver<typeof BaseRelationalEntity<Schema>>;\n repository: TValueOrAsyncResolver<DefaultCRUDRepository<Schema>>;\n createMetaLink?: (opts: {\n uploadResult: IUploadResult;\n fileStat: IFileStat;\n /** The caller's labels. Named for where they used to travel - they arrive in the request BODY now, as form fields on an upload and beside the commit token on a direct one. */\n query: TUploadQuery;\n }) => ValueOrPromise<{ count: number; data: TTableObject<Schema> }>;\n};\n\n/** The part of a built-in route an application may change. */\nexport type TStaticAssetRouteConfig = Partial<\n Omit<IAuthRouteConfig, 'method' | 'request' | 'responses'>\n> & {\n /**\n * Whether this route is registered.\n *\n * @default true\n */\n enabled?: boolean;\n};\n\n/** Per-route overrides for the built-in routes of a generated asset controller. A key left out keeps that route as built. */\nexport type TStaticAssetRoutes = {\n getBuckets?: TStaticAssetRouteConfig;\n getBucketByName?: TStaticAssetRouteConfig;\n createBucket?: TStaticAssetRouteConfig;\n deleteBucket?: TStaticAssetRouteConfig;\n\n upload?: TStaticAssetRouteConfig;\n listObjects?: TStaticAssetRouteConfig;\n deleteObject?: TStaticAssetRouteConfig;\n getObjectByName?: TStaticAssetRouteConfig;\n downloadObjectByName?: TStaticAssetRouteConfig;\n\n uploadPolicy?: TStaticAssetRouteConfig;\n uploadCommit?: TStaticAssetRouteConfig;\n\n recreateMetaLink?: TStaticAssetRouteConfig;\n};\n\n/** Static asset controllers keyed by an application-chosen name. Each entry pairs a storage type with its matching helper, and `useMetaLink: true` requires a `metaLink` config. */\nexport type TStaticAssetsComponentOptions<\n Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema,\n> = {\n [key: string]: {\n controller: {\n name: string;\n basePath: string;\n\n /**\n * Whether `/path` and `/path/` are different routes on this controller.\n *\n * @default true\n */\n isStrict?: boolean;\n\n /**\n * `true` serves a raw nested object path (`/objects/photos/2024/f.jpg`) - a URL shape change; a percent-encoded path keeps working either way.\n *\n * @default false\n */\n rawObjectPath?: boolean;\n\n /** The single bucket every object route uses. It leaves the URL (`/objects/{objectName}`) and the four bucket-management routes are not registered. The function form is read per request, so an environment variable can be read lazily. */\n bucket?: TValueOrAsyncResolver<string>;\n\n /**\n * The key scope this controller owns, e.g. `inventory/`. Every route refuses a key outside it\n * as a 404 without calling the storage, `listObjects` lists only inside it, and an upload key\n * must land inside it: the default name is placed there, a `resolveObjectName` or\n * `extra.normalizeNameFn` key outside it is refused. `maxFolderDepth` counts the folders below\n * it.\n *\n * @default every key in the bucket\n */\n keyPrefix?: string;\n\n routes?: TStaticAssetRoutes;\n\n /** Direct upload: the browser posts the bytes to the storage and IGNIS only signs the permission. Absent leaves both routes unregistered. Requires `bucket` - a policy names one bucket, and a bucket in the URL is a bucket the caller chooses. */\n directUpload?: TDirectUploadOptions;\n };\n extra?: TStaticAssetExtraOptions;\n\n /** Decides the stored object name of each uploaded file; absent keeps the storage helper's own naming. */\n resolveObjectName?: TObjectNameResolver;\n\n /** Registers the application's own routes BEFORE every built-in one, so a literal path wins over the catch-all `rawObjectPath` produces. Hono matches in registration order. */\n defineRoutesBefore?: TDefineExtraRoutes;\n\n /** Registers the application's own routes on the generated controller, after every built-in one. */\n defineExtraRoutes?: TDefineExtraRoutes;\n } & (\n | { storage: typeof StaticAssetStorageTypes.BUN_S3; helper: BunS3Helper }\n | { storage: typeof StaticAssetStorageTypes.DISK; helper: DiskHelper }\n ) &\n (\n | { useMetaLink?: false | undefined }\n | { useMetaLink: true; metaLink: TMetaLinkConfig<Schema> }\n );\n};\n"]}
@@ -23,6 +23,8 @@ export declare class AssetDefinitionBuilder {
23
23
  static build(opts: {
24
24
  hasConfiguredBucket?: boolean;
25
25
  rawObjectPath?: boolean;
26
+ /** The most files one upload-policy request may name. */
27
+ maxPolicyFiles?: number;
26
28
  }): IAssetDefinitions;
27
29
  }
28
30
  //# sourceMappingURL=base.definition.d.ts.map
@@ -1,7 +1,7 @@
1
1
  import { OpenApiResponses } from '@venizia/ignis-kernel';
2
2
  import { z } from '@hono/zod-openapi';
3
3
  import { HTTP } from '@venizia/ignis-helpers/common';
4
- import { MetaLinkRecreateActions } from '../common/constants.js';
4
+ import { DEFAULT_MAX_UPLOAD_FILES, MetaLinkRecreateActions } from '../common/constants.js';
5
5
  /** The labels both upload paths take. They ride the BODY, not the URL - an identifier in a query string lands in every access log between the client and here. */
6
6
  const uploadLabels = () => ({
7
7
  principalType: z.string().optional(),
@@ -59,7 +59,7 @@ const fileStreamResponses = () => ({
59
59
  */
60
60
  export class AssetDefinitionBuilder {
61
61
  static build(opts) {
62
- const { hasConfiguredBucket = false, rawObjectPath = false } = opts;
62
+ const { hasConfiguredBucket = false, rawObjectPath = false, maxPolicyFiles = DEFAULT_MAX_UPLOAD_FILES, } = opts;
63
63
  const bucketPrefix = hasConfiguredBucket ? '' : '/buckets/{bucketName}';
64
64
  // `{objectName}` is ONE segment: a folder path travels percent-encoded (`photos%2F2024%2Ff.jpg`).
65
65
  // The catch-all also matches a RAW nested path; the encoded form keeps working either way.
@@ -144,11 +144,13 @@ export class AssetDefinitionBuilder {
144
144
  content: {
145
145
  'application/json': {
146
146
  schema: z.object({
147
- files: z.array(z.object({
147
+ files: z
148
+ .array(z.object({
148
149
  fileName: z.string().min(1),
149
150
  contentType: z.string().optional(),
150
151
  size: z.number().int().nonnegative().optional(),
151
- })),
152
+ }))
153
+ .max(maxPolicyFiles),
152
154
  }),
153
155
  },
154
156
  },
@@ -1 +1 @@
1
- {"version":3,"file":"base.definition.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/controller/base.definition.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,CAAC,EAAE,MAAM,mBAAmB,CAAC;A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ig } from '@/base';\nimport { OpenApiResponses } from '@venizia/ignis-kernel';\nimport { z } from '@hono/zod-openapi';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport { MetaLinkRecreateActions } from '../common/constants';\n\ntype TRouteRequest = NonNullable<IAuthRouteConfig['request']>;\n\n/** The labels both upload paths take. They ride the BODY, not the URL - an identifier in a query string lands in every access log between the client and here. */\nconst uploadLabels = () => ({\n principalType: z.string().optional(),\n principalId: z.string().or(z.number()).optional(),\n variant: z.string().optional(),\n sequence: z.coerce.number().int().optional(),\n});\n\nconst MultipartBodySchema = z.object({\n files: z.union([z.instanceof(File), z.array(z.instanceof(File))]).openapi({\n type: 'array',\n items: {\n type: 'string',\n format: 'binary',\n },\n }),\n ...uploadLabels(),\n folderPath: z.string().optional().openapi({\n description: 'Target folder path for uploaded files (e.g., \"photos/2024\")',\n example: 'photos/2024',\n }),\n});\n\nconst bucketNameParam = () =>\n z.string().openapi({\n param: {\n name: 'bucketName',\n in: 'path',\n },\n example: 'images',\n });\n\nconst objectNameParam = () =>\n z.string().openapi({\n param: {\n name: 'objectName',\n in: 'path',\n description: 'Object name or path (e.g., \"photo.jpg\" or \"photos/2024/photo.jpg\")',\n },\n example: 'photos/2024/photo.jpg',\n });\n\nconst fileStreamResponses = (): IAuthRouteConfig['responses'] => ({\n [HTTP.ResultCodes.RS_2.Ok]: {\n description: 'File stream response',\n content: {\n 'application/octet-stream': {\n schema: {\n type: 'string',\n format: 'binary',\n },\n },\n },\n },\n ...OpenApiResponses.errorResponses(),\n});\n\n/** The ten built-in asset routes. Only `path` and `request.params` differ between option combinations. */\nexport interface IAssetDefinitions {\n GET_BUCKETS: IAuthRouteConfig;\n GET_BUCKET_BY_NAME: IAuthRouteConfig;\n CREATE_BUCKET: IAuthRouteConfig;\n DELETE_BUCKET: IAuthRouteConfig;\n GET_OBJECT_BY_NAME: IAuthRouteConfig;\n DOWNLOAD_OBJECT_BY_NAME: IAuthRouteConfig;\n UPLOAD_POLICY: IAuthRouteConfig;\n UPLOAD_COMMIT: IAuthRouteConfig;\n UPLOAD: IAuthRouteConfig;\n DELETE_OBJECT: IAuthRouteConfig;\n LIST_OBJECTS: IAuthRouteConfig;\n RECREATE_METALINK: IAuthRouteConfig;\n}\n\n/**\n * Builds the route configs of one asset controller.\n * `hasConfiguredBucket` drops `/buckets/{bucketName}` and its param from every object route.\n * `rawObjectPath` appends the `{.+}` catch-all, the spelling `@hono/zod-openapi` translates.\n */\nexport class AssetDefinitionBuilder {\n static build(opts: {\n hasConfiguredBucket?: boolean;\n rawObjectPath?: boolean;\n }): IAssetDefinitions {\n const { hasConfiguredBucket = false, rawObjectPath = false } = opts;\n\n const bucketPrefix = hasConfiguredBucket ? '' : '/buckets/{bucketName}';\n\n // `{objectName}` is ONE segment: a folder path travels percent-encoded (`photos%2F2024%2Ff.jpg`).\n // The catch-all also matches a RAW nested path; the encoded form keeps working either way.\n const objectSegment = rawObjectPath ? '{objectName}{.+}' : '{objectName}';\n\n // A configured bucket is never in the URL, so a route whose only param was `bucketName` carries none.\n const bucketRequest = (): Pick<TRouteRequest, 'params'> =>\n hasConfiguredBucket ? {} : { params: z.object({ bucketName: bucketNameParam() }) };\n\n const objectRequest = (): TRouteRequest => ({\n params: hasConfiguredBucket\n ? z.object({ objectName: objectNameParam() })\n : z.object({ bucketName: bucketNameParam(), objectName: objectNameParam() }),\n });\n\n return {\n GET_BUCKETS: {\n method: 'get',\n path: '/buckets',\n responses: OpenApiResponses.jsonResponse({\n schema: z.array(\n z.object({\n name: z.string(),\n creationDate: z.iso.datetime(),\n }),\n ),\n }),\n },\n GET_BUCKET_BY_NAME: {\n method: 'get',\n path: bucketPrefix,\n request: {\n params: z.object({ bucketName: bucketNameParam() }),\n },\n responses: OpenApiResponses.jsonResponse({\n schema: z\n .object({\n name: z.string(),\n creationDate: z.iso.datetime(),\n })\n .nullable(),\n }),\n },\n CREATE_BUCKET: {\n method: 'post',\n path: bucketPrefix,\n request: {\n params: z.object({ bucketName: bucketNameParam() }),\n },\n responses: OpenApiResponses.jsonResponse({\n schema: z\n .object({\n name: z.string(),\n creationDate: z.iso.datetime(),\n })\n .nullable(),\n }),\n },\n DELETE_BUCKET: {\n method: 'delete',\n path: bucketPrefix,\n request: {\n params: z.object({ bucketName: bucketNameParam() }),\n },\n responses: OpenApiResponses.jsonResponse({\n schema: z.object({\n isDeleted: z.boolean(),\n }),\n }),\n },\n GET_OBJECT_BY_NAME: {\n method: 'get',\n path: `${bucketPrefix}/objects/${objectSegment}`,\n request: objectRequest(),\n responses: fileStreamResponses(),\n },\n DOWNLOAD_OBJECT_BY_NAME: {\n method: 'get',\n path: `${bucketPrefix}/download/${objectSegment}`,\n request: objectRequest(),\n responses: fileStreamResponses(),\n },\n UPLOAD_POLICY: {\n method: 'post',\n path: `${bucketPrefix}/upload-policy`,\n request: {\n body: {\n content: {\n 'application/json': {\n schema: z.object({\n files: z.array(\n z.object({\n fileName: z.string().min(1),\n contentType: z.string().optional(),\n size: z.number().int().nonnegative().optional(),\n }),\n ),\n }),\n },\n },\n },\n },\n responses: OpenApiResponses.jsonResponse({\n schema: z.array(\n z.object({\n postURL: z.string(),\n formData: z.record(z.string(), z.string()),\n objectName: z.string(),\n commitToken: z.string(),\n expiresAt: z.string(),\n }),\n ),\n description: 'One signed POST policy per file, plus the token its commit is claimed with',\n }),\n },\n UPLOAD_COMMIT: {\n method: 'post',\n path: `${bucketPrefix}/upload-commit`,\n request: {\n body: {\n content: {\n 'application/json': {\n // The labels sit beside the token, not inside it: the token is an HMAC over\n // { bucket, key, expiresAt } and deliberately carries no business fields.\n schema: z.object({ commitToken: z.string().min(1), ...uploadLabels() }),\n },\n },\n },\n },\n responses: OpenApiResponses.jsonResponse({\n schema: z.object({\n bucket: z.object({ name: z.string() }),\n object: z.object({ key: z.string() }),\n link: z.string(),\n metaLink: z\n .union([z.object({ data: z.any() }), z.object({ error: z.string() })])\n .optional(),\n }),\n description: 'The object at its final key, copied out of the pending prefix',\n }),\n },\n UPLOAD: {\n method: 'post',\n path: `${bucketPrefix}/objects`,\n request: {\n ...bucketRequest(),\n body: {\n content: {\n 'multipart/form-data': {\n schema: MultipartBodySchema,\n },\n },\n },\n },\n responses: OpenApiResponses.jsonResponse({\n schema: z.array(\n z.object({\n bucket: z.object({ name: z.string() }),\n object: z.object({\n key: z.string(),\n size: z.number(),\n contentType: z.string(),\n }),\n link: z.string(),\n metaLink: z\n .union([z.object({ data: z.any() }), z.object({ error: z.string() })])\n .optional(),\n }),\n ),\n }),\n },\n DELETE_OBJECT: {\n method: 'delete',\n path: `${bucketPrefix}/objects/${objectSegment}`,\n request: objectRequest(),\n responses: OpenApiResponses.jsonResponse({\n schema: z.object({\n success: z.boolean(),\n }),\n }),\n },\n LIST_OBJECTS: {\n method: 'get',\n path: `${bucketPrefix}/objects`,\n request: {\n ...bucketRequest(),\n query: z.object({\n prefix: z\n .string()\n .optional()\n .openapi({\n param: {\n name: 'prefix',\n in: 'query',\n description: 'Filter objects by prefix',\n },\n example: 'folder/',\n }),\n recursive: z\n .string()\n .optional()\n .openapi({\n param: {\n name: 'recursive',\n in: 'query',\n description: 'Recursive listing',\n },\n example: 'true',\n }),\n maxKeys: z\n .string()\n .optional()\n .openapi({\n param: {\n name: 'maxKeys',\n in: 'query',\n description: 'Maximum number of objects to return',\n },\n example: '100',\n }),\n }),\n },\n responses: OpenApiResponses.jsonResponse({\n schema: z.array(\n z.object({\n name: z.string().optional(),\n size: z.number().optional(),\n lastModified: z.iso.datetime().optional(),\n etag: z.string().optional(),\n prefix: z.string().optional(),\n }),\n ),\n }),\n },\n RECREATE_METALINK: {\n method: 'put',\n path: `${bucketPrefix}/meta-links/${objectSegment}`,\n request: objectRequest(),\n responses: OpenApiResponses.jsonResponse({\n schema: z.object({\n success: z.boolean(),\n action: z\n .enum([MetaLinkRecreateActions.REFRESHED, MetaLinkRecreateActions.CREATED])\n .openapi({\n description:\n '`refreshed` when rows for the object existed, `created` when none did',\n example: 'refreshed',\n }),\n count: z.number().openapi({ description: 'Rows refreshed or created' }),\n metaLink: z.any().optional().openapi({ description: 'The first of `metaLinks`' }),\n metaLinks: z.array(z.any()),\n }),\n }),\n },\n };\n }\n}\n"]}
1
+ {"version":3,"file":"base.definition.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/controller/base.definition.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,CAAC,EAAE,MAAM,mBAAmB,CAAC;AACtC,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,wBAAwB,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAIxF,kKAAkK;AAClK,MAAM,YAAY,GAAG,GAAG,EAAE,CAAC,CAAC;IAC1B,aAAa,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IACpC,WAAW,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,QAAQ,EAAE;IACjD,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC9B,QAAQ,EAAE,CAAC,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE;CAC7C,CAAC,CAAC;AAEH,MAAM,mBAAmB,GAAG,CAAC,CAAC,MAAM,CAAC;IACnC,KAAK,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;QACxE,IAAI,EAAE,OAAO;QACb,KAAK,EAAE;YACL,IAAI,EAAE,QAAQ;YACd,MAAM,EAAE,QAAQ;SACjB;KACF,CAAC;IACF,GAAG,YAAY,EAAE;IACjB,UAAU,EAAE,CAAC,CAAC,MAAM,E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ACJ,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,EAAE,WAAW,EAAE,2BAA2B,EAAE,CAAC;wBACvE,QAAQ,EAAE,CAAC,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,EAAE,WAAW,EAAE,0BAA0B,EAAE,CAAC;wBACjF,SAAS,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC;qBAC5B,CAAC;iBACH,CAAC;aACH;SACF,CAAC;IACJ,CAAC;CACF","sourcesContent":["import type { IAuthRouteConfig } from '@/base';\nimport { OpenApiResponses } from '@venizia/ignis-kernel';\nimport { z } from '@hono/zod-openapi';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport { DEFAULT_MAX_UPLOAD_FILES, MetaLinkRecreateActions } from '../common/constants';\n\ntype TRouteRequest = NonNullable<IAuthRouteConfig['request']>;\n\n/** The labels both upload paths take. They ride the BODY, not the URL - an identifier in a query string lands in every access log between the client and here. */\nconst uploadLabels = () => ({\n principalType: z.string().optional(),\n principalId: z.string().or(z.number()).optional(),\n variant: z.string().optional(),\n sequence: z.coerce.number().int().optional(),\n});\n\nconst MultipartBodySchema = z.object({\n files: z.union([z.instanceof(File), z.array(z.instanceof(File))]).openapi({\n type: 'array',\n items: {\n type: 'string',\n format: 'binary',\n },\n }),\n ...uploadLabels(),\n folderPath: z.string().optional().openapi({\n description: 'Target folder path for uploaded files (e.g., \"photos/2024\")',\n example: 'photos/2024',\n }),\n});\n\nconst bucketNameParam = () =>\n z.string().openapi({\n param: {\n name: 'bucketName',\n in: 'path',\n },\n example: 'images',\n });\n\nconst objectNameParam = () =>\n z.string().openapi({\n param: {\n name: 'objectName',\n in: 'path',\n description: 'Object name or path (e.g., \"photo.jpg\" or \"photos/2024/photo.jpg\")',\n },\n example: 'photos/2024/photo.jpg',\n });\n\nconst fileStreamResponses = (): IAuthRouteConfig['responses'] => ({\n [HTTP.ResultCodes.RS_2.Ok]: {\n description: 'File stream response',\n content: {\n 'application/octet-stream': {\n schema: {\n type: 'string',\n format: 'binary',\n },\n },\n },\n },\n ...OpenApiResponses.errorResponses(),\n});\n\n/** The ten built-in asset routes. Only `path` and `request.params` differ between option combinations. */\nexport interface IAssetDefinitions {\n GET_BUCKETS: IAuthRouteConfig;\n GET_BUCKET_BY_NAME: IAuthRouteConfig;\n CREATE_BUCKET: IAuthRouteConfig;\n DELETE_BUCKET: IAuthRouteConfig;\n GET_OBJECT_BY_NAME: IAuthRouteConfig;\n DOWNLOAD_OBJECT_BY_NAME: IAuthRouteConfig;\n UPLOAD_POLICY: IAuthRouteConfig;\n UPLOAD_COMMIT: IAuthRouteConfig;\n UPLOAD: IAuthRouteConfig;\n DELETE_OBJECT: IAuthRouteConfig;\n LIST_OBJECTS: IAuthRouteConfig;\n RECREATE_METALINK: IAuthRouteConfig;\n}\n\n/**\n * Builds the route configs of one asset controller.\n * `hasConfiguredBucket` drops `/buckets/{bucketName}` and its param from every object route.\n * `rawObjectPath` appends the `{.+}` catch-all, the spelling `@hono/zod-openapi` translates.\n */\nexport class AssetDefinitionBuilder {\n static build(opts: {\n hasConfiguredBucket?: boolean;\n rawObjectPath?: boolean;\n /** The most files one upload-policy request may name. */\n maxPolicyFiles?: number;\n }): IAssetDefinitions {\n const {\n hasConfiguredBucket = false,\n rawObjectPath = false,\n maxPolicyFiles = DEFAULT_MAX_UPLOAD_FILES,\n } = opts;\n\n const bucketPrefix = hasConfiguredBucket ? '' : '/buckets/{bucketName}';\n\n // `{objectName}` is ONE segment: a folder path travels percent-encoded (`photos%2F2024%2Ff.jpg`).\n // The catch-all also matches a RAW nested path; the encoded form keeps working either way.\n const objectSegment = rawObjectPath ? '{objectName}{.+}' : '{objectName}';\n\n // A configured bucket is never in the URL, so a route whose only param was `bucketName` carries none.\n const bucketRequest = (): Pick<TRouteRequest, 'params'> =>\n hasConfiguredBucket ? {} : { params: z.object({ bucketName: bucketNameParam() }) };\n\n const objectRequest = (): TRouteRequest => ({\n params: hasConfiguredBucket\n ? z.object({ objectName: objectNameParam() })\n : z.object({ bucketName: bucketNameParam(), objectName: objectNameParam() }),\n });\n\n return {\n GET_BUCKETS: {\n method: 'get',\n path: '/buckets',\n responses: OpenApiResponses.jsonResponse({\n schema: z.array(\n z.object({\n name: z.string(),\n creationDate: z.iso.datetime(),\n }),\n ),\n }),\n },\n GET_BUCKET_BY_NAME: {\n method: 'get',\n path: bucketPrefix,\n request: {\n params: z.object({ bucketName: bucketNameParam() }),\n },\n responses: OpenApiResponses.jsonResponse({\n schema: z\n .object({\n name: z.string(),\n creationDate: z.iso.datetime(),\n })\n .nullable(),\n }),\n },\n CREATE_BUCKET: {\n method: 'post',\n path: bucketPrefix,\n request: {\n params: z.object({ bucketName: bucketNameParam() }),\n },\n responses: OpenApiResponses.jsonResponse({\n schema: z\n .object({\n name: z.string(),\n creationDate: z.iso.datetime(),\n })\n .nullable(),\n }),\n },\n DELETE_BUCKET: {\n method: 'delete',\n path: bucketPrefix,\n request: {\n params: z.object({ bucketName: bucketNameParam() }),\n },\n responses: OpenApiResponses.jsonResponse({\n schema: z.object({\n isDeleted: z.boolean(),\n }),\n }),\n },\n GET_OBJECT_BY_NAME: {\n method: 'get',\n path: `${bucketPrefix}/objects/${objectSegment}`,\n request: objectRequest(),\n responses: fileStreamResponses(),\n },\n DOWNLOAD_OBJECT_BY_NAME: {\n method: 'get',\n path: `${bucketPrefix}/download/${objectSegment}`,\n request: objectRequest(),\n responses: fileStreamResponses(),\n },\n UPLOAD_POLICY: {\n method: 'post',\n path: `${bucketPrefix}/upload-policy`,\n request: {\n body: {\n content: {\n 'application/json': {\n schema: z.object({\n files: z\n .array(\n z.object({\n fileName: z.string().min(1),\n contentType: z.string().optional(),\n size: z.number().int().nonnegative().optional(),\n }),\n )\n .max(maxPolicyFiles),\n }),\n },\n },\n },\n },\n responses: OpenApiResponses.jsonResponse({\n schema: z.array(\n z.object({\n postURL: z.string(),\n formData: z.record(z.string(), z.string()),\n objectName: z.string(),\n commitToken: z.string(),\n expiresAt: z.string(),\n }),\n ),\n description: 'One signed POST policy per file, plus the token its commit is claimed with',\n }),\n },\n UPLOAD_COMMIT: {\n method: 'post',\n path: `${bucketPrefix}/upload-commit`,\n request: {\n body: {\n content: {\n 'application/json': {\n // The labels sit beside the token, not inside it: the token is an HMAC over\n // { bucket, key, expiresAt } and deliberately carries no business fields.\n schema: z.object({ commitToken: z.string().min(1), ...uploadLabels() }),\n },\n },\n },\n },\n responses: OpenApiResponses.jsonResponse({\n schema: z.object({\n bucket: z.object({ name: z.string() }),\n object: z.object({ key: z.string() }),\n link: z.string(),\n metaLink: z\n .union([z.object({ data: z.any() }), z.object({ error: z.string() })])\n .optional(),\n }),\n description: 'The object at its final key, copied out of the pending prefix',\n }),\n },\n UPLOAD: {\n method: 'post',\n path: `${bucketPrefix}/objects`,\n request: {\n ...bucketRequest(),\n body: {\n content: {\n 'multipart/form-data': {\n schema: MultipartBodySchema,\n },\n },\n },\n },\n responses: OpenApiResponses.jsonResponse({\n schema: z.array(\n z.object({\n bucket: z.object({ name: z.string() }),\n object: z.object({\n key: z.string(),\n size: z.number(),\n contentType: z.string(),\n }),\n link: z.string(),\n metaLink: z\n .union([z.object({ data: z.any() }), z.object({ error: z.string() })])\n .optional(),\n }),\n ),\n }),\n },\n DELETE_OBJECT: {\n method: 'delete',\n path: `${bucketPrefix}/objects/${objectSegment}`,\n request: objectRequest(),\n responses: OpenApiResponses.jsonResponse({\n schema: z.object({\n success: z.boolean(),\n }),\n }),\n },\n LIST_OBJECTS: {\n method: 'get',\n path: `${bucketPrefix}/objects`,\n request: {\n ...bucketRequest(),\n query: z.object({\n prefix: z\n .string()\n .optional()\n .openapi({\n param: {\n name: 'prefix',\n in: 'query',\n description: 'Filter objects by prefix',\n },\n example: 'folder/',\n }),\n recursive: z\n .string()\n .optional()\n .openapi({\n param: {\n name: 'recursive',\n in: 'query',\n description: 'Recursive listing',\n },\n example: 'true',\n }),\n maxKeys: z\n .string()\n .optional()\n .openapi({\n param: {\n name: 'maxKeys',\n in: 'query',\n description: 'Maximum number of objects to return',\n },\n example: '100',\n }),\n }),\n },\n responses: OpenApiResponses.jsonResponse({\n schema: z.array(\n z.object({\n name: z.string().optional(),\n size: z.number().optional(),\n lastModified: z.iso.datetime().optional(),\n etag: z.string().optional(),\n prefix: z.string().optional(),\n }),\n ),\n }),\n },\n RECREATE_METALINK: {\n method: 'put',\n path: `${bucketPrefix}/meta-links/${objectSegment}`,\n request: objectRequest(),\n responses: OpenApiResponses.jsonResponse({\n schema: z.object({\n success: z.boolean(),\n action: z\n .enum([MetaLinkRecreateActions.REFRESHED, MetaLinkRecreateActions.CREATED])\n .openapi({\n description:\n '`refreshed` when rows for the object existed, `created` when none did',\n example: 'refreshed',\n }),\n count: z.number().openapi({ description: 'Rows refreshed or created' }),\n metaLink: z.any().optional().openapi({ description: 'The first of `metaLinks`' }),\n metaLinks: z.array(z.any()),\n }),\n }),\n },\n };\n }\n}\n"]}
@@ -14,7 +14,7 @@ import { HTTP, ResolverUtility } from '@venizia/ignis-helpers/common';
14
14
  import { BaseHelper, getError, UuidHelper } from '@venizia/ignis-helpers/core';
15
15
  import { readFileSync, rmSync } from 'node:fs';
16
16
  import { RENDERABLE_CONTENT_TYPES, StaticAssetErrors, DEFAULT_PENDING_PREFIX, META_LINK_CREATE_FAILED, WHITELIST_HEADERS, } from '../common/index.js';
17
- import { AssetCommitToken, MetaLinkRecreateActions } from '../common/index.js';
17
+ import { AssetCommitToken, DEFAULT_MAX_UPLOAD_FILES, MetaLinkRecreateActions } from '../common/index.js';
18
18
  import { AssetDefinitionBuilder } from './base.definition.js';
19
19
  import { AssetKeyScope } from './key-scope.js';
20
20
  import { AssetMetaLink } from './meta-link.js';
@@ -176,7 +176,11 @@ export class AssetControllerFactory extends BaseHelper {
176
176
  const objectKeyMaxDepth = maxFolderDepth + (scope?.depth ?? 0);
177
177
  // The component's own name under a scope: the original name must stay one segment, as without one.
178
178
  const isScopedDefaultNaming = keyPrefix !== undefined && !resolveObjectName && !options?.normalizeNameFn;
179
- const definitions = AssetDefinitionBuilder.build({ hasConfiguredBucket, rawObjectPath });
179
+ const definitions = AssetDefinitionBuilder.build({
180
+ hasConfiguredBucket,
181
+ rawObjectPath,
182
+ maxPolicyFiles: options?.parseMultipartBody?.maxFiles ?? DEFAULT_MAX_UPLOAD_FILES,
183
+ });
180
184
  // The mount path may be declared with or without a leading slash; a link must carry exactly one.
181
185
  const normalizedBasePath = basePath.startsWith('/') ? basePath : `/${basePath}`;
182
186
  /** Only when the URL shape deviates: with neither option the storage helper's own link is left untouched. */
@@ -426,6 +430,7 @@ export class AssetControllerFactory extends BaseHelper {
426
430
  : AssetRouteOptions.appendLengthGuard({
427
431
  middleware: uploadRoute.override.middleware,
428
432
  maxBytes,
433
+ maxFiles: options?.parseMultipartBody?.maxFiles ?? DEFAULT_MAX_UPLOAD_FILES,
429
434
  });
430
435
  this.bindRoute({
431
436
  configs: {
@@ -469,18 +474,21 @@ export class AssetControllerFactory extends BaseHelper {
469
474
  context: ctx,
470
475
  storage: options?.parseMultipartBody?.storage,
471
476
  uploadDir: options?.parseMultipartBody?.uploadDir,
477
+ maxFiles: options?.parseMultipartBody?.maxFiles ?? DEFAULT_MAX_UPLOAD_FILES,
472
478
  });
473
- // Labels travel with the payload, not the URL, so the folder check waits for the parse.
474
- const query = readUploadLabels({ fields });
475
- const folderPath = query.folderPath;
476
- if (folderPath) {
477
- validateFolderPath(folderPath);
478
- }
479
479
  const spoolPaths = filesArray
480
480
  .map((file) => file.path)
481
481
  .filter((filePath) => Boolean(filePath));
482
+ let query;
482
483
  let uploaded;
484
+ // From here every exit removes the spool files, the validation failures included.
483
485
  try {
486
+ // Labels travel with the payload, not the URL, so the folder check waits for the parse.
487
+ query = readUploadLabels({ fields });
488
+ const folderPath = query.folderPath;
489
+ if (folderPath) {
490
+ validateFolderPath(folderPath);
491
+ }
484
492
  // `storage: 'disk'` spools the payload to `uploadDir` and returns `path` instead of `buffer`; the storage helpers only ever write `buffer`, so it must be read back.
485
493
  const modifiedFiles = filesArray.map((file) => {
486
494
  const buffer = file.buffer ?? (file.path ? readFileSync(file.path) : undefined);