@appaflytech/zeyrek-ai-mcp 0.0.81 → 0.0.83

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 (86) hide show
  1. package/.env.example +18 -1
  2. package/.env.production.example +17 -0
  3. package/README.md +50 -5
  4. package/dist/auth/clientRegistry.js +57 -0
  5. package/dist/auth/gatewayOAuthProvider.js +115 -0
  6. package/dist/auth/loginPage.js +60 -0
  7. package/dist/auth/loginRoute.js +56 -0
  8. package/dist/auth/loginThrottle.js +33 -0
  9. package/dist/auth/tokenSeal.js +25 -0
  10. package/dist/config.js +80 -4
  11. package/dist/gatewayVersion.js +3 -0
  12. package/dist/httpApp.js +90 -0
  13. package/dist/index.js +11 -47
  14. package/dist/knowledge/access.js +22 -22
  15. package/dist/knowledge/backendConstraints.js +18 -18
  16. package/dist/knowledge/case.js +1 -1
  17. package/dist/knowledge/componentCatalog.js +1 -1
  18. package/dist/knowledge/coverage.js +5 -5
  19. package/dist/knowledge/decision.js +1 -1
  20. package/dist/knowledge/languages.js +1 -1
  21. package/dist/knowledge/methodEffect.js +1 -1
  22. package/dist/knowledge/mobileStore.js +3 -3
  23. package/dist/knowledge/normalize.js +1 -1
  24. package/dist/knowledge/process.js +15 -15
  25. package/dist/knowledge/rules.js +207 -207
  26. package/dist/knowledge/schemaGuard.js +2 -2
  27. package/dist/knowledge/socialSignIn.js +1 -1
  28. package/dist/knowledge/themeRules.js +1 -1
  29. package/dist/observability/gapSink.js +1 -2
  30. package/dist/observability/trace.js +1 -1
  31. package/dist/platform/errors.js +4 -2
  32. package/dist/platform/http.js +13 -3
  33. package/dist/platform/localFiles.js +21 -0
  34. package/dist/platform/token.js +74 -52
  35. package/dist/resources/examples/flow-sign-in-with.json +1 -1
  36. package/dist/resources/examples/function-total.json +1 -1
  37. package/dist/resources/examples/mobile-list-detail-form.json +1 -1
  38. package/dist/resources/guides/bpm.md +3 -3
  39. package/dist/resources/guides/entity.md +5 -5
  40. package/dist/resources/guides/external-component.md +1 -1
  41. package/dist/resources/guides/functions.md +3 -3
  42. package/dist/resources/guides/getting-started.md +17 -4
  43. package/dist/resources/guides/html.md +1 -1
  44. package/dist/resources/guides/layout.md +1 -1
  45. package/dist/resources/guides/microfunction.md +2 -2
  46. package/dist/resources/guides/microservice.md +2 -2
  47. package/dist/resources/guides/middleware.md +2 -2
  48. package/dist/resources/guides/mobile-layout.md +1 -1
  49. package/dist/resources/guides/mobile-local.md +1 -1
  50. package/dist/resources/guides/mobile-steps.md +6 -6
  51. package/dist/resources/guides/mobile.md +6 -6
  52. package/dist/resources/guides/modify-existing.md +1 -1
  53. package/dist/resources/guides/page.md +23 -23
  54. package/dist/resources/guides/translation.md +1 -1
  55. package/dist/resources/guides/view.md +2 -2
  56. package/dist/resources/guides/workflow.md +9 -9
  57. package/dist/resources/instructions/server.md +19 -0
  58. package/dist/resources/knowledge.js +4 -4
  59. package/dist/resources/read.js +28 -7
  60. package/dist/resources/rules.js +4 -4
  61. package/dist/resources/schema-fingerprint.json +2 -2
  62. package/dist/resources/schemas.js +3 -3
  63. package/dist/server.js +9 -2
  64. package/dist/tools/access.js +1 -1
  65. package/dist/tools/accessRuntime.js +1 -1
  66. package/dist/tools/assistant.js +1 -1
  67. package/dist/tools/bpm.js +3 -3
  68. package/dist/tools/bpmOperations.js +1 -1
  69. package/dist/tools/bpmRuntime.js +2 -2
  70. package/dist/tools/common.js +1 -1
  71. package/dist/tools/entities.js +1 -1
  72. package/dist/tools/externalComponents.js +6 -6
  73. package/dist/tools/files.js +33 -3
  74. package/dist/tools/flows.js +1 -1
  75. package/dist/tools/microservices.js +4 -4
  76. package/dist/tools/mobile.js +1 -1
  77. package/dist/tools/mobileStore.js +5 -5
  78. package/dist/tools/mobileStoreImport.js +3 -3
  79. package/dist/tools/modules.js +1 -1
  80. package/dist/tools/platformInfo.js +9 -9
  81. package/dist/tools/rows.js +2 -2
  82. package/dist/tools/textHookGuard.js +1 -1
  83. package/dist/tools/translations.js +3 -3
  84. package/dist/tools/views.js +2 -2
  85. package/dist/tools/workflows.js +4 -4
  86. package/package.json +4 -2
package/.env.example CHANGED
@@ -79,11 +79,28 @@ TENANT_SWAGGER_URL=
79
79
 
80
80
  # Bos = tum moduller (172 tool / 28 modul). Hazir kumeler: core (veri+mantik, 97), studio
81
81
  # (sayfa tasarimi + kullanici fonksiyonlari, 66), admin (template/organizasyon/deployment, 15). platform modulu (3 tool)
82
- # her kumede vardir. Kume ve tekil modul adi karisik yazilabilir.
82
+ # her kumede vardir. Kume ve tekil modul adi karisik yazilabilir. Uzak baglayici kumeleri: operations (94, isletim)
83
+ # ve development (197, operations + ekran kurma: page, layout, flow, microservice, mobile...).
83
84
  # Ornek: core,studio | entity,row,microservice
84
85
  MODULES=
85
86
 
86
87
  MCP_PORT=5100
