@haneinfo/m2m-api-key 0.0.0-stage → 8.0.4

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 (87) hide show
  1. package/LICENSE +14 -0
  2. package/dist/api-key-machine.strategy.d.ts +25 -0
  3. package/dist/api-key-machine.strategy.d.ts.map +1 -0
  4. package/dist/api-key-machine.strategy.js +110 -0
  5. package/dist/api-key-machine.strategy.js.map +1 -0
  6. package/dist/api-key-rate-limiter.d.ts +10 -0
  7. package/dist/api-key-rate-limiter.d.ts.map +1 -0
  8. package/dist/api-key-rate-limiter.js +53 -0
  9. package/dist/api-key-rate-limiter.js.map +1 -0
  10. package/dist/api-key.guard.d.ts +26 -0
  11. package/dist/api-key.guard.d.ts.map +1 -0
  12. package/dist/api-key.guard.js +109 -0
  13. package/dist/api-key.guard.js.map +1 -0
  14. package/dist/api-keys.controller.d.ts +29 -0
  15. package/dist/api-keys.controller.d.ts.map +1 -0
  16. package/dist/api-keys.controller.js +119 -0
  17. package/dist/api-keys.controller.js.map +1 -0
  18. package/dist/api-keys.module.d.ts +24 -0
  19. package/dist/api-keys.module.d.ts.map +1 -0
  20. package/dist/api-keys.module.js +85 -0
  21. package/dist/api-keys.module.js.map +1 -0
  22. package/dist/api-keys.service.d.ts +51 -0
  23. package/dist/api-keys.service.d.ts.map +1 -0
  24. package/dist/api-keys.service.js +153 -0
  25. package/dist/api-keys.service.js.map +1 -0
  26. package/dist/decorators/scopes.decorator.d.ts +3 -0
  27. package/dist/decorators/scopes.decorator.d.ts.map +1 -0
  28. package/dist/decorators/scopes.decorator.js +8 -0
  29. package/dist/decorators/scopes.decorator.js.map +1 -0
  30. package/dist/dto/api-key.dto.d.ts +37 -0
  31. package/dist/dto/api-key.dto.d.ts.map +1 -0
  32. package/dist/dto/api-key.dto.js +22 -0
  33. package/dist/dto/api-key.dto.js.map +1 -0
  34. package/dist/frontend/api-key-row-actions.d.ts +3 -0
  35. package/dist/frontend/api-key-row-actions.d.ts.map +1 -0
  36. package/dist/frontend/api-key-row-actions.js +54 -0
  37. package/dist/frontend/api-key-row-actions.js.map +1 -0
  38. package/dist/frontend/api-keys-table.d.ts +3 -0
  39. package/dist/frontend/api-keys-table.d.ts.map +1 -0
  40. package/dist/frontend/api-keys-table.js +11 -0
  41. package/dist/frontend/api-keys-table.js.map +1 -0
  42. package/dist/frontend/create-api-key-dialog.d.ts +3 -0
  43. package/dist/frontend/create-api-key-dialog.d.ts.map +1 -0
  44. package/dist/frontend/create-api-key-dialog.js +43 -0
  45. package/dist/frontend/create-api-key-dialog.js.map +1 -0
  46. package/dist/frontend/created-api-key-reveal.d.ts +3 -0
  47. package/dist/frontend/created-api-key-reveal.d.ts.map +1 -0
  48. package/dist/frontend/created-api-key-reveal.js +17 -0
  49. package/dist/frontend/created-api-key-reveal.js.map +1 -0
  50. package/dist/frontend/index.d.ts +7 -0
  51. package/dist/frontend/index.d.ts.map +1 -0
  52. package/dist/frontend/index.js +22 -0
  53. package/dist/frontend/index.js.map +1 -0
  54. package/dist/frontend/types.d.ts +98 -0
  55. package/dist/frontend/types.d.ts.map +1 -0
  56. package/dist/frontend/types.js +6 -0
  57. package/dist/frontend/types.js.map +1 -0
  58. package/dist/frontend.d.ts +9 -0
  59. package/dist/frontend.d.ts.map +1 -0
  60. package/dist/frontend.js +13 -0
  61. package/dist/frontend.js.map +1 -0
  62. package/dist/guards/admin.guard.d.ts +7 -0
  63. package/dist/guards/admin.guard.d.ts.map +1 -0
  64. package/dist/guards/admin.guard.js +6 -0
  65. package/dist/guards/admin.guard.js.map +1 -0
  66. package/dist/guards/scope.guard.d.ts +11 -0
  67. package/dist/guards/scope.guard.d.ts.map +1 -0
  68. package/dist/guards/scope.guard.js +53 -0
  69. package/dist/guards/scope.guard.js.map +1 -0
  70. package/dist/index.d.ts +12 -0
  71. package/dist/index.d.ts.map +1 -0
  72. package/dist/index.js +33 -0
  73. package/dist/index.js.map +1 -0
  74. package/dist/plugin.d.ts +16 -0
  75. package/dist/plugin.d.ts.map +1 -0
  76. package/dist/plugin.js +109 -0
  77. package/dist/plugin.js.map +1 -0
  78. package/dist/scope-matcher.service.d.ts +12 -0
  79. package/dist/scope-matcher.service.d.ts.map +1 -0
  80. package/dist/scope-matcher.service.js +28 -0
  81. package/dist/scope-matcher.service.js.map +1 -0
  82. package/haneinfo.plugin.json +82 -0
  83. package/package.json +95 -3
  84. package/plugin.d.ts +2 -0
  85. package/plugin.js +4 -0
  86. package/prisma/api-key.prisma +43 -0
  87. package/README.md +0 -3