88
+ # Yalniz HTTP kipinde. AUTH_MODE=local iken yalniz 127.0.0.1, ::1 ya da localhost olabilir.
89
+ MCP_HOST=127.0.0.1
90
+ # Yol alan araclar (bodyFile, outPath, path...) gateway'in diskini okur/yazar. Bos: local kipte on, passthrough'ta off.
91
+ # on yalniz localhost'u dinleyen gateway'de acilabilir.
92
+ LOCAL_FILES=
93
+
94
+ # AUTH_MODE=oauth: gateway Claude.ai/ChatGPT baglayicilari icin OAuth sunucusudur (docs/adr/0007).
95
+ # OAUTH_ISSUER_URL gateway'in disaridan gorunen koku (https; http yalniz localhost).
96
+ # OAUTH_SECRET en az 32 bayt base64: openssl rand -base64 32. Degeri buraya degil gizli degiskene yazin.
97
+ # OAUTH_REDIRECT_ALLOWLIST virgullu onek listesi: https://claude.ai/api/mcp/auth_callback,https://claude.com/api/mcp/auth_callback
98
+ OAUTH_ISSUER_URL=
99
+ OAUTH_SECRET=
100
+ OAUTH_REDIRECT_ALLOWLIST=
101
+ # Erisim token'i dakika, yenileme token'i gun (girisen itibaren, kaymaz). Bos: 60 ve 30.
102
+ OAUTH_ACCESS_TTL_MINUTES=
103
+ OAUTH_REFRESH_TTL_DAYS=
87
104
 
88
105
  # Uygulama asistanı (Anthropic). docker-compose*.yml Assistant__ApiKey / Assistant__WorkspaceId buradan okur;
89
106
  # anahtar appsettings.json'a ya da compose dosyasına yazılmaz. Kullanıcı anahtarı (sk-ant-usr-…) çalışma alanı kimliği ister.
@@ -47,6 +47,23 @@ ORG_SWAGGER_URL=
47
47
  TENANT_SWAGGER_URL=
48
48
 
49
49
  # Bos = tum moduller (167 tool). Kumeler: core (97) | studio (59) | admin (16).
50
+ # Claude.ai/ChatGPT baglayicisi: operations (94, isletim) | development (197, ikinci dagitim, ekran kurma).
50
51
  MODULES=
51
52
 
52
53
  MCP_PORT=5100
54
+ # Yalniz HTTP kipinde. AUTH_MODE=local iken yalniz 127.0.0.1, ::1 ya da localhost olabilir.
55
+ MCP_HOST=127.0.0.1
56
+ # Yol alan araclar (bodyFile, outPath, path...) gateway'in diskini okur/yazar. Bos: local kipte on, passthrough'ta off.
57
+ # on yalniz localhost'u dinleyen gateway'de acilabilir.
58
+ LOCAL_FILES=
59
+
60
+ # AUTH_MODE=oauth: gateway Claude.ai/ChatGPT baglayicilari icin OAuth sunucusudur (docs/adr/0007).
61
+ # OAUTH_ISSUER_URL gateway'in disaridan gorunen koku (https; http yalniz localhost).
62
+ # OAUTH_SECRET en az 32 bayt base64: openssl rand -base64 32. Degeri buraya degil gizli degiskene yazin.
63
+ # OAUTH_REDIRECT_ALLOWLIST virgullu onek listesi: https://claude.ai/api/mcp/auth_callback,https://claude.com/api/mcp/auth_callback
64
+ OAUTH_ISSUER_URL=
65
+ OAUTH_SECRET=
66
+ OAUTH_REDIRECT_ALLOWLIST=
67
+ # Erisim token'i dakika, yenileme token'i gun (girisen itibaren, kaymaz). Bos: 60 ve 30.
68
+ OAUTH_ACCESS_TTL_MINUTES=
69
+ OAUTH_REFRESH_TTL_DAYS=
package/README.md CHANGED
@@ -100,7 +100,12 @@ hiç yazmayıp çalışma dizininize `PASSWORD=...` içeren bir `.env` koyun.
100
100
  |---|---|---|
101
101
  | `HOST_SUFFIX` | `localhost` | Org çözümündeki alan adı eki |
102
102
  | `DEFAULT_PROJECT` | — | Tool'daki `project` parametresi her zaman ezer |
103
- | `AUTH_MODE` | `local` | `passthrough`: kimlik istemcinin `Authorization` header'ından gelir (stdio kipinde kullanılamaz) |
103
+ | `AUTH_MODE` | `local` | `passthrough`: kimlik istemcinin `Authorization` header'ından gelir; `oauth`: gateway Claude.ai/ChatGPT bağlayıcıları için OAuth sunucusudur ([ADR 0007](docs/adr/0007-uzak-baglayici-oauth.md)). İkisi de stdio kipinde kullanılamaz |
104
+ | `OAUTH_ISSUER_URL` | — | Yalnız `oauth`: gateway'in dışarıdan görünen kökü; https, http yalnız localhost |
105
+ | `OAUTH_SECRET` | — | Yalnız `oauth`: en az 32 bayt, base64. Token'ı şifreler, kayıt ve kodu imzalar; değişirse herkes yeniden giriş yapar |
106
+ | `OAUTH_REDIRECT_ALLOWLIST` | — | Yalnız `oauth`: istemci geri dönüş adresi önekleri, virgülle |
107
+ | `OAUTH_ACCESS_TTL_MINUTES` | `60` | Yalnız `oauth`: erişim token'ının ömrü; istemci süresi dolunca yenileme token'ıyla yenisini alır |
108
+ | `OAUTH_REFRESH_TTL_DAYS` | `30` | Yalnız `oauth`: yenileme token'ının girişten itibaren ömrü; dolunca kullanıcı yeniden giriş yapar |
104
109
  | `MODULES` | hepsi | Tool setini daraltır — aşağıdaki Modüller bölümü |
105
110
  | `POLICY` | `strict` | Politika lint'i: `strict` \| `warn` \| `off` |
106
111
  | `LOG_LEVEL` | `detail` | `detail` gövdeleri de yazar · `summary` gövdesiz · `off` dosya açmaz |
@@ -110,6 +115,8 @@ hiç yazmayıp çalışma dizininize `PASSWORD=...` içeren bir `.env` koyun.
110
115
  | `MAX_RESPONSE_BYTES` | `262144` | Yanıt budama eşiği |
111
116
  | `REQUEST_TIMEOUT_MS` | `100000` | Platform isteklerinin zaman aşımı |
112
117
  | `MCP_PORT` | `5100` | Yalnız HTTP kipinde |
118
+ | `LOCAL_FILES` | `local`'de `on`, `passthrough`'ta `off` | `off` iken yol alan hiçbir araç (`bodyFile`, `path`, `outPath`, `directory`…) gateway'in diskini okumaz ve ona yazmaz; gövde satır içinde verilir. `on` yalnız localhost'u dinleyen gateway'de açılır |
119
+ | `MCP_HOST` | `127.0.0.1` | Yalnız HTTP kipinde dinlenen arayüz. `AUTH_MODE=local` iken yalnız `127.0.0.1`, `::1` ya da `localhost`; imaj `0.0.0.0` verir, bu yüzden yalnız `passthrough` ya da `oauth` kipinde açılır |
113
120
  | `STUDIO_BASE_URL` | — | Yalnız `page_screenshot`: Studio arayüzünün kök adresi |
114
121
  | `SCREENSHOT_BROWSER_PATH` | — | `page_screenshot` için sistemdeki Chromium ikilisi (verilmezse playwright-core'un indirdiği tarayıcı) |
115
122
 
@@ -143,6 +150,8 @@ ya da ikisi karışık (`core,page`). `platform` modülü (3 tool) her kümede v
143
150
  | `core` | 280 | platform, project, application, datasource, entity, row, import, microservice, microfunction, query, workflow, automation, function, dto, view, access, dependency, environment, merge, activity, revision, bpm, bpmRuntime, bpmOperations, bpmRouting, bpmGovernance, bpmReporting, decision, connector, case, caseRuntime, module |
144
151
  | `studio` | 119 | platform, page, theme, component, externalComponent, flow, layout, variable, function, folder, file, import, access, translation, revision |
145
152
  | `admin` | 28 | platform, template, organization, deployment, environment, merge, activity |
153
+ | `operations` | 94 | platform, project, application, datasource, entity, row, query, view, import, folder, file, bpmRuntime, caseRuntime, activity, revision — Claude.ai/ChatGPT bağlayıcısı için (≈ 53 bin token; bütçe testi 60 bin) |
154
+ | `development` | 197 | `operations` + page, layout, component, theme, flow, workflow, microservice, variable, mobile — sohbetten uygulama kuran kullanıcının ikinci bağlayıcısı (≈ 143 bin token; bütçe testi 150 bin; uzak kipte 194) |
146
155
  | (boş) | **354** | 45 modülün tamamı (ölçüm 2026-09-18, `listTools()`) |
147
156
 
148
157
  Bilinmeyen bir modül/küme adı verilirse sunucu açılmaz, geçerli adları listeleyen bir hata yazar.
@@ -178,10 +187,10 @@ Bilinmeyen bir modül/küme adı verilirse sunucu açılmaz, geçerli adları li
178
187
 
179
188
  - **Rehberler:** `platform_guide` tool'u (workflow, microservice, entity, page, component, html,
180
189
  layout, middleware, view, expressions, getting-started, modify-existing) +
181
- `ngapps://guides/*` resource'ları. Bir modülde ilk yazma işleminden önce ilgili rehber
190
+ `zeyrek://guides/*` resource'ları. Bir modülde ilk yazma işleminden önce ilgili rehber
182
191
  okunmalıdır; tool açıklamaları bunu söyler. Komponent davranış bilgisi ayrıca `component_get`
183
192
  çıktısında `knowledge` alanı olarak döner.
184
- - **Altın örnekler:** `ngapps://examples/*` — boş org'da şablon kaynağı.
193
+ - **Altın örnekler:** `zeyrek://examples/*` — boş org'da şablon kaynağı.
185
194
  - **Politika lint'i:** entity/microservice/workflow/automation create/update/preview gövdeleri
186
195
  API'ye gitmeden kurallardan geçer. Block kuralları (MS-001 join'li kaynakta boş selectFields,
187
196
  WF-001 kopuk step grafı, WF-002 workflow'da returnDtoId, WF-005 tip×step matrisi) isteği
@@ -240,6 +249,42 @@ claude mcp add zeyrek-ai --transport http http://localhost:5100/mcp
240
249
  `AUTH_MODE=passthrough` yalnız bu kipte anlamlıdır: kimlik istemcinin `Authorization` header'ından
241
250
  geçer. (PoC boyunca `local` modda test edildi.)
242
251
 
252
+ Kök adres (`/`) ad, sürüm ve MCP yolunu; `/healthz` yalnız `{ "ok": true }` döner. `AUTH_MODE=local` yalnız
253
+ localhost'u dinleyebilir (`MCP_HOST`); dışarıya açılan gateway passthrough ya da oauth kipinde çalışır.
254
+
255
+ ### Claude.ai ve ChatGPT bağlayıcısı (`AUTH_MODE=oauth`)
256
+
257
+ Gateway OAuth yetkilendirme sunucusu olarak açılır; kullanıcı bağlayıcıyı eklerken kendi Zeyrek hesabıyla giriş yapar
258
+ ve araçlar onun yetkisiyle, seçtiği organizasyonda çalışır. Bağlayıcı dağıtımı `MODULES=operations` ile açılır
259
+ (kurulmuş uygulamayı işleten kullanıcı için). Sohbetten uygulama kurmak için aynı imaj ikinci bir adreste
260
+ `MODULES=development` ile açılır: ekran, layout, akış, microservice, mobil kabuk ve `page_screenshot` oradadır. Ayarlar: `OAUTH_ISSUER_URL`, `OAUTH_SECRET`,
261
+ `OAUTH_REDIRECT_ALLOWLIST` (yukarıdaki tablo). Akış ve kararlar: [docs/03](docs/03-kimlik-ve-coklu-kiracilik.md)
262
+ §Token akışı (AuthMode = OAuth), [ADR 0007](docs/adr/0007-uzak-baglayici-oauth.md).
263
+
264
+ - **Claude.ai:** Customize › Connectors › Add custom connector; adres `https://<gateway>/mcp`; Authentication
265
+ "Sign in now", OAuth client "Register automatically". Geri dönüş adresleri:
266
+ `https://claude.ai/api/mcp/auth_callback`, `https://claude.com/api/mcp/auth_callback`.
267
+ - **ChatGPT:** Developer mode açık; Create connector, adres `https://<gateway>/mcp`, Authentication OAuth.
268
+ ChatGPT'nin geri dönüş adresi ilk denemede gateway log'undaki reddedilen kayıttan okunup listeye eklenir.
269
+
270
+ ### Uzak kipte (`LOCAL_FILES=off`) kullanılamayan araçlar
271
+
272
+ Passthrough kipinde varsayılan `LOCAL_FILES=off`'tur: araçlar sunucunun diskini okumaz ve ona yazmaz.
273
+
274
+ - **Listeden çıkanlar** — yalnız yerel dosyayla çalışırlar: `translation_export`, `external_component_scaffold`,
275
+ `external_component_publish`, `mobile_purchase_import`, `mobile_asset_download`, `mobile_asset_preview`.
276
+ - **`file_download`** `outPath`'siz çağrılır: metin dosyası yanıtta döner, ikili dosya indirilemez.
277
+ - **Yol parametresi reddedilenler** — gövdeyi satır içinde verin: `bodyFile` (`page_*`, `flow_*`, `workflow_*`,
278
+ `microservice_*`), `codeFile` (`microfunction_create/update`), `path` (`row_create/update`, `file_upload`,
279
+ `import_analyze`, `mobile_asset_create`), `filePath` (`process_bpmn_update`, `decision_dmn_update`,
280
+ `case_cmmn_update`), `file` (`translation_update`).
281
+ - **`page_screenshot`** imajdaki Chromium'la (`SCREENSHOT_BROWSER_PATH`) çalışır; `STUDIO_BASE_URL` gateway'in ulaşabildiği
282
+ Studio kökü olmalıdır. Bağlayıcının `MODULES=operations` kümesi `page` modülünü açmaz; araç `MODULES=development` ile
283
+ açılan geliştirme bağlayıcısında görünür.
284
+ - **Çıktısı 256 KB ile sınırlananlar** — `outPath` uzakta yoktur: `process_bpmn_get`, `process_documentation_get`,
285
+ `process_export_get`, `decision_dmn_get`, `case_cmmn_get`; `page_screenshot` görüntüyü satır içinde döner,
286
+ `row_export` Sürücü kopyasını kullanır.
287
+
243
288
  ---