package/LICENSE ADDED
@@ -0,0 +1,14 @@
1
+ Copyright (c) 2026 Haneinfo. All Rights Reserved.
2
+
3
+ This software and associated documentation files (the "Software") are the proprietary and
4
+ confidential property of Haneinfo. No part of the Software may be copied, modified, merged,
5
+ published, distributed, sublicensed, or sold without the prior written permission of Haneinfo.
6
+
7
+ The Software is provided for internal use by Haneinfo and its authorized personnel only, and is
8
+ NOT licensed for external distribution or open-source use.
9
+
10
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
11
+ NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
12
+ NONINFRINGEMENT. IN NO EVENT SHALL HANEINFO BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
13
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
14
+ THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,25 @@
1
+ import { PrismaService } from '@haneinfo/common';
2
+ import { type MachinePrincipal, type RbacPolicyPort } from '@haneinfo/plugin-api';
3
+ import type { AuthenticationStrategy } from '@haneinfo/plugin-host-nest';
4
+ import { type ExecutionContext } from '@nestjs/common';
5
+ import { ApiKeyRateLimiter } from './api-key-rate-limiter';
6
+ /**
7
+ * Registers API keys as a machine authentication provider with the host strategy registry (051 PL4-03, PL1-11).
8
+ *
9
+ * Implements the neutral `AuthenticationStrategy` contract:
10
+ * - Returns `null` when no `X-Api-Key` header is present (allows fall-through to interactive or other machine strategies).
11
+ * - Throws `UnauthorizedException` when an API key is presented but invalid, expired, inactive, or malformed.
12
+ * - Throws `HttpException(429)` with `Retry-After` header when rate limit is exceeded.
13
+ * - Fails closed with `UnauthorizedException` if no `RBAC_POLICY` provider is available.
14
+ */
15
+ export declare class ApiKeyMachineStrategy implements AuthenticationStrategy {
16
+ private readonly prisma;
17
+ private readonly rateLimiter;
18
+ private readonly rbacPolicy?;
19
+ readonly id = "api-key";
20
+ readonly kind: "machine";
21
+ private readonly logger;
22
+ constructor(prisma: PrismaService, rateLimiter: ApiKeyRateLimiter, rbacPolicy?: RbacPolicyPort | undefined);
23
+ authenticate(context: ExecutionContext): Promise<MachinePrincipal | null>;
24
+ }
25
+ //# sourceMappingURL=api-key-machine.strategy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-key-machine.strategy.d.ts","sourceRoot":"","sources":["../src/api-key-machine.strategy.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,KAAK,gBAAgB,EAAe,KAAK,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC/F,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AACzE,OAAO,EACL,KAAK,gBAAgB,EAQtB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAG3D;;;;;;;;GAQG;AACH,qBACa,qBAAsB,YAAW,sBAAsB;IAOzC,OAAO,CAAC,QAAQ,CAAC,MAAM;IACnB,OAAO,CAAC,QAAQ,CAAC,WAAW;IACtB,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAC;IAR/D,QAAQ,CAAC,EAAE,aAAa;IACxB,QAAQ,CAAC,IAAI,EAAG,SAAS,CAAU;IAEnC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAA0C;gBAGvB,MAAM,EAAE,aAAa,EACjB,WAAW,EAAE,iBAAiB,EACxB,UAAU,CAAC,EAAE,cAAc,YAAA;IAGzE,YAAY,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,GAAG,IAAI,CAAC;CAsEhF"}
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ var ApiKeyMachineStrategy_1;
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.ApiKeyMachineStrategy = void 0;
17
+ const node_crypto_1 = require("node:crypto");
18
+ const common_1 = require("@haneinfo/common");
19
+ const plugin_api_1 = require("@haneinfo/plugin-api");
20
+ const common_2 = require("@nestjs/common");
21
+ const api_key_rate_limiter_1 = require("./api-key-rate-limiter");
22
+ const api_keys_service_1 = require("./api-keys.service");
23
+ /**
24
+ * Registers API keys as a machine authentication provider with the host strategy registry (051 PL4-03, PL1-11).
25
+ *
26
+ * Implements the neutral `AuthenticationStrategy` contract:
27
+ * - Returns `null` when no `X-Api-Key` header is present (allows fall-through to interactive or other machine strategies).
28
+ * - Throws `UnauthorizedException` when an API key is presented but invalid, expired, inactive, or malformed.
29
+ * - Throws `HttpException(429)` with `Retry-After` header when rate limit is exceeded.
30
+ * - Fails closed with `UnauthorizedException` if no `RBAC_POLICY` provider is available.
31
+ */
32
+ let ApiKeyMachineStrategy = ApiKeyMachineStrategy_1 = class ApiKeyMachineStrategy {
33
+ constructor(prisma, rateLimiter, rbacPolicy) {
34
+ this.prisma = prisma;
35
+ this.rateLimiter = rateLimiter;
36
+ this.rbacPolicy = rbacPolicy;
37
+ this.id = 'api-key';
38
+ this.kind = 'machine';
39
+ this.logger = new common_2.Logger(ApiKeyMachineStrategy_1.name);
40
+ }
41
+ async authenticate(context) {
42
+ const request = context.switchToHttp().getRequest();
43
+ const rawKey = request?.headers?.['x-api-key'];
44
+ // No header presented -> fall through to next strategy
45
+ if (typeof rawKey !== 'string')
46
+ return null;
47
+ // Header presented but malformed -> reject explicitly
48
+ if (!rawKey.startsWith(api_keys_service_1.KEY_PREFIX)) {
49
+ throw new common_2.UnauthorizedException('Invalid API key');
50
+ }
51
+ if (!this.rbacPolicy) {
52
+ this.logger.error('API key authentication is unavailable: no haneinfo.rbac-policy provider is registered. ' +
53
+ 'Import RbacModule (or another provider of RBAC_POLICY) to enable it.');
54
+ throw new common_2.UnauthorizedException('API key authentication is unavailable: no RBAC policy provider registered');
55
+ }
56
+ const hashedKey = (0, node_crypto_1.createHash)('sha256').update(rawKey).digest('hex');
57
+ const now = new Date();
58
+ const apiKey = await this.prisma.apiKey.findFirst({
59
+ where: {
60
+ hashedKey,
61
+ isActive: true,
62
+ OR: [{ expiresAt: null }, { expiresAt: { gt: now } }],
63
+ },
64
+ include: {
65
+ role: { include: { permissions: true } },
66
+ actingUser: { select: { id: true, isActive: true } },
67
+ },
68
+ });
69
+ if (!apiKey) {
70
+ throw new common_2.UnauthorizedException('Invalid API key');
71
+ }
72
+ const { allowed, retryAfter } = this.rateLimiter.check(apiKey.id, apiKey.rateLimit);
73
+ if (!allowed) {
74
+ const response = context
75
+ .switchToHttp()
76
+ .getResponse();
77
+ if (typeof response?.setHeader === 'function') {
78
+ response.setHeader('Retry-After', String(retryAfter ?? 60));
79
+ }
80
+ throw new common_2.HttpException('Too Many Requests', common_2.HttpStatus.TOO_MANY_REQUESTS);
81
+ }
82
+ // Fire-and-forget lastUsedAt update
83
+ this.prisma.apiKey
84
+ .update({ where: { id: apiKey.id }, data: { lastUsedAt: now } })
85
+ .catch((e) => this.logger.error(`lastUsedAt update failed: ${errorMessage(e)}`));
86
+ const actingUserId = apiKey.actingUser?.isActive ? apiKey.actingUser.id : null;
87
+ const flattened = this.rbacPolicy.flatten([apiKey.role]);
88
+ return {
89
+ sub: apiKey.id,
90
+ ...flattened,
91
+ scopes: apiKey.scopes,
92
+ isApiKey: true,
93
+ actingUserId,
94
+ };
95
+ }
96
+ };
97
+ exports.ApiKeyMachineStrategy = ApiKeyMachineStrategy;
98
+ exports.ApiKeyMachineStrategy = ApiKeyMachineStrategy = ApiKeyMachineStrategy_1 = __decorate([
99
+ (0, common_2.Injectable)(),
100
+ __param(0, (0, common_2.Inject)(common_1.PrismaService)),
101
+ __param(1, (0, common_2.Inject)(api_key_rate_limiter_1.ApiKeyRateLimiter)),
102
+ __param(2, (0, common_2.Optional)()),
103
+ __param(2, (0, common_2.Inject)(plugin_api_1.RBAC_POLICY)),
104
+ __metadata("design:paramtypes", [common_1.PrismaService,
105
+ api_key_rate_limiter_1.ApiKeyRateLimiter, Object])
106
+ ], ApiKeyMachineStrategy);
107
+ function errorMessage(error) {
108
+ return error instanceof Error ? error.message : String(error);
109
+ }
110
+ //# sourceMappingURL=api-key-machine.strategy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-key-machine.strategy.js","sourceRoot":"","sources":["../src/api-key-machine.strategy.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,6CAAyC;AACzC,6CAAiD;AACjD,qDAA+F;AAE/F,2CASwB;AACxB,iEAA2D;AAC3D,yDAAgD;AAEhD;;;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AA6B,YAAY,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;QAE5F,MAAM,YAAY,GAAG,MAAM,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;QAC/E,MAAM,SAAS,GAAG,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;QAEzD,OAAO;YACL,GAAG,EAAE,MAAM,CAAC,EAAE;YACd,GAAG,SAAS;YACZ,MAAM,EAAE,MAAM,CAAC,MAAM;YACrB,QAAQ,EAAE,IAAI;YACd,YAAY;SACb,CAAC;IACJ,CAAC;CACF,CAAA;AAlFY,sDAAqB;gCAArB,qBAAqB;IADjC,IAAA,mBAAU,GAAE;IAQR,WAAA,IAAA,eAAM,EAAC,sBAAa,CAAC,CAAA;IACrB,WAAA,IAAA,eAAM,EAAC,wCAAiB,CAAC,CAAA;IACzB,WAAA,IAAA,iBAAQ,GAAE,CAAA;IAAE,WAAA,IAAA,eAAM,EAAC,wBAAW,CAAC,CAAA;qCAFgB,sBAAa;QACJ,wCAAiB;GARjE,qBAAqB,CAkFjC;AAED,SAAS,YAAY,CAAC,KAAc;IAClC,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAChE,CAAC"}
@@ -0,0 +1,10 @@
1
+ export declare class ApiKeyRateLimiter {
2
+ private readonly buckets;
3
+ constructor();
4
+ check(keyId: string, limitPerMin: number | null): {
5
+ allowed: boolean;
6
+ retryAfter?: number;
7
+ };
8
+ private evict;
9
+ }
10
+ //# sourceMappingURL=api-key-rate-limiter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-key-rate-limiter.d.ts","sourceRoot":"","sources":["../src/api-key-rate-limiter.ts"],"names":[],"mappings":"AAWA,qBACa,iBAAiB;IAC5B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA6B;;IAOrD,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,IAAI,GAAG;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE;IAoB3F,OAAO,CAAC,KAAK;CAQd"}
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.ApiKeyRateLimiter = void 0;
13
+ const common_1 = require("@nestjs/common");
14
+ const DEFAULT_LIMIT = 60;
15
+ const WINDOW_MS = 60_000;
16
+ const EVICTION_INTERVAL_MS = 5 * 60_000;
17
+ let ApiKeyRateLimiter = class ApiKeyRateLimiter {
18
+ constructor() {
19
+ this.buckets = new Map();
20
+ // Evict stale buckets every 5 minutes to prevent unbounded memory growth
21
+ setInterval(() => this.evict(), EVICTION_INTERVAL_MS).unref();
22
+ }
23
+ check(keyId, limitPerMin) {
24
+ const limit = limitPerMin ?? DEFAULT_LIMIT;
25
+ const now = Date.now();
26
+ let bucket = this.buckets.get(keyId);
27
+ if (!bucket || now - bucket.windowStart >= WINDOW_MS) {
28
+ bucket = { count: 1, windowStart: now };
29
+ this.buckets.set(keyId, bucket);
30
+ return { allowed: true };
31
+ }
32
+ bucket.count += 1;
33
+ if (bucket.count > limit) {
34
+ const retryAfter = Math.ceil((WINDOW_MS - (now - bucket.windowStart)) / 1000);
35
+ return { allowed: false, retryAfter };
36
+ }
37
+ return { allowed: true };
38
+ }
39
+ evict() {
40
+ const now = Date.now();
41
+ for (const [id, bucket] of this.buckets) {
42
+ if (now - bucket.windowStart >= WINDOW_MS * 2) {
43
+ this.buckets.delete(id);
44
+ }
45
+ }
46
+ }
47
+ };
48
+ exports.ApiKeyRateLimiter = ApiKeyRateLimiter;
49
+ exports.ApiKeyRateLimiter = ApiKeyRateLimiter = __decorate([
50
+ (0, common_1.Injectable)(),
51
+ __metadata("design:paramtypes", [])
52
+ ], ApiKeyRateLimiter);
53
+ //# sourceMappingURL=api-key-rate-limiter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-key-rate-limiter.js","sourceRoot":"","sources":["../src/api-key-rate-limiter.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,2CAA4C;AAE5C,MAAM,aAAa,GAAG,EAAE,CAAC;AACzB,MAAM,SAAS,GAAG,MAAM,CAAC;AACzB,MAAM,oBAAoB,GAAG,CAAC,GAAG,MAAM,CAAC;AAQjC,IAAM,iBAAiB,GAAvB,MAAM,iBAAiB;IAG5B;QAFiB,YAAO,GAAG,IAAI,GAAG,EAAkB,CAAC;QAGnD,yEAAyE;QACzE,WAAW,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,EAAE,EAAE,oBAAoB,CAAC,CAAC,KAAK,EAAE,CAAC;IAChE,CAAC;IAED,KAAK,CAAC,KAAa,EAAE,WAA0B;QAC7C,MAAM,KAAK,GAAG,WAAW,IAAI,aAAa,CAAC;QAC3C,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACvB,IAAI,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QAErC,IAAI,CAAC,MAAM,IAAI,GAAG,GAAG,MAAM,CAAC,WAAW,IAAI,SAAS,EAAE,CAAC;YACrD,MAAM,GAAG,EAAE,KAAK,EAAE,CAAC,EAAE,WAAW,EAAE,GAAG,EAAE,CAAC;YACxC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;YAChC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;QAC3B,CAAC;QAED,MAAM,CAAC,KAAK,IAAI,CAAC,CAAC;QAClB,IAAI,MAAM,CAAC,KAAK,GAAG,KAAK,EAAE,CAAC;YACzB,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,SAAS,GAAG,CAAC,GAAG,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;YAC9E,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC;QACxC,CAAC;QAED,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC3B,CAAC;IAEO,KAAK;QACX,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACvB,KAAK,MAAM,CAAC,EAAE,EAAE,MAAM,CAAC,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;YACxC,IAAI,GAAG,GAAG,MAAM,CAAC,WAAW,IAAI,SAAS,GAAG,CAAC,EAAE,CAAC;gBAC9C,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;YAC1B,CAAC;QACH,CAAC;IACH,CAAC;CACF,CAAA;AApCY,8CAAiB;4BAAjB,iBAAiB;IAD7B,IAAA,mBAAU,GAAE;;GACA,iBAAiB,CAoC7B"}
@@ -0,0 +1,26 @@
1
+ import { PrismaService } from '@haneinfo/common';
2
+ import { type RbacPolicyPort } from '@haneinfo/plugin-api';
3
+ import { CanActivate, ExecutionContext } from '@nestjs/common';
4
+ import { ApiKeyRateLimiter } from './api-key-rate-limiter';
5
+ export declare class ApiKeyGuard implements CanActivate {
6
+ private readonly prisma;
7
+ private readonly rateLimiter;
8
+ private readonly rbacPolicy?;
9
+ private readonly logger;
10
+ /**
11
+ * `RBAC_POLICY` is optional at injection and mandatory at use.
12
+ *
13
+ * Before the 051 split this guard called `buildUserContext()`, a pure function from
14
+ * `@haneinfo/auth`, so it had no DI requirement at all. Requiring the token outright would turn
15
+ * "this App has not installed RBAC" into a boot failure for the whole application — in a package
16
+ * that has no manifest yet (it migrates in Phase 4), so nothing could have warned the operator
17
+ * first. Gate G1's independent review found exactly that, shipped as a patch.
18
+ *
19
+ * Fail-closed instead: without a policy provider an API key authorises nothing, and says so.
20
+ * The App boots, every other authentication path keeps working, and no request is ever served
21
+ * with a silently permission-less principal.
22
+ */
23
+ constructor(prisma: PrismaService, rateLimiter: ApiKeyRateLimiter, rbacPolicy?: RbacPolicyPort | undefined);
24
+ canActivate(ctx: ExecutionContext): Promise<boolean>;
25
+ }
26
+ //# sourceMappingURL=api-key.guard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-key.guard.d.ts","sourceRoot":"","sources":["../src/api-key.guard.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAe,KAAK,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAExE,OAAO,EACL,WAAW,EACX,gBAAgB,EAOjB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAG3D,qBACa,WAAY,YAAW,WAAW;IAiBpB,OAAO,CAAC,QAAQ,CAAC,MAAM;IACnB,OAAO,CAAC,QAAQ,CAAC,WAAW;IACtB,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAC;IAlB/D,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAgC;IAEvD;;;;;;;;;;;;OAYG;gBAEuC,MAAM,EAAE,aAAa,EACjB,WAAW,EAAE,iBAAiB,EACxB,UAAU,CAAC,EAAE,cAAc,YAAA;IAGzE,WAAW,CAAC,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,OAAO,CAAC;CAiE3D"}
@@ -0,0 +1,109 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ var ApiKeyGuard_1;
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.ApiKeyGuard = void 0;
17
+ const node_crypto_1 = require("node:crypto");
18
+ const common_1 = require("@haneinfo/common");
19
+ const plugin_api_1 = require("@haneinfo/plugin-api");
20
+ const common_2 = require("@nestjs/common");
21
+ const api_key_rate_limiter_1 = require("./api-key-rate-limiter");
22
+ const api_keys_service_1 = require("./api-keys.service");
23
+ let ApiKeyGuard = ApiKeyGuard_1 = class ApiKeyGuard {
24
+ /**
25
+ * `RBAC_POLICY` is optional at injection and mandatory at use.
26
+ *
27
+ * Before the 051 split this guard called `buildUserContext()`, a pure function from
28
+ * `@haneinfo/auth`, so it had no DI requirement at all. Requiring the token outright would turn
29
+ * "this App has not installed RBAC" into a boot failure for the whole application — in a package
30
+ * that has no manifest yet (it migrates in Phase 4), so nothing could have warned the operator
31
+ * first. Gate G1's independent review found exactly that, shipped as a patch.
32
+ *
33
+ * Fail-closed instead: without a policy provider an API key authorises nothing, and says so.
34
+ * The App boots, every other authentication path keeps working, and no request is ever served
35
+ * with a silently permission-less principal.
36
+ */
37
+ constructor(prisma, rateLimiter, rbacPolicy) {
38
+ this.prisma = prisma;
39
+ this.rateLimiter = rateLimiter;
40
+ this.rbacPolicy = rbacPolicy;
41
+ this.logger = new common_2.Logger(ApiKeyGuard_1.name);
42
+ }
43
+ async canActivate(ctx) {
44
+ const request = ctx.switchToHttp().getRequest();
45
+ if (!this.rbacPolicy) {
46
+ // Logged per rejected request on purpose: a misconfiguration that disables API-key auth
47
+ // should be noisy in the logs of the requests it actually breaks, not once at boot where it
48
+ // scrolls past.
49
+ this.logger.error('API key authentication is unavailable: no haneinfo.rbac-policy provider is registered. ' +
50
+ 'Import RbacModule (or another provider of RBAC_POLICY) to enable it.');
51
+ return false;
52
+ }
53
+ const rawKey = request.headers['x-api-key'];
54
+ // Express may return string | string[] for duplicate headers; reject anything
55
+ // that isn't a single, well-formed key before hashing.
56
+ if (typeof rawKey !== 'string' || !rawKey.startsWith(api_keys_service_1.KEY_PREFIX))
57
+ return false;
58
+ const hashedKey = (0, node_crypto_1.createHash)('sha256').update(rawKey).digest('hex');
59
+ const now = new Date();
60
+ const apiKey = await this.prisma.apiKey.findFirst({
61
+ where: {
62
+ hashedKey,
63
+ isActive: true,
64
+ OR: [{ expiresAt: null }, { expiresAt: { gt: now } }],
65
+ },
66
+ include: {
67
+ role: { include: { permissions: true } },
68
+ actingUser: { select: { id: true, isActive: true } },
69
+ },
70
+ });
71
+ if (!apiKey)
72
+ return false;
73
+ const { allowed, retryAfter } = this.rateLimiter.check(apiKey.id, apiKey.rateLimit);
74
+ if (!allowed) {
75
+ const response = ctx
76
+ .switchToHttp()
77
+ .getResponse();
78
+ response.setHeader('Retry-After', String(retryAfter ?? 60));
79
+ throw new common_2.HttpException('Too Many Requests', common_2.HttpStatus.TOO_MANY_REQUESTS);
80
+ }
81
+ // Fire-and-forget lastUsedAt update
82
+ this.prisma.apiKey
83
+ .update({ where: { id: apiKey.id }, data: { lastUsedAt: now } })
84
+ .catch((e) => this.logger.error(`lastUsedAt update failed: ${errorMessage(e)}`));
85
+ const actingUserId = apiKey.actingUser?.isActive ? apiKey.actingUser.id : null;
86
+ request.user = {
87
+ sub: apiKey.id,
88
+ ...this.rbacPolicy.flatten([apiKey.role]),
89
+ scopes: apiKey.scopes,
90
+ isApiKey: true,
91
+ actingUserId,
92
+ };
93
+ return true;
94
+ }
95
+ };
96
+ exports.ApiKeyGuard = ApiKeyGuard;
97
+ exports.ApiKeyGuard = ApiKeyGuard = ApiKeyGuard_1 = __decorate([
98
+ (0, common_2.Injectable)(),
99
+ __param(0, (0, common_2.Inject)(common_1.PrismaService)),
100
+ __param(1, (0, common_2.Inject)(api_key_rate_limiter_1.ApiKeyRateLimiter)),
101
+ __param(2, (0, common_2.Optional)()),
102
+ __param(2, (0, common_2.Inject)(plugin_api_1.RBAC_POLICY)),
103
+ __metadata("design:paramtypes", [common_1.PrismaService,
104
+ api_key_rate_limiter_1.ApiKeyRateLimiter, Object])
105
+ ], ApiKeyGuard);
106
+ function errorMessage(error) {
107
+ return error instanceof Error ? error.message : String(error);
108
+ }
109
+ //# sourceMappingURL=api-key.guard.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-key.guard.js","sourceRoot":"","sources":["../src/api-key.guard.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,6CAAyC;AACzC,6CAAiD;AACjD,qDAAwE;AAExE,2CASwB;AACxB,iEAA2D;AAC3D,yDAAgD;AAGzC,IAAM,WAAW,mBAAjB,MAAM,WAAW;IAGtB;;;;;;;;;;;;OAYG;IACH,YACyB,MAAsC,EAClC,WAA+C,EACzC,UAA4C;QAFrC,WAAM,GAAN,MAAM,CAAe;QACjB,gBAAW,GAAX,WAAW,CAAmB;QACxB,eAAU,GAAV,UAAU,CAAiB;QAlB9D,WAAM,GAAG,IAAI,eAAM,CAAC,aAAW,CAAC,IAAI,CAAC,CAA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BR,WAAA,IAAA,eAAM,EAAC,sBAAa,CAAC,CAAA;IACrB,WAAA,IAAA,eAAM,EAAC,wCAAiB,CAAC,CAAA;IACzB,WAAA,IAAA,iBAAQ,GAAE,CAAA;IAAE,WAAA,IAAA,eAAM,EAAC,wBAAW,CAAC,CAAA;qCAFgB,sBAAa;QACJ,wCAAiB;GAlBjE,WAAW,CAuFvB;AAED,SAAS,YAAY,CAAC,KAAc;IAClC,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAChE,CAAC"}
@@ -0,0 +1,29 @@
1
+ import type { PaginationQuery } from '@haneinfo/common';
2
+ import { type AuditSinkPort } from '@haneinfo/plugin-api';
3
+ import { ApiKeysService } from './api-keys.service';
4
+ import type { CreateApiKeyDto, UpdateApiKeyDto } from './dto/api-key.dto';
5
+ export declare class ApiKeysController {
6
+ private readonly apiKeysService;
7
+ private readonly auditSink?;
8
+ private readonly logger;
9
+ constructor(apiKeysService: ApiKeysService, auditSink?: AuditSinkPort | undefined);
10
+ private recordAudit;
11
+ create(dto: CreateApiKeyDto, actor: {
12
+ sub: string;
13
+ email?: string;
14
+ isApiKey?: boolean;
15
+ }): Promise<import("./dto/api-key.dto").CreateApiKeyResponse>;
16
+ findAll(query: PaginationQuery): Promise<import("@haneinfo/common").PaginatedResult<import("./api-keys.service").ApiKeyRecord>>;
17
+ findOne(id: string): Promise<import("./api-keys.service").ApiKeyRecord>;
18
+ update(id: string, dto: UpdateApiKeyDto, actor: {
19
+ sub: string;
20
+ email?: string;
21
+ isApiKey?: boolean;
22
+ }): Promise<import("./api-keys.service").ApiKeyRecord>;
23
+ remove(id: string, actor: {
24
+ sub: string;
25
+ email?: string;
26
+ isApiKey?: boolean;
27
+ }): Promise<void>;
28
+ }
29
+ //# sourceMappingURL=api-keys.controller.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-keys.controller.d.ts","sourceRoot":"","sources":["../src/api-keys.controller.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAExD,OAAO,EAAc,KAAK,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAiBtE,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,KAAK,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAK1E,qBAEa,iBAAiB;IAIF,OAAO,CAAC,QAAQ,CAAC,cAAc;IACvB,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC;IAJ7D,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAsC;gBAGlB,cAAc,EAAE,cAAc,EACtB,SAAS,CAAC,EAAE,aAAa,YAAA;IAM5E,OAAO,CAAC,WAAW;IAqBb,MAAM,CACuC,GAAG,EAAE,eAAe,EAEtD,KAAK,EAAE;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,OAAO,CAAA;KAAE;IAQ3E,OAAO,CAAsD,KAAK,EAAE,eAAe;IAKnF,OAAO,CAAc,EAAE,EAAE,MAAM;IAKzB,MAAM,CACG,EAAE,EAAE,MAAM,EAC0B,GAAG,EAAE,eAAe,EACtD,KAAK,EAAE;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,OAAO,CAAA;KAAE;IASrE,MAAM,CACG,EAAE,EAAE,MAAM,EACR,KAAK,EAAE;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,OAAO,CAAA;KAAE;CAK5E"}
@@ -0,0 +1,119 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ var ApiKeysController_1;
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.ApiKeysController = void 0;
17
+ const common_1 = require("@haneinfo/common");
18
+ const plugin_api_1 = require("@haneinfo/plugin-api");
19
+ const plugin_host_nest_1 = require("@haneinfo/plugin-host-nest");
20
+ const common_2 = require("@nestjs/common");
21
+ const api_keys_service_1 = require("./api-keys.service");
22
+ const api_key_dto_1 = require("./dto/api-key.dto");
23
+ const admin_guard_1 = require("./guards/admin.guard");
24
+ // API key management is ADMIN-only per user requirement.
25
+ let ApiKeysController = ApiKeysController_1 = class ApiKeysController {
26
+ constructor(apiKeysService, auditSink) {
27
+ this.apiKeysService = apiKeysService;
28
+ this.auditSink = auditSink;
29
+ this.logger = new common_2.Logger(ApiKeysController_1.name);
30
+ }
31
+ // Fire-and-forget: an audit log failure must never block the business response
32
+ // (dev_docs/004-task-breakdown.md T-101). Never pass the raw key into `entityId`
33
+ // or any audit payload field — only the key's id/name/scopes are non-secret.
34
+ recordAudit(entityId, action, actor) {
35
+ if (!this.auditSink)
36
+ return;
37
+ void this.auditSink
38
+ .record({
39
+ entityType: 'ApiKey',
40
+ entityId,
41
+ action,
42
+ actorId: actor.sub,
43
+ actorEmail: actor.email ?? `api-key:${actor.sub}`,
44
+ appName: process.env.APP_NAME ?? 'haneinfo-app-template',
45
+ actingApiKeyId: actor.isApiKey === true ? actor.sub : null,
46
+ })
47
+ .catch((error) => this.logger.warn(`Failed to record audit log: ${String(error)}`));
48
+ }
49
+ async create(dto, actor) {
50
+ const result = await this.apiKeysService.create(dto, actor.email ?? `api-key:${actor.sub}`);
51
+ this.recordAudit(result.id, common_1.AuditAction.CREATE, actor);
52
+ return result;
53
+ }
54
+ findAll(query) {
55
+ return this.apiKeysService.findAll(query);
56
+ }
57
+ findOne(id) {
58
+ return this.apiKeysService.findOne(id);
59
+ }
60
+ async update(id, dto, actor) {
61
+ const result = await this.apiKeysService.update(id, dto);
62
+ this.recordAudit(id, common_1.AuditAction.UPDATE, actor);
63
+ return result;
64
+ }
65
+ async remove(id, actor) {
66
+ await this.apiKeysService.remove(id);
67
+ this.recordAudit(id, common_1.AuditAction.DELETE, actor);
68
+ }
69
+ };
70
+ exports.ApiKeysController = ApiKeysController;
71
+ __decorate([
72
+ (0, common_2.Post)(),
73
+ __param(0, (0, common_2.Body)(new common_1.ZodValidationPipe(api_key_dto_1.createApiKeySchema))),
74
+ __param(1, (0, plugin_host_nest_1.CurrentUser)()),
75
+ __metadata("design:type", Function),
76
+ __metadata("design:paramtypes", [Object, Object]),
77
+ __metadata("design:returntype", Promise)
78
+ ], ApiKeysController.prototype, "create", null);
79
+ __decorate([
80
+ (0, common_2.Get)(),
81
+ __param(0, (0, common_2.Query)(new common_1.ZodValidationPipe(common_1.paginationQuerySchema))),
82
+ __metadata("design:type", Function),
83
+ __metadata("design:paramtypes", [Object]),
84
+ __metadata("design:returntype", void 0)
85
+ ], ApiKeysController.prototype, "findAll", null);
86
+ __decorate([
87
+ (0, common_2.Get)(':id'),
88
+ __param(0, (0, common_2.Param)('id')),
89
+ __metadata("design:type", Function),
90
+ __metadata("design:paramtypes", [String]),
91
+ __metadata("design:returntype", void 0)
92
+ ], ApiKeysController.prototype, "findOne", null);
93
+ __decorate([
94
+ (0, common_2.Patch)(':id'),
95
+ __param(0, (0, common_2.Param)('id')),
96
+ __param(1, (0, common_2.Body)(new common_1.ZodValidationPipe(api_key_dto_1.updateApiKeySchema))),
97
+ __param(2, (0, plugin_host_nest_1.CurrentUser)()),
98
+ __metadata("design:type", Function),
99
+ __metadata("design:paramtypes", [String, Object, Object]),
100
+ __metadata("design:returntype", Promise)
101
+ ], ApiKeysController.prototype, "update", null);
102
+ __decorate([
103
+ (0, common_2.Delete)(':id'),
104
+ (0, common_2.HttpCode)(204),
105
+ __param(0, (0, common_2.Param)('id')),
106
+ __param(1, (0, plugin_host_nest_1.CurrentUser)()),
107
+ __metadata("design:type", Function),
108
+ __metadata("design:paramtypes", [String, Object]),
109
+ __metadata("design:returntype", Promise)
110
+ ], ApiKeysController.prototype, "remove", null);
111
+ exports.ApiKeysController = ApiKeysController = ApiKeysController_1 = __decorate([
112
+ (0, common_2.Controller)('api-keys'),
113
+ (0, common_2.UseGuards)(plugin_host_nest_1.HaneinfoAuthGuard, admin_guard_1.ApiKeyAdminGuard),
114
+ __param(0, (0, common_2.Inject)(api_keys_service_1.ApiKeysService)),
115
+ __param(1, (0, common_2.Optional)()),
116
+ __param(1, (0, common_2.Inject)(plugin_api_1.AUDIT_SINK)),
117
+ __metadata("design:paramtypes", [api_keys_service_1.ApiKeysService, Object])
118
+ ], ApiKeysController);
119
+ //# sourceMappingURL=api-keys.controller.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-keys.controller.js","sourceRoot":"","sources":["../src/api-keys.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AACA,6CAAyF;AACzF,qDAAsE;AACtE,iEAA4E;AAC5E,2CAcwB;AACxB,yDAAoD;AAEpD,mDAA2E;AAC3E,sDAAwD;AAExD,yDAAyD;AAGlD,IAAM,iBAAiB,yBAAvB,MAAM,iBAAiB;IAG5B,YAC0B,cAA+C,EACvC,SAA0C;QADjC,mBAAc,GAAd,cAAc,CAAgB;QACtB,cAAS,GAAT,SAAS,CAAgB;QAJ3D,WAAM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,CAAC;IACb,IAAA,iBAAQ,EAAC,GAAG,CAAC;IAEX,WAAA,IAAA,cAAK,EAAC,IAAI,CAAC,CAAA;IACX,WAAA,IAAA,8BAAW,GAAE,CAAA;;;;+CAIf;4BAvEU,iBAAiB;IAF7B,IAAA,mBAAU,EAAC,UAAU,CAAC;IACtB,IAAA,kBAAS,EAAC,oCAAiB,EAAE,8BAAgB,CAAC;IAK1C,WAAA,IAAA,eAAM,EAAC,iCAAc,CAAC,CAAA;IACtB,WAAA,IAAA,iBAAQ,GAAE,CAAA;IAAE,WAAA,IAAA,eAAM,EAAC,uBAAU,CAAC,CAAA;qCAD0B,iCAAc;GAJ9D,iBAAiB,CAwE7B"}
@@ -0,0 +1,24 @@
1
+ import { AuthenticationStrategyRegistry } from '@haneinfo/plugin-host-nest';
2
+ import { type OnModuleInit } from '@nestjs/common';
3
+ import { ApiKeyMachineStrategy } from './api-key-machine.strategy';
4
+ /**
5
+ * Machine-to-Machine API Keys capability module (051 PL4-03).
6
+ *
7
+ * Provides:
8
+ * - `haneinfo.machine-auth-provider`: registers `ApiKeyMachineStrategy` into `AuthenticationStrategyRegistry`.
9
+ * - `haneinfo.scope-matcher`: bound to `SCOPE_MATCHER` token via `ScopeMatcherService`.
10
+ * - Admin key management CRUD endpoints (`ApiKeysController` / `ApiKeysService`).
11
+ *
12
+ * The module is deliberately scoped. Consumers must import it explicitly or import a generated
13
+ * plugin composition module that exports it.
14
+ */
15
+ export declare class ApiKeysModule implements OnModuleInit {
16
+ private readonly registry;
17
+ private readonly strategy;
18
+ constructor(registry: AuthenticationStrategyRegistry, strategy: ApiKeyMachineStrategy);
19
+ /**
20
+ * Registers the machine strategy with the host (PL1-11, PL4-03).
21
+ */
22
+ onModuleInit(): void;
23
+ }
24
+ //# sourceMappingURL=api-keys.module.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-keys.module.d.ts","sourceRoot":"","sources":["../src/api-keys.module.ts"],"names":[],"mappings":"AACA,OAAO,EACL,8BAA8B,EAG/B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAkB,KAAK,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAEnE,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AAQnE;;;;;;;;;;GAUG;AACH,qBA0Ba,aAAc,YAAW,YAAY;IAG9C,OAAO,CAAC,QAAQ,CAAC,QAAQ;IAEzB,OAAO,CAAC,QAAQ,CAAC,QAAQ;gBAFR,QAAQ,EAAE,8BAA8B,EAExC,QAAQ,EAAE,qBAAqB;IAGlD;;OAEG;IACH,YAAY,IAAI,IAAI;CAKrB"}