244
289
 
245
290
  ## Geliştirme (repo)
@@ -268,8 +313,8 @@ npm run docs:lint
268
313
  ```
269
314
 
270
315
  Şema kaynakları (API'ler ayaktayken): `npm run generate-schemas`, Swagger'dan seçili komut
271
- şemalarını `src/resources/schemas/` altına yazar; sunucu bunları `ngapps://schemas/*` resource'ları
272
- olarak yayınlar (`ngapps://schemas/index` dizindir). Swagger adresi sırayla denenir:
316
+ şemalarını `src/resources/schemas/` altına yazar; sunucu bunları `zeyrek://schemas/*` resource'ları
317
+ olarak yayınlar (`zeyrek://schemas/index` dizindir). Swagger adresi sırayla denenir:
273
318
  `ORG_SWAGGER_URL` / `TENANT_SWAGGER_URL` override'ları → `{API_BASE_URL}/swagger/v1/swagger.json`
274
319
  → `localhost:3000` frontend proxy'si.
275
320
 
@@ -0,0 +1,57 @@
1
+ import { createHmac } from 'node:crypto';
2
+ import { InvalidClientMetadataError } from '@modelcontextprotocol/sdk/server/auth/errors.js';
3
+ import { open, seal } from './tokenSeal.js';
4
+ /**
5
+ * K6: önek düz metinle karşılaştırılırsa `http://localhost` öneki `http://localhost.saldirgan.example`'ı da kabul eder.
6
+ * Şema ve host tam eşleşir; önekte port yoksa her port (loopback istemcileri rastgele port kullanır, RFC 8252 §7.3),
7
+ * yol önek olarak eşleşir.
8
+ */
9
+ export function redirectAllowed(uri, allowlist) {
10
+ let candidate;
11
+ try {
12
+ candidate = new URL(uri);
13
+ }
14
+ catch {
15
+ return false;
16
+ }
17
+ return allowlist.some(entry => {
18
+ const allowed = new URL(entry);
19
+ return candidate.protocol === allowed.protocol
20
+ && candidate.hostname === allowed.hostname
21
+ && (allowed.port === '' || candidate.port === allowed.port)
22
+ && candidate.pathname.startsWith(allowed.pathname);
23
+ });
24
+ }
25
+ /**
26
+ * K3: istemci kaydı sunucuda tutulmaz; `client_id` kaydın kendisidir (mühürlü). Gizli istemcinin parolası saklanmaz,
27
+ * `client_id`'den HMAC ile her seferinde yeniden türetilir. `OAUTH_SECRET` değişirse kayıtlar geçersizleşir (ADR 0007).
28
+ */
29
+ export class SealedClientsStore {
30
+ settings;
31
+ constructor(settings) {
32
+ this.settings = settings;
33
+ }
34
+ getClient(clientId) {
35
+ const record = open('client', clientId, this.settings.secret);
36
+ return record ? this.withCredentials(clientId, record) : undefined;
37
+ }
38
+ registerClient(client) {
39
+ const rejected = client.redirect_uris.filter(uri => !redirectAllowed(String(uri), this.settings.redirectAllowlist));
40
+ if (rejected.length > 0) {
41
+ throw new InvalidClientMetadataError(`redirect_uri izin listesinde değil: ${rejected.join(', ')}. Gateway yöneticisi OAUTH_REDIRECT_ALLOWLIST'e ekleyebilir.`);
42
+ }
43
+ const { client_secret: _secret, client_secret_expires_at: _expires, ...record } = client;
44
+ const clientId = seal('client', record, this.settings.secret);
45
+ return { ...this.withCredentials(clientId, record), client_id_issued_at: Math.floor(Date.now() / 1000) };
46
+ }
47
+ withCredentials(clientId, record) {
48
+ if (record.token_endpoint_auth_method === 'none')
49
+ return { ...record, client_id: clientId };
50
+ return {
51
+ ...record,
52
+ client_id: clientId,
53
+ client_secret: createHmac('sha256', this.settings.secret).update(clientId).digest('base64url'),
54
+ client_secret_expires_at: 0
55
+ };
56
+ }
57
+ }
@@ -0,0 +1,115 @@
1
+ import { InvalidGrantError, InvalidTokenError } from '@modelcontextprotocol/sdk/server/auth/errors.js';
2
+ import { SealedClientsStore } from './clientRegistry.js';
3
+ import { sendLoginPage } from './loginPage.js';
4
+ import { open, seal } from './tokenSeal.js';
5
+ export const loginRequestMaxAgeSeconds = 600;
6
+ export const codeLifetimeSeconds = 60;
7
+ const nowSeconds = () => Math.floor(Date.now() / 1000);
8
+ /**
9
+ * Uzak bağlayıcı planı 02–03 (K1): yetkilendirme sunucusu gateway'dedir; platformun `/connect/token`'ı OAuth konuşmaz.
10
+ * Değişkenlik ekseni kimliği kimin doğruladığıdır — backend bir OAuth sunucusu olursa bu sınıfın yerine SDK'nın
11
+ * `ProxyOAuthServerProvider`'ı takılır, `/mcp` tarafı değişmez (ADR 0007).
12
+ */
13
+ export class GatewayOAuthProvider {
14
+ settings;
15
+ defaultOrganization;
16
+ clientsStore;
17
+ usedCodes = new Map();
18
+ constructor(settings, defaultOrganization) {
19
+ this.settings = settings;
20
+ this.defaultOrganization = defaultOrganization;
21
+ this.clientsStore = new SealedClientsStore(settings);
22
+ }
23
+ async authorize(client, params, response) {
24
+ const request = {
25
+ clientId: client.client_id,
26
+ clientName: client.client_name ?? 'MCP istemcisi',
27
+ redirectUri: params.redirectUri,
28
+ codeChallenge: params.codeChallenge,
29
+ ...(params.state === undefined ? {} : { state: params.state }),
30
+ ...(params.scopes === undefined ? {} : { scopes: params.scopes }),
31
+ iat: nowSeconds()
32
+ };
33
+ sendLoginPage(response, {
34
+ clientName: request.clientName,
35
+ redirectHost: new URL(request.redirectUri).host,
36
+ organization: this.defaultOrganization,
37
+ request: seal('login', request, this.settings.secret)
38
+ });
39
+ }
40
+ /** Giriş formunun mühürlü isteği; açılmıyorsa ya da 10 dakikadan eskiyse `undefined`. */
41
+ openLoginRequest(sealed) {
42
+ const request = open('login', sealed, this.settings.secret);
43
+ return request && nowSeconds() - request.iat <= loginRequestMaxAgeSeconds ? request : undefined;
44
+ }
45
+ issueCode(request, organization, platformToken, tokenExp) {
46
+ const code = {
47
+ platformToken,
48
+ organization,
49
+ clientId: request.clientId,
50
+ redirectUri: request.redirectUri,
51
+ codeChallenge: request.codeChallenge,
52
+ tokenExp,
53
+ exp: nowSeconds() + codeLifetimeSeconds
54
+ };
55
+ return seal('code', code, this.settings.secret);
56
+ }
57
+ async challengeForAuthorizationCode(client, authorizationCode) {
58
+ return this.openCode(client, authorizationCode).codeChallenge;
59
+ }
60
+ async exchangeAuthorizationCode(client, authorizationCode, _codeVerifier, redirectUri) {
61
+ const code = this.openCode(client, authorizationCode);
62
+ if (redirectUri !== undefined && redirectUri !== code.redirectUri)
63
+ throw new InvalidGrantError('redirect_uri does not match the authorization request');
64
+ this.markUsed(authorizationCode, code.exp);
65
+ const now = nowSeconds();
66
+ const refresh = { platformToken: code.platformToken, organization: code.organization, clientId: code.clientId, exp: Math.min(code.tokenExp, now + this.settings.refreshTtlSeconds) };
67
+ return this.issue(refresh, seal('refresh', refresh, this.settings.secret));
68
+ }
69
+ /**
70
+ * Yenileme token'ı kaymaz: aynı token geri döner ve girişteki son tarihini korur. Durumsuz gateway eski bir yenileme
71
+ * token'ını iptal edemediği için her yenilemede yenisini vermek (rotation) güvenlik kazandırmaz, yalnız ömrü uzatırdı.
72
+ */
73
+ async exchangeRefreshToken(client, refreshToken) {
74
+ const refresh = open('refresh', refreshToken, this.settings.secret);
75
+ if (!refresh || refresh.clientId !== client.client_id || refresh.exp < nowSeconds()) {
76
+ throw new InvalidGrantError('Refresh token is invalid, expired or belongs to another client; sign in again');
77
+ }
78
+ return this.issue(refresh, refreshToken);
79
+ }
80
+ issue(refresh, refreshToken) {
81
+ const now = nowSeconds();
82
+ const access = { ...refresh, exp: Math.min(refresh.exp, now + this.settings.accessTtlSeconds) };
83
+ return { access_token: seal('access', access, this.settings.secret), token_type: 'bearer', expires_in: Math.max(0, access.exp - now), refresh_token: refreshToken };
84
+ }
85
+ async verifyAccessToken(token) {
86
+ const payload = open('access', token, this.settings.secret);
87
+ // Mesaj `WWW-Authenticate` başlığına yazılır (SDK `bearerAuth.js`); başlıkta ASCII dışı karakter Express'te
88
+ // fırlatır ve yanıt hiç gitmez — istemci asılı kalır (ölçüldü 2026-11-12, oauth-discovery testi zaman aşımı).
89
+ if (!payload || typeof payload.platformToken !== 'string' || typeof payload.exp !== 'number') {
90
+ throw new InvalidTokenError('Token was not issued by this gateway or is corrupt');
91
+ }
92
+ return {
93
+ token,
94
+ clientId: payload.clientId,
95
+ scopes: [],
96
+ expiresAt: payload.exp,
97
+ extra: { platformToken: payload.platformToken, organization: payload.organization }
98
+ };
99
+ }
100
+ openCode(client, authorizationCode) {
101
+ const code = open('code', authorizationCode, this.settings.secret);
102
+ if (!code || code.clientId !== client.client_id || code.exp < nowSeconds() || this.usedCodes.has(authorizationCode)) {
103
+ throw new InvalidGrantError('Authorization code is invalid, expired or already used');
104
+ }
105
+ return code;
106
+ }
107
+ /** K3: kod durumsuzdur; ikinci kullanımı yalnız bu küme engeller — dağıtım tek replika olmalıdır. */
108
+ markUsed(authorizationCode, exp) {
109
+ const now = nowSeconds();
110
+ for (const [used, until] of this.usedCodes)
111
+ if (until < now)
112
+ this.usedCodes.delete(used);
113
+ this.usedCodes.set(authorizationCode, exp);
114
+ }
115
+ }
@@ -0,0 +1,60 @@
1
+ const escapeHtml = (value) => value
2
+ .replaceAll('&', '&amp;')
3
+ .replaceAll('<', '&lt;')
4
+ .replaceAll('>', '&gt;')
5
+ .replaceAll('"', '&quot;')
6
+ .replaceAll("'", '&#39;');
7
+ /**
8
+ * Gateway'in tek HTML yüzeyi (planı 03, K5). Harici kaynak yok; parola alanı hiçbir zaman geri doldurulmaz. Başlıklar:
9
+ * çerçevelenemez (tıklama hırsızlığı), önbelleğe alınmaz, Referer'a kod sızmaz. `form-action` konmaz: Chrome onu formdan
10
+ * sonraki yönlendirmeye de uygular ve istemcinin geri dönüş adresine gidişi keser.
11
+ */
12
+ export function sendLoginPage(response, input, status = 200) {
13
+ const error = input.error ? `<p class="error" role="alert">${escapeHtml(input.error)}</p>` : '';
14
+ response
15
+ .status(status)
16
+ .set({
17
+ 'Content-Type': 'text/html; charset=utf-8',
18
+ 'Cache-Control': 'no-store',
19
+ 'X-Frame-Options': 'DENY',
20
+ 'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'",
21
+ 'Referrer-Policy': 'no-referrer'
22
+ })
23
+ .send(`<!doctype html>
24
+ <html lang="tr">
25
+ <head>
26
+ <meta charset="utf-8">
27
+ <meta name="viewport" content="width=device-width,initial-scale=1">
28
+ <title>Zeyrek'e giriş</title>
29
+ <style>
30
+ :root { color-scheme: light dark; --bg: #f5f6f8; --card: #fff; --fg: #15181d; --muted: #59616d; --line: #d8dce2; --accent: #1f5eff; --on-accent: #fff; --error: #b42318; }
31
+ @media (prefers-color-scheme: dark) { :root { --bg: #111418; --card: #1a1e24; --fg: #e9ecf0; --muted: #9aa3ae; --line: #2d333b; --accent: #7aa2ff; --on-accent: #0b1220; --error: #ff8a80; } }
32
+ * { box-sizing: border-box; }
33
+ body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: var(--bg); color: var(--fg); font: 15px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; padding: 16px; }
34
+ main { width: 100%; max-width: 380px; background: var(--card); border: 1px solid var(--line); border-radius: 10px; padding: 28px 24px; display: flex; flex-direction: column; gap: 18px; }
35
+ h1 { margin: 0; font-size: 1.3rem; }
36
+ p { margin: 0; color: var(--muted); }
37
+ form { display: flex; flex-direction: column; gap: 14px; }
38
+ label { display: flex; flex-direction: column; gap: 6px; font-weight: 500; }
39
+ input { font: inherit; padding: 9px 11px; border: 1px solid var(--line); border-radius: 6px; background: transparent; color: inherit; }
40
+ input:focus-visible, button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
41
+ button { font: inherit; font-weight: 600; padding: 10px; border: 0; border-radius: 6px; background: var(--accent); color: var(--on-accent); cursor: pointer; }
42
+ .error { color: var(--error); }
43
+ </style>
44
+ </head>
45
+ <body>
46
+ <main>
47
+ <h1>Zeyrek'e giriş</h1>
48
+ <p><strong>${escapeHtml(input.clientName)}</strong> (${escapeHtml(input.redirectHost)}) Zeyrek hesabınızla bağlanmak istiyor. Araçlar sizin yetkilerinizle çalışır.</p>
49
+ ${error}
50
+ <form method="post" action="/authorize/login">
51
+ <input type="hidden" name="request" value="${escapeHtml(input.request)}">
52
+ <label>Organizasyon<input name="organization" id="organization" value="${escapeHtml(input.organization)}" autocomplete="organization" required></label>
53
+ <label>Kullanıcı adı<input name="username" id="username" value="${escapeHtml(input.username ?? '')}" autocomplete="username" required></label>
54
+ <label>Parola<input name="password" id="password" type="password" autocomplete="current-password" required></label>
55
+ <button type="submit">Giriş yap</button>
56
+ </form>
57
+ </main>
58
+ </body>
59
+ </html>`);
60
+ }
@@ -0,0 +1,56 @@
1
+ import { PlatformApiError } from '../platform/errors.js';
2
+ import { exchangePassword, jwtExpiry } from '../platform/token.js';
3
+ import { sendLoginPage } from './loginPage.js';
4
+ import { LoginThrottle } from './loginThrottle.js';
5
+ const organizationPattern = /^[a-z0-9][a-z0-9-]{0,62}$/i;
6
+ /**
7
+ * Planı 03 (K5): giriş sayfasının formu. Parola yalnız platformun `/connect/token` isteğinin gövdesine gider; sayfa
8
+ * yeniden çizilirken parola alanı boş gelir, kullanıcı adı korunur. Başarılı girişte istemcinin kayıtlı adresine kod ve
9
+ * `state` ile dönülür.
10
+ */
11
+ export function loginRoute(config, provider) {
12
+ const throttle = new LoginThrottle();
13
+ return async (request, response) => {
14
+ const body = (request.body ?? {});
15
+ const field = (name) => typeof body[name] === 'string' ? body[name].trim() : '';
16
+ const login = provider.openLoginRequest(field('request'));
17
+ const organization = field('organization');
18
+ const username = field('username');
19
+ const password = typeof body.password === 'string' ? body.password : '';
20
+ if (!login) {
21
+ response.status(400).type('text/plain; charset=utf-8').send('Giriş isteği geçersiz ya da süresi doldu (10 dk). Bağlayıcıdan yeniden bağlanın.');
22
+ return;
23
+ }
24
+ const page = (error, status = 200) => sendLoginPage(response, {
25
+ clientName: login.clientName,
26
+ redirectHost: new URL(login.redirectUri).host,
27
+ organization: organization || config.organization,
28
+ username,
29
+ request: field('request'),
30
+ error
31
+ }, status);
32
+ if (!organizationPattern.test(organization) || username === '' || password === '') {
33
+ page('Organizasyon, kullanıcı adı ve parola gerekli; organizasyon yalnız harf, rakam ve tire içerir.');
34
+ return;
35
+ }
36
+ if (!throttle.allow(organization, username)) {
37
+ page('Bu hesap için çok fazla deneme yapıldı. Bir dakika sonra yeniden deneyin.', 429);
38
+ return;
39
+ }
40
+ let platformToken;
41
+ try {
42
+ platformToken = await exchangePassword(config, organization, username, password);
43
+ }
44
+ catch (error) {
45
+ const rejected = error instanceof PlatformApiError && error.status !== undefined && error.status >= 400 && error.status < 500;
46
+ page(rejected ? 'Organizasyon, kullanıcı adı ya da parola hatalı.' : 'Platforma ulaşılamadı; biraz sonra yeniden deneyin.', rejected ? 200 : 502);
47
+ return;
48
+ }
49
+ const tokenExp = jwtExpiry(platformToken) ?? Math.floor(Date.now() / 1000) + 300;
50
+ const target = new URL(login.redirectUri);
51
+ target.searchParams.set('code', provider.issueCode(login, organization.toLowerCase(), platformToken, tokenExp));
52
+ if (login.state !== undefined)
53
+ target.searchParams.set('state', login.state);
54
+ response.set('Cache-Control', 'no-store').redirect(302, target.href);
55
+ };
56
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Planı 03: parola denemesi hesap başına sınırlanır (organizasyon + kullanıcı adı), IP başına değil — gateway bir ters
3
+ * vekilin arkasında durur ve IP herkes için aynı görünür. Sayaç bellektedir; dağıtım tek replikadır (K3).
4
+ */
5
+ export class LoginThrottle {
6
+ limit;
7
+ windowMs;
8
+ now;
9
+ attempts = new Map();
10
+ constructor(limit = 10, windowMs = 60_000, now = Date.now) {
11
+ this.limit = limit;
12
+ this.windowMs = windowMs;
13
+ this.now = now;
14
+ }
15
+ /** Deneme sayılır; sınır aşıldıysa `false`. */
16
+ allow(organization, username) {
17
+ const key = `${organization.toLowerCase()}\u0000${username.toLowerCase()}`;
18
+ const since = this.now() - this.windowMs;
19
+ const recent = (this.attempts.get(key) ?? []).filter(at => at > since);
20
+ if (recent.length >= this.limit) {
21
+ this.attempts.set(key, recent);
22
+ return false;
23
+ }
24
+ recent.push(this.now());
25
+ this.attempts.set(key, recent);
26
+ if (this.attempts.size > 10_000) {
27
+ for (const [entry, times] of this.attempts)
28
+ if (times.every(at => at <= since))
29
+ this.attempts.delete(entry);
30
+ }
31
+ return true;
32
+ }
33
+ }
@@ -0,0 +1,25 @@
1
+ import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
2
+ const ivBytes = 12;
3
+ const tagBytes = 16;
4
+ export function seal(purpose, payload, secret) {
5
+ const iv = randomBytes(ivBytes);
6
+ const cipher = createCipheriv('aes-256-gcm', secret, iv);
7
+ cipher.setAAD(Buffer.from(purpose));
8
+ const body = Buffer.concat([cipher.update(JSON.stringify(payload), 'utf8'), cipher.final()]);
9
+ return Buffer.concat([iv, cipher.getAuthTag(), body]).toString('base64url');
10
+ }
11
+ export function open(purpose, token, secret) {
12
+ const bytes = Buffer.from(token, 'base64url');
13
+ if (bytes.byteLength <= ivBytes + tagBytes)
14
+ return undefined;
15
+ try {
16
+ const decipher = createDecipheriv('aes-256-gcm', secret, bytes.subarray(0, ivBytes));
17
+ decipher.setAAD(Buffer.from(purpose));
18
+ decipher.setAuthTag(bytes.subarray(ivBytes, ivBytes + tagBytes));
19
+ const text = Buffer.concat([decipher.update(bytes.subarray(ivBytes + tagBytes)), decipher.final()]).toString('utf8');
20
+ return JSON.parse(text);
21
+ }
22
+ catch {
23
+ return undefined;
24
+ }
25
+ }
package/dist/config.js CHANGED
@@ -109,6 +109,19 @@ export const modulePresets = {
109
109
  "assistant",
110
110
  ],
111
111
  admin: ["platform", "template", "organization", "deployment", "environment", "customDomain", "merge", "activity"],
112
+ // Uzak bağlayıcı planı 04 (K7, iş sahibi onayı 2026-11-12): Claude.ai/ChatGPT bağlayıcısı kurulmuş uygulamayı işleten
113
+ // kullanıcı içindir — veri, kayıt, süreç görevi. `folder` planı 09'un uygulama notları (`ai-notlari/`) için gerekir.
114
+ // Ölçüldü 2026-11-12: 94 tool, ≈ 53 bin token (`npm run footprint`);
115
+ // bütçesini `test/operations-budget.test.ts` korur. Adı `connector` değildir: o bir modül adı ve küme önce çözülür.
116
+ operations: ["platform", "project", "application", "datasource", "entity", "row", "query", "view", "import", "folder", "file", "bpmRuntime", "caseRuntime", "activity", "revision"],
117
+ // Uzak bağlayıcı planı 10 (K13, iş sahibi seçimi 2026-11-12): sohbetten uygulama kuran kullanıcı için ikinci bağlayıcı
118
+ // dağıtımı. `operations`'ın tamamı + ekran kurma ve doğrulama yüzeyi; `operations` 94 tool'da kalır. Ölçüm ve bütçe
119
+ // `test/operations-budget.test.ts`'te; rakamlar planın 10. dosyasında.
120
+ development: [
121
+ "platform", "project", "application", "datasource", "entity", "row", "query", "view", "import", "folder", "file",
122
+ "bpmRuntime", "caseRuntime", "activity", "revision",
123
+ "page", "layout", "component", "theme", "flow", "workflow", "microservice", "variable", "mobile",
124
+ ],
112
125
  };
113
126
  function expandModuleNames(entries) {
114
127
  const modules = [];
@@ -134,7 +147,7 @@ const environmentSchema = z.object({
134
147
  HOST_SUFFIX: z.string().min(1).default("localhost"),
135
148
  DEFAULT_ENVIRONMENT: z.string().min(1),
136
149
  DEFAULT_PROJECT: z.string().optional(),
137
- AUTH_MODE: z.enum(["local", "passthrough"]).default("local"),
150
+ AUTH_MODE: z.enum(["local", "passthrough", "oauth"]).default("local"),
138
151
  TOKEN: z.string().optional(),
139
152
  USERNAME: z.string().optional(),
140
153
  PASSWORD: z.string().optional(),
@@ -148,6 +161,13 @@ const environmentSchema = z.object({
148
161
  LOG_MAX_BODY_CHARS: z.coerce.number().int().positive().default(2000),
149
162
  GAP_REPORT_WEBHOOK_URL: z.string().url().optional(),
150
163
  MCP_PORT: z.coerce.number().int().positive().default(5100),
164
+ MCP_HOST: z.string().min(1).default("127.0.0.1"),
165
+ LOCAL_FILES: z.enum(["on", "off"]).optional(),
166
+ OAUTH_ISSUER_URL: z.string().url().optional(),
167
+ OAUTH_SECRET: z.string().min(1).optional(),
168
+ OAUTH_REDIRECT_ALLOWLIST: z.string().optional(),
169
+ OAUTH_ACCESS_TTL_MINUTES: z.coerce.number().int().positive().default(60),
170
+ OAUTH_REFRESH_TTL_DAYS: z.coerce.number().int().positive().default(30),
151
171
  STUDIO_BASE_URL: z.string().url().optional(),
152
172
  SCREENSHOT_BROWSER_PATH: z.string().min(1).optional(),
153
173
  SCREENSHOT_QUEUE_WAIT_MS: z.coerce.number().int().positive().default(120000),
@@ -156,6 +176,12 @@ const environmentSchema = z.object({
156
176
  MCP_TOKEN_TTL_MINUTES: z.coerce.number().int().positive().optional(),
157
177
  });
158
178
  export const environmentKeys = Object.keys(environmentSchema.shape);
179
+ /**
180
+ * Uzak bağlayıcı incelemesi B2 (2026-11-12): local kipte gateway kendi servis hesabıyla girer ve `/mcp` kimlik sormaz.
181
+ * Bu kip dış arayüzü dinlerse adresi bilen herkes o hesabın yetkisini alır; docs/03 §Güvenlik notları 2 bunu
182
+ * yasaklıyordu ama kod denetlemiyordu.
183
+ */
184
+ const localHosts = new Set(["127.0.0.1", "::1", "localhost"]);
159
185
  /**
160
186
  * Makine kullanıcısının adı. Windows `USER`/`LOGNAME` tanımlamaz — o ikisi POSIX kabuklarına
161
187
  * aittir — bu yüzden `USERNAME` gölgelemesinin HER ZAMAN yaşandığı platformda kıyaslanacak ad
@@ -212,6 +238,41 @@ function withoutEmptyValues(env) {
212
238
  }
213
239
  return copy;
214
240
  }
241
+ /**
242
+ * İstemci kaydı (DCR) her geri dönüş adresini kabul ederse sahte bir istemci kullanıcıyı giriş sayfasına yollayıp kodu
243
+ * kendi adresine alabilir (oltalama); K6 bu yüzden önek listesidir. Issuer kuralı SDK'nınkiyle aynıdır
244
+ * (`@modelcontextprotocol/sdk/server/auth/router.js` `checkIssuerUrl`): https, yalnız localhost'ta http.
245
+ */
246
+ function oauthSettings(values) {
247
+ if (!values.OAUTH_ISSUER_URL) {
248
+ throw new Error("AUTH_MODE=oauth için OAUTH_ISSUER_URL zorunludur: gateway'in dışarıdan görünen kökü (https://…).");
249
+ }
250
+ const issuer = new URL(values.OAUTH_ISSUER_URL);
251
+ if (issuer.protocol !== "https:" && issuer.hostname !== "localhost" && issuer.hostname !== "127.0.0.1") {
252
+ throw new Error(`OAUTH_ISSUER_URL https olmalıdır; http yalnız localhost için kabul edilir (verilen: ${issuer.href}).`);
253
+ }
254
+ if (!values.OAUTH_SECRET) {
255
+ throw new Error("AUTH_MODE=oauth için OAUTH_SECRET zorunludur: en az 32 bayt rastgele değer, base64 (openssl rand -base64 32).");
256
+ }
257
+ const secret = Buffer.from(values.OAUTH_SECRET, "base64");
258
+ if (secret.byteLength < 32) {
259
+ throw new Error(`OAUTH_SECRET en az 32 bayt olmalıdır (base64 çözülünce ${secret.byteLength} bayt).`);
260
+ }
261
+ const redirectAllowlist = (values.OAUTH_REDIRECT_ALLOWLIST ?? "")
262
+ .split(",")
263
+ .map((entry) => entry.trim())
264
+ .filter((entry) => entry.length > 0);
265
+ if (redirectAllowlist.length === 0) {
266
+ throw new Error("AUTH_MODE=oauth için OAUTH_REDIRECT_ALLOWLIST zorunludur: istemcilerin geri dönüş adresi önekleri, virgülle.");
267
+ }
268
+ return {
269
+ issuerUrl: issuer.href,
270
+ secret: secret.subarray(0, 32),
271
+ redirectAllowlist,
272
+ accessTtlSeconds: values.OAUTH_ACCESS_TTL_MINUTES * 60,
273
+ refreshTtlSeconds: values.OAUTH_REFRESH_TTL_DAYS * 24 * 3600,
274
+ };
275
+ }
215
276
  export function loadConfig(env) {
216
277
  const parsed = environmentSchema.safeParse(withoutEmptyValues(env));
217
278
  if (!parsed.success) {
@@ -226,10 +287,21 @@ export function loadConfig(env) {
226
287
  (!values.USERNAME || !values.PASSWORD)) {
227
288
  throw new Error("AUTH_MODE=local için TOKEN ya da USERNAME + PASSWORD zorunludur.");
228
289
  }
290
+ const oauth = values.AUTH_MODE === "oauth" ? oauthSettings(values) : undefined;
291
+ const ignoredCredentials = values.AUTH_MODE === "oauth"
292
+ ? ["TOKEN", "USERNAME", "PASSWORD"].filter((key) => values[key] !== undefined)
293
+ : [];
229
294
  if (values.AUTH_MODE === "passthrough" &&
230
295
  (values.TOKEN || values.USERNAME || values.PASSWORD)) {
231
296
  throw new Error("AUTH_MODE=passthrough iken TOKEN/USERNAME/PASSWORD tanımlanamaz — kimlik istemciden gelir.");
232
297
  }
298
+ if (values.AUTH_MODE === "local" && !localHosts.has(values.MCP_HOST)) {
299
+ throw new Error(`AUTH_MODE=local yalnız localhost'u dinleyebilir (MCP_HOST=${values.MCP_HOST}); internete açılacak gateway passthrough ya da oauth kipinde çalışır (zeyrek-mcp/docs/03-kimlik-ve-coklu-kiracilik.md §Güvenlik notları).`);
300
+ }
301
+ const localFiles = values.LOCAL_FILES ?? (values.AUTH_MODE === "local" ? "on" : "off");
302
+ if (localFiles === "on" && !localHosts.has(values.MCP_HOST)) {
303
+ throw new Error(`LOCAL_FILES=on yalnız localhost'u dinleyen gateway'de açılabilir (MCP_HOST=${values.MCP_HOST}); dışarıya açık gateway'de yol alan araçlar sunucunun diskini okur ve ona yazar.`);
304
+ }
233
305
  const requested = values.MODULES
234
306
  ? values.MODULES.split(",")
235
307
  .map((name) => name.trim())
@@ -247,9 +319,9 @@ export function loadConfig(env) {
247
319
  defaultEnvironment: values.DEFAULT_ENVIRONMENT,
248
320
  defaultProject: values.DEFAULT_PROJECT,
249
321
  authMode: values.AUTH_MODE,
250
- token: values.TOKEN,
251
- username: values.USERNAME,
252
- password: values.PASSWORD,
322
+ token: oauth ? undefined : values.TOKEN,
323
+ username: oauth ? undefined : values.USERNAME,
324
+ password: oauth ? undefined : values.PASSWORD,
253
325
  policyMode: values.POLICY,
254
326
  maxResponseBytes: values.MAX_RESPONSE_BYTES,
255
327
  requestTimeoutMs: values.REQUEST_TIMEOUT_MS,
@@ -260,6 +332,10 @@ export function loadConfig(env) {
260
332
  logMaxBodyChars: values.LOG_MAX_BODY_CHARS,
261
333
  gapReportWebhookUrl: values.GAP_REPORT_WEBHOOK_URL,
262
334
  port: values.MCP_PORT,
335
+ host: values.MCP_HOST,
336
+ localFiles,
337
+ oauth,
338
+ ignoredCredentials,
263
339
  studioBaseUrl: values.STUDIO_BASE_URL?.replace(/\/+$/, ""),
264
340
  screenshotBrowserPath: values.SCREENSHOT_BROWSER_PATH,
265
341
  screenshotQueueWaitMs: values.SCREENSHOT_QUEUE_WAIT_MS,