create-mercato-app 0.7.1-develop.7150.1.c1941e0c22 → 0.7.1-develop.7152.1.a69e92f9c9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/agentic/shared/ai/harness/cases.json +4 -2
- package/dist/agentic/guides/module-facts.json +828 -149
- package/dist/agentic/guides/module-facts.v2.json +828 -149
- package/dist/agentic/guides/modules/ai_assistant/index.md +1 -1
- package/dist/agentic/guides/modules/api_docs/index.md +1 -1
- package/dist/agentic/guides/modules/api_keys/index.md +1 -1
- package/dist/agentic/guides/modules/attachments/index.md +1 -1
- package/dist/agentic/guides/modules/audit_logs/index.md +1 -1
- package/dist/agentic/guides/modules/auth/index.md +1 -1
- package/dist/agentic/guides/modules/business_rules/index.md +1 -1
- package/dist/agentic/guides/modules/catalog/index.md +1 -1
- package/dist/agentic/guides/modules/channel_apns/index.md +1 -1
- package/dist/agentic/guides/modules/channel_discord/index.md +1 -1
- package/dist/agentic/guides/modules/channel_expo/index.md +1 -1
- package/dist/agentic/guides/modules/channel_fcm/index.md +1 -1
- package/dist/agentic/guides/modules/channel_gmail/index.md +1 -1
- package/dist/agentic/guides/modules/channel_imap/index.md +1 -1
- package/dist/agentic/guides/modules/channel_resend/acl-features.md +12 -0
- package/dist/agentic/guides/modules/channel_resend/contribution-resolutions.md +11 -0
- package/dist/agentic/guides/modules/channel_resend/di-registrations-rich.md +12 -0
- package/dist/agentic/guides/modules/channel_resend/exact-override-targets.md +16 -0
- package/dist/agentic/guides/modules/channel_resend/index.md +18 -0
- package/dist/agentic/guides/modules/channel_resend/owned-contract-module-metadata.md +11 -0
- package/dist/agentic/guides/modules/channel_resend/setup.md +11 -0
- package/dist/agentic/guides/modules/channel_resend/umes-contributions.md +11 -0
- package/dist/agentic/guides/modules/channel_ses/acl-features.md +12 -0
- package/dist/agentic/guides/modules/channel_ses/contribution-resolutions.md +11 -0
- package/dist/agentic/guides/modules/channel_ses/di-registrations-rich.md +12 -0
- package/dist/agentic/guides/modules/channel_ses/exact-override-targets.md +16 -0
- package/dist/agentic/guides/modules/channel_ses/index.md +18 -0
- package/dist/agentic/guides/modules/channel_ses/owned-contract-module-metadata.md +11 -0
- package/dist/agentic/guides/modules/channel_ses/setup.md +11 -0
- package/dist/agentic/guides/modules/channel_ses/umes-contributions.md +11 -0
- package/dist/agentic/guides/modules/checkout/index.md +1 -1
- package/dist/agentic/guides/modules/communication_channels/di-registrations-rich.md +10 -9
- package/dist/agentic/guides/modules/communication_channels/exact-override-targets.md +12 -11
- package/dist/agentic/guides/modules/communication_channels/index.md +1 -1
- package/dist/agentic/guides/modules/communication_channels/setup.md +1 -1
- package/dist/agentic/guides/modules/configs/index.md +1 -1
- package/dist/agentic/guides/modules/content/index.md +1 -1
- package/dist/agentic/guides/modules/currencies/index.md +1 -1
- package/dist/agentic/guides/modules/customer_accounts/index.md +1 -1
- package/dist/agentic/guides/modules/customers/index.md +1 -1
- package/dist/agentic/guides/modules/dashboards/index.md +1 -1
- package/dist/agentic/guides/modules/data_sync/index.md +1 -1
- package/dist/agentic/guides/modules/design_system/index.md +1 -1
- package/dist/agentic/guides/modules/devices/index.md +1 -1
- package/dist/agentic/guides/modules/dictionaries/index.md +1 -1
- package/dist/agentic/guides/modules/directory/index.md +1 -1
- package/dist/agentic/guides/modules/documents/index.md +1 -1
- package/dist/agentic/guides/modules/entities/index.md +1 -1
- package/dist/agentic/guides/modules/eudr/index.md +1 -1
- package/dist/agentic/guides/modules/events/index.md +1 -1
- package/dist/agentic/guides/modules/feature_toggles/index.md +1 -1
- package/dist/agentic/guides/modules/gateway_stripe/index.md +1 -1
- package/dist/agentic/guides/modules/generators/index.md +1 -1
- package/dist/agentic/guides/modules/inbox_ops/index.md +1 -1
- package/dist/agentic/guides/modules/integrations/index.md +1 -1
- package/dist/agentic/guides/modules/messages/index.md +1 -1
- package/dist/agentic/guides/modules/notifications/index.md +1 -1
- package/dist/agentic/guides/modules/onboarding/index.md +1 -1
- package/dist/agentic/guides/modules/payment_gateways/index.md +1 -1
- package/dist/agentic/guides/modules/perspectives/index.md +1 -1
- package/dist/agentic/guides/modules/planner/index.md +1 -1
- package/dist/agentic/guides/modules/portal/index.md +1 -1
- package/dist/agentic/guides/modules/progress/index.md +1 -1
- package/dist/agentic/guides/modules/push_notifications/index.md +1 -1
- package/dist/agentic/guides/modules/query_index/index.md +1 -1
- package/dist/agentic/guides/modules/record_locks/index.md +1 -1
- package/dist/agentic/guides/modules/resources/index.md +1 -1
- package/dist/agentic/guides/modules/sales/index.md +1 -1
- package/dist/agentic/guides/modules/scheduler/index.md +1 -1
- package/dist/agentic/guides/modules/search/index.md +1 -1
- package/dist/agentic/guides/modules/security/index.md +1 -1
- package/dist/agentic/guides/modules/shipping_carriers/index.md +1 -1
- package/dist/agentic/guides/modules/sso/index.md +1 -1
- package/dist/agentic/guides/modules/staff/index.md +1 -1
- package/dist/agentic/guides/modules/storage_s3/index.md +1 -1
- package/dist/agentic/guides/modules/sync_akeneo/index.md +1 -1
- package/dist/agentic/guides/modules/sync_excel/index.md +1 -1
- package/dist/agentic/guides/modules/system_status_overlays/index.md +1 -1
- package/dist/agentic/guides/modules/translations/index.md +1 -1
- package/dist/agentic/guides/modules/warranty_claims/index.md +1 -1
- package/dist/agentic/guides/modules/webhooks/index.md +1 -1
- package/dist/agentic/guides/modules/wms/index.md +1 -1
- package/dist/agentic/guides/modules/workflows/index.md +1 -1
- package/dist/agentic/guides/reference-module-facts.json +1 -1
- package/dist/agentic/guides/upstream/manifest.json +1 -1
- package/dist/agentic/shared/ai/harness/cases.json +4 -2
- package/package.json +3 -3
- package/template/.env.example +46 -1
- package/template/package.json.template +2 -0
- package/template/scripts/dev-runtime-actions.mjs +99 -0
- package/template/scripts/dev-runtime-config.mjs +89 -0
- package/template/scripts/dev-runtime-diagnostics.mjs +292 -0
- package/template/scripts/dev-runtime-gateway.mjs +370 -0
- package/template/scripts/dev-runtime-probe.mjs +77 -0
- package/template/scripts/dev-runtime-state.mjs +571 -0
- package/template/scripts/dev-runtime-supervisor.mjs +268 -0
- package/template/scripts/dev-runtime.mjs +29 -0
- package/template/scripts/dev-splash-state.mjs +14 -0
- package/template/scripts/dev-splash.html +357 -2
- package/template/scripts/dev.mjs +396 -14
- package/template/src/app/__tests__/start-page-bootstrap.test.ts +34 -0
- package/template/src/app/api/dev-runtime/actions/[action]/route.ts +5 -0
- package/template/src/app/api/dev-runtime/diagnostics/route.ts +5 -0
- package/template/src/app/api/dev-runtime/logs/route.ts +5 -0
- package/template/src/app/api/dev-runtime/status/route.ts +5 -0
- package/template/src/app/api/healthz/__tests__/route.test.ts +3 -1
- package/template/src/app/global-error.tsx +7 -0
- package/template/src/app/layout.tsx +11 -0
- package/template/src/app/start/page.tsx +11 -1
- package/template/src/i18n/de.json +27 -0
- package/template/src/i18n/en.json +27 -0
- package/template/src/i18n/es.json +27 -0
- package/template/src/i18n/ko.json +27 -0
- package/template/src/i18n/pl.json +27 -0
- package/template/src/modules/example/__integration__/TC-START-001-onboarding-gate.spec.ts +33 -0
- package/template/src/modules.ts +2 -0
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
import crypto from 'node:crypto'
|
|
2
|
+
import fs from 'node:fs'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
|
|
5
|
+
import {
|
|
6
|
+
MAX_BROWSER_REPORT_BYTES,
|
|
7
|
+
MAX_STACK_LENGTH,
|
|
8
|
+
redactSensitiveText,
|
|
9
|
+
RUNTIME_RECOVERY_ACTIONS,
|
|
10
|
+
} from './dev-runtime-state.mjs'
|
|
11
|
+
|
|
12
|
+
export const BROWSER_REPORT_KINDS = [
|
|
13
|
+
'global-error',
|
|
14
|
+
'window-error',
|
|
15
|
+
'unhandled-rejection',
|
|
16
|
+
'chunk-load-error',
|
|
17
|
+
'request-error',
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
export const MAX_DIAGNOSTIC_SINK_BYTES = 512 * 1024
|
|
21
|
+
|
|
22
|
+
export function createDevRuntimeToken() {
|
|
23
|
+
return crypto.randomBytes(24).toString('base64url')
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Constant-time comparison so a local attacker cannot probe the token byte by
|
|
27
|
+
// byte through response timing.
|
|
28
|
+
export function isMatchingDevRuntimeToken(expected, provided) {
|
|
29
|
+
if (typeof expected !== 'string' || expected.length === 0) return false
|
|
30
|
+
if (typeof provided !== 'string' || provided.length === 0) return false
|
|
31
|
+
const expectedBuffer = Buffer.from(expected)
|
|
32
|
+
const providedBuffer = Buffer.from(provided)
|
|
33
|
+
if (expectedBuffer.length !== providedBuffer.length) return false
|
|
34
|
+
return crypto.timingSafeEqual(expectedBuffer, providedBuffer)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function invalid(message) {
|
|
38
|
+
return { ok: false, status: 400, error: { code: 'invalid_report', message } }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Validates an untrusted browser report. A report may inform runtime state but
|
|
42
|
+
// can never select an action, a command, or a configuration value.
|
|
43
|
+
export function validateBrowserReport(input, options = {}) {
|
|
44
|
+
const maxBytes = Number.isInteger(options.maxBytes) ? options.maxBytes : MAX_BROWSER_REPORT_BYTES
|
|
45
|
+
|
|
46
|
+
let payload = input
|
|
47
|
+
if (typeof input === 'string') {
|
|
48
|
+
if (Buffer.byteLength(input, 'utf8') > maxBytes) {
|
|
49
|
+
return { ok: false, status: 400, error: { code: 'report_too_large', message: 'Diagnostic report exceeds the size limit.' } }
|
|
50
|
+
}
|
|
51
|
+
try {
|
|
52
|
+
payload = JSON.parse(input)
|
|
53
|
+
} catch {
|
|
54
|
+
return invalid('Diagnostic report is not valid JSON.')
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
|
|
59
|
+
return invalid('Diagnostic report must be an object.')
|
|
60
|
+
}
|
|
61
|
+
if (!BROWSER_REPORT_KINDS.includes(payload.kind)) {
|
|
62
|
+
return invalid('Diagnostic report kind is not supported.')
|
|
63
|
+
}
|
|
64
|
+
if (typeof payload.message !== 'string' || payload.message.trim().length === 0) {
|
|
65
|
+
return invalid('Diagnostic report requires a message.')
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const message = redactSensitiveText(payload.message, 500)
|
|
69
|
+
if (!message) return invalid('Diagnostic report message is empty after redaction.')
|
|
70
|
+
|
|
71
|
+
const report = { kind: payload.kind, message }
|
|
72
|
+
|
|
73
|
+
if (payload.digest != null) {
|
|
74
|
+
if (typeof payload.digest !== 'string' || !/^[A-Za-z0-9_-]{1,64}$/.test(payload.digest)) {
|
|
75
|
+
return invalid('Diagnostic report digest is malformed.')
|
|
76
|
+
}
|
|
77
|
+
report.digest = payload.digest
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
if (payload.path != null) {
|
|
81
|
+
if (typeof payload.path !== 'string' || payload.path.length > 300) {
|
|
82
|
+
return invalid('Diagnostic report path is malformed.')
|
|
83
|
+
}
|
|
84
|
+
const sanitized = redactSensitiveText(payload.path, 300)
|
|
85
|
+
if (sanitized) report.path = sanitized.startsWith('/') ? sanitized : `/${sanitized}`
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
if (payload.stack != null) {
|
|
89
|
+
if (typeof payload.stack !== 'string') {
|
|
90
|
+
return invalid('Diagnostic report stack is malformed.')
|
|
91
|
+
}
|
|
92
|
+
const sanitized = redactSensitiveText(payload.stack, MAX_STACK_LENGTH)
|
|
93
|
+
if (sanitized) report.stack = sanitized
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
if (payload.timestamp != null) {
|
|
97
|
+
if (typeof payload.timestamp !== 'string' || Number.isNaN(Date.parse(payload.timestamp))) {
|
|
98
|
+
return invalid('Diagnostic report timestamp is malformed.')
|
|
99
|
+
}
|
|
100
|
+
report.timestamp = new Date(payload.timestamp).toISOString()
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
if (Buffer.byteLength(JSON.stringify(report), 'utf8') > maxBytes) {
|
|
104
|
+
return { ok: false, status: 400, error: { code: 'report_too_large', message: 'Diagnostic report exceeds the size limit.' } }
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
return { ok: true, report }
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function browserReportToSignal(report, generation) {
|
|
111
|
+
return {
|
|
112
|
+
source: 'browser',
|
|
113
|
+
severity: 'error',
|
|
114
|
+
generation,
|
|
115
|
+
message: report.message,
|
|
116
|
+
digest: report.digest,
|
|
117
|
+
path: report.path,
|
|
118
|
+
blocking: false,
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Fixed-window limiter. Bounded, per-process and dev-only: it exists so a
|
|
123
|
+
// looping browser cannot flood the sink, not as a security control.
|
|
124
|
+
export function createRateLimiter(options = {}) {
|
|
125
|
+
const limit = Number.isInteger(options.limit) && options.limit > 0 ? options.limit : 30
|
|
126
|
+
const windowMs = Number.isInteger(options.windowMs) && options.windowMs > 0 ? options.windowMs : 10_000
|
|
127
|
+
const now = typeof options.now === 'function' ? options.now : () => Date.now()
|
|
128
|
+
|
|
129
|
+
let windowStart = now()
|
|
130
|
+
let count = 0
|
|
131
|
+
|
|
132
|
+
return {
|
|
133
|
+
tryConsume() {
|
|
134
|
+
const timestamp = now()
|
|
135
|
+
if (timestamp - windowStart >= windowMs) {
|
|
136
|
+
windowStart = timestamp
|
|
137
|
+
count = 0
|
|
138
|
+
}
|
|
139
|
+
if (count >= limit) return false
|
|
140
|
+
count += 1
|
|
141
|
+
return true
|
|
142
|
+
},
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export const MAX_ACTION_REQUEST_BYTES = 16 * 1024
|
|
147
|
+
|
|
148
|
+
// Validates an action request coming from the dev-only app route. The action is
|
|
149
|
+
// matched against the fixed allowlist here as well as at the runner, so a
|
|
150
|
+
// malformed sink line can never widen what the supervisor will execute.
|
|
151
|
+
export function validateActionRequest(input, options = {}) {
|
|
152
|
+
const maxBytes = Number.isInteger(options.maxBytes) ? options.maxBytes : MAX_ACTION_REQUEST_BYTES
|
|
153
|
+
const serialized = typeof input === 'string' ? input : JSON.stringify(input)
|
|
154
|
+
if (typeof serialized !== 'string' || Buffer.byteLength(serialized, 'utf8') > maxBytes) {
|
|
155
|
+
return { ok: false, status: 400, error: { code: 'action_too_large', message: 'Action request exceeds the size limit.' } }
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
let payload = input
|
|
159
|
+
if (typeof input === 'string') {
|
|
160
|
+
try {
|
|
161
|
+
payload = JSON.parse(input)
|
|
162
|
+
} catch {
|
|
163
|
+
return { ok: false, status: 400, error: { code: 'invalid_action', message: 'Action request is not valid JSON.' } }
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
|
|
167
|
+
return { ok: false, status: 400, error: { code: 'invalid_action', message: 'Action request must be an object.' } }
|
|
168
|
+
}
|
|
169
|
+
if (!RUNTIME_RECOVERY_ACTIONS.includes(payload.action)) {
|
|
170
|
+
return { ok: false, status: 400, error: { code: 'unknown_action', message: 'Unknown recovery action.' } }
|
|
171
|
+
}
|
|
172
|
+
const request = { action: payload.action }
|
|
173
|
+
if (Number.isInteger(payload.generation)) request.generation = payload.generation
|
|
174
|
+
if (typeof payload.requestedAt === 'string' && !Number.isNaN(Date.parse(payload.requestedAt))) {
|
|
175
|
+
request.requestedAt = new Date(payload.requestedAt).toISOString()
|
|
176
|
+
}
|
|
177
|
+
return { ok: true, request }
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// A cursor is only meaningful while the bytes it already consumed are still the
|
|
181
|
+
// same records. Every line the sink writes ends in a newline, so the byte before
|
|
182
|
+
// the cursor must be one; when it is not, the file underneath the reader was
|
|
183
|
+
// replaced and the cursor has to restart.
|
|
184
|
+
function endsOnRecordBoundary(handle, cursor) {
|
|
185
|
+
const probe = Buffer.alloc(1)
|
|
186
|
+
return fs.readSync(handle, probe, 0, 1, cursor - 1) === 1 && probe[0] === 0x0a
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// Append-only NDJSON hand-off between the dev-only app route (writer) and the
|
|
190
|
+
// supervisor (reader). The reader tracks a byte offset so it never re-ingests a
|
|
191
|
+
// line, and the file is rotated rather than growing without bound. Used for both
|
|
192
|
+
// browser reports and recovery-action requests via the `validate` option.
|
|
193
|
+
export function createDiagnosticsSink(options = {}) {
|
|
194
|
+
const filePath = options.filePath
|
|
195
|
+
const maxBytes = Number.isInteger(options.maxBytes) ? options.maxBytes : MAX_DIAGNOSTIC_SINK_BYTES
|
|
196
|
+
// Every drained line is re-validated, so the same sink shape can carry either
|
|
197
|
+
// browser reports or action requests without trusting what was written.
|
|
198
|
+
const validate = typeof options.validate === 'function' ? options.validate : validateBrowserReport
|
|
199
|
+
let offset = 0
|
|
200
|
+
let inode = null
|
|
201
|
+
|
|
202
|
+
function ensureDirectory() {
|
|
203
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true })
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// Rotation unlinks instead of truncating so a reader can detect it through
|
|
207
|
+
// the changed inode even when it never observed the empty file.
|
|
208
|
+
function rotate() {
|
|
209
|
+
offset = 0
|
|
210
|
+
inode = null
|
|
211
|
+
try {
|
|
212
|
+
ensureDirectory()
|
|
213
|
+
fs.rmSync(filePath, { force: true })
|
|
214
|
+
} catch {
|
|
215
|
+
// The sink is best-effort; the terminal remains authoritative.
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
return {
|
|
220
|
+
getFilePath() {
|
|
221
|
+
return filePath
|
|
222
|
+
},
|
|
223
|
+
|
|
224
|
+
clear: rotate,
|
|
225
|
+
|
|
226
|
+
append(report) {
|
|
227
|
+
try {
|
|
228
|
+
ensureDirectory()
|
|
229
|
+
fs.appendFileSync(filePath, `${JSON.stringify(report)}\n`, 'utf8')
|
|
230
|
+
return true
|
|
231
|
+
} catch {
|
|
232
|
+
return false
|
|
233
|
+
}
|
|
234
|
+
},
|
|
235
|
+
|
|
236
|
+
drain() {
|
|
237
|
+
let stats
|
|
238
|
+
try {
|
|
239
|
+
stats = fs.statSync(filePath)
|
|
240
|
+
} catch {
|
|
241
|
+
offset = 0
|
|
242
|
+
inode = null
|
|
243
|
+
return []
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// A changed inode proves rotation, but an unchanged one proves nothing:
|
|
247
|
+
// inode numbers are recycled as soon as they are freed, so a rotated file
|
|
248
|
+
// routinely reappears under the inode the reader already recorded. The
|
|
249
|
+
// record-boundary check below is what actually catches that.
|
|
250
|
+
if (inode !== null && stats.ino !== inode) offset = 0
|
|
251
|
+
inode = stats.ino
|
|
252
|
+
if (stats.size < offset) offset = 0
|
|
253
|
+
|
|
254
|
+
let chunk = ''
|
|
255
|
+
try {
|
|
256
|
+
const handle = fs.openSync(filePath, 'r')
|
|
257
|
+
try {
|
|
258
|
+
if (offset > 0 && !endsOnRecordBoundary(handle, offset)) offset = 0
|
|
259
|
+
if (stats.size === offset) return []
|
|
260
|
+
const length = stats.size - offset
|
|
261
|
+
const buffer = Buffer.alloc(length)
|
|
262
|
+
fs.readSync(handle, buffer, 0, length, offset)
|
|
263
|
+
chunk = buffer.toString('utf8')
|
|
264
|
+
} finally {
|
|
265
|
+
fs.closeSync(handle)
|
|
266
|
+
}
|
|
267
|
+
} catch {
|
|
268
|
+
return []
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const lastNewline = chunk.lastIndexOf('\n')
|
|
272
|
+
if (lastNewline === -1) return []
|
|
273
|
+
offset += Buffer.byteLength(chunk.slice(0, lastNewline + 1), 'utf8')
|
|
274
|
+
|
|
275
|
+
const reports = []
|
|
276
|
+
for (const line of chunk.slice(0, lastNewline).split('\n')) {
|
|
277
|
+
if (!line.trim()) continue
|
|
278
|
+
try {
|
|
279
|
+
const parsed = JSON.parse(line)
|
|
280
|
+
const validated = validate(parsed)
|
|
281
|
+
if (validated.ok) reports.push(validated.report ?? validated.request)
|
|
282
|
+
} catch {
|
|
283
|
+
// Ignore malformed lines; a partial write must not stall the drain.
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
if (offset > maxBytes) rotate()
|
|
288
|
+
|
|
289
|
+
return reports
|
|
290
|
+
},
|
|
291
|
+
}
|
|
292
|
+
}
|
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
import http from 'node:http'
|
|
2
|
+
|
|
3
|
+
import { isMatchingDevRuntimeToken, validateBrowserReport } from './dev-runtime-diagnostics.mjs'
|
|
4
|
+
import { assertLocalSplashRequest } from './dev-splash-shared.mjs'
|
|
5
|
+
import { RUNTIME_RECOVERY_ACTIONS } from './dev-runtime-state.mjs'
|
|
6
|
+
|
|
7
|
+
export const GATEWAY_NAMESPACE = '/__open-mercato'
|
|
8
|
+
export const DEV_RUNTIME_TOKEN_HEADER = 'x-om-dev-runtime-token'
|
|
9
|
+
|
|
10
|
+
// RFC 7230 hop-by-hop headers. They describe a single transport link and must
|
|
11
|
+
// never be forwarded across the proxy boundary.
|
|
12
|
+
const HOP_BY_HOP_HEADERS = new Set([
|
|
13
|
+
'connection',
|
|
14
|
+
'keep-alive',
|
|
15
|
+
'proxy-authenticate',
|
|
16
|
+
'proxy-authorization',
|
|
17
|
+
'te',
|
|
18
|
+
'trailer',
|
|
19
|
+
'transfer-encoding',
|
|
20
|
+
'upgrade',
|
|
21
|
+
])
|
|
22
|
+
|
|
23
|
+
const MAX_DIAGNOSTIC_BODY_BYTES = 8192
|
|
24
|
+
const SERVE_SPLASH_HEALTH = new Set(['starting', 'recovering', 'unavailable'])
|
|
25
|
+
|
|
26
|
+
export function isGatewayControlPath(pathname) {
|
|
27
|
+
return pathname === GATEWAY_NAMESPACE || pathname.startsWith(`${GATEWAY_NAMESPACE}/`)
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// A navigation is what a developer sees in the address bar. Only navigations
|
|
31
|
+
// may be answered with splash HTML — an API or asset request must always reach
|
|
32
|
+
// the upstream so a business 4xx/5xx is never masked.
|
|
33
|
+
export function isNavigationRequest(method, pathname, headers = {}) {
|
|
34
|
+
if (method !== 'GET' && method !== 'HEAD') return false
|
|
35
|
+
if (isGatewayControlPath(pathname)) return false
|
|
36
|
+
if (pathname.startsWith('/api/') || pathname.startsWith('/_next/')) return false
|
|
37
|
+
if (headers['x-requested-with']) return false
|
|
38
|
+
// Browsers label a real navigation `sec-fetch-mode: navigate`; every other
|
|
39
|
+
// value (`cors`, `no-cors`, `same-origin`) is a programmatic fetch that must
|
|
40
|
+
// reach the upstream even though it may accept HTML.
|
|
41
|
+
const fetchMode = headers['sec-fetch-mode']
|
|
42
|
+
if (typeof fetchMode === 'string' && fetchMode !== 'navigate') return false
|
|
43
|
+
const accept = typeof headers.accept === 'string' ? headers.accept : ''
|
|
44
|
+
return accept.includes('text/html')
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function stripHopByHopHeaders(headers) {
|
|
48
|
+
const forwarded = {}
|
|
49
|
+
for (const [name, value] of Object.entries(headers ?? {})) {
|
|
50
|
+
if (HOP_BY_HOP_HEADERS.has(name.toLowerCase())) continue
|
|
51
|
+
forwarded[name] = value
|
|
52
|
+
}
|
|
53
|
+
return forwarded
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function resolveForwardedProto(req) {
|
|
57
|
+
return req.socket?.encrypted ? 'https' : 'http'
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function buildUpstreamHeaders(req, upstream) {
|
|
61
|
+
const headers = stripHopByHopHeaders(req.headers)
|
|
62
|
+
const originalHost = typeof req.headers.host === 'string' ? req.headers.host : ''
|
|
63
|
+
|
|
64
|
+
headers.host = `${upstream.host}:${upstream.port}`
|
|
65
|
+
headers['x-forwarded-host'] = originalHost
|
|
66
|
+
headers['x-forwarded-proto'] = resolveForwardedProto(req)
|
|
67
|
+
headers['x-forwarded-for'] = [req.headers['x-forwarded-for'], req.socket?.remoteAddress]
|
|
68
|
+
.filter(Boolean)
|
|
69
|
+
.join(', ')
|
|
70
|
+
|
|
71
|
+
// The upstream validates Origin against its own host. Rewriting it to the
|
|
72
|
+
// internal address keeps Next's server-action origin check satisfied while
|
|
73
|
+
// the developer keeps browsing the public port.
|
|
74
|
+
if (typeof req.headers.origin === 'string' && originalHost && req.headers.origin.includes(originalHost)) {
|
|
75
|
+
headers.origin = `${resolveForwardedProto(req)}://${upstream.host}:${upstream.port}`
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
return headers
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function sendJson(res, status, payload) {
|
|
82
|
+
const body = JSON.stringify(payload)
|
|
83
|
+
res.statusCode = status
|
|
84
|
+
res.setHeader('content-type', 'application/json; charset=utf-8')
|
|
85
|
+
res.setHeader('cache-control', 'no-store')
|
|
86
|
+
res.end(body)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function sendJsonError(res, status, code, message) {
|
|
90
|
+
sendJson(res, status, { error: { code, message } })
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function readRequestBody(req, maxBytes) {
|
|
94
|
+
return new Promise((resolve) => {
|
|
95
|
+
let size = 0
|
|
96
|
+
const chunks = []
|
|
97
|
+
req.on('data', (chunk) => {
|
|
98
|
+
size += chunk.length
|
|
99
|
+
if (size > maxBytes) {
|
|
100
|
+
req.destroy()
|
|
101
|
+
resolve({ ok: false })
|
|
102
|
+
return
|
|
103
|
+
}
|
|
104
|
+
chunks.push(chunk)
|
|
105
|
+
})
|
|
106
|
+
req.on('end', () => resolve({ ok: true, body: Buffer.concat(chunks).toString('utf8') }))
|
|
107
|
+
req.on('error', () => resolve({ ok: false }))
|
|
108
|
+
})
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Opt-in development gateway. It owns the public port, answers the
|
|
113
|
+
* `/__open-mercato/*` control namespace itself, serves splash feedback for
|
|
114
|
+
* navigations while the runtime cannot serve, and otherwise streams traffic to
|
|
115
|
+
* the managed Next.js upstream — including raw HMR `upgrade` forwarding.
|
|
116
|
+
*
|
|
117
|
+
* It is a development aid, never a production reverse proxy.
|
|
118
|
+
*/
|
|
119
|
+
export function createDevRuntimeGateway(options = {}) {
|
|
120
|
+
const getStatus = typeof options.getStatus === 'function' ? options.getStatus : () => null
|
|
121
|
+
const getDiagnosticLines = typeof options.getDiagnosticLines === 'function' ? options.getDiagnosticLines : () => ({ lines: [], nextCursor: 0, generation: 0 })
|
|
122
|
+
const recordBrowserReport = typeof options.recordBrowserReport === 'function' ? options.recordBrowserReport : () => null
|
|
123
|
+
const runAction = typeof options.runAction === 'function' ? options.runAction : null
|
|
124
|
+
const resolveUpstream = typeof options.resolveUpstream === 'function' ? options.resolveUpstream : () => null
|
|
125
|
+
const renderSplashHtml = typeof options.renderSplashHtml === 'function' ? options.renderSplashHtml : () => '<!doctype html><title>Open Mercato Dev</title>'
|
|
126
|
+
const env = options.env ?? process.env
|
|
127
|
+
const token = typeof options.token === 'string' ? options.token : null
|
|
128
|
+
const logger = options.logger ?? console
|
|
129
|
+
|
|
130
|
+
function isAuthorized(req) {
|
|
131
|
+
return isMatchingDevRuntimeToken(token, req.headers[DEV_RUNTIME_TOKEN_HEADER])
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function currentHealth() {
|
|
135
|
+
return getStatus()?.health ?? 'starting'
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function handleControlRequest(req, res, url) {
|
|
139
|
+
const guard = assertLocalSplashRequest(req, env)
|
|
140
|
+
if (!guard.ok) {
|
|
141
|
+
sendJsonError(res, guard.status, 'forbidden', guard.error)
|
|
142
|
+
return
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
if (req.method === 'GET' && url.pathname === `${GATEWAY_NAMESPACE}/status`) {
|
|
146
|
+
const status = getStatus()
|
|
147
|
+
if (!status) {
|
|
148
|
+
sendJsonError(res, 404, 'not_found', 'Runtime status is not available.')
|
|
149
|
+
return
|
|
150
|
+
}
|
|
151
|
+
sendJson(res, 200, status)
|
|
152
|
+
return
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
if (req.method === 'GET' && url.pathname === `${GATEWAY_NAMESPACE}/logs`) {
|
|
156
|
+
const raw = url.searchParams.get('cursor')
|
|
157
|
+
// A malformed cursor restarts the snapshot rather than failing the view.
|
|
158
|
+
const parsed = Number.parseInt(raw ?? '', 10)
|
|
159
|
+
sendJson(res, 200, getDiagnosticLines(Number.isInteger(parsed) && parsed >= 0 ? parsed : 0))
|
|
160
|
+
return
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
if (req.method === 'POST' && url.pathname === `${GATEWAY_NAMESPACE}/diagnostics`) {
|
|
164
|
+
if (!isAuthorized(req)) {
|
|
165
|
+
sendJsonError(res, 403, 'forbidden', 'Invalid dev runtime token.')
|
|
166
|
+
return
|
|
167
|
+
}
|
|
168
|
+
const body = await readRequestBody(req, MAX_DIAGNOSTIC_BODY_BYTES)
|
|
169
|
+
if (!body.ok) {
|
|
170
|
+
sendJsonError(res, 400, 'report_too_large', 'Diagnostic report exceeds the size limit.')
|
|
171
|
+
return
|
|
172
|
+
}
|
|
173
|
+
const validated = validateBrowserReport(body.body, { maxBytes: MAX_DIAGNOSTIC_BODY_BYTES })
|
|
174
|
+
if (!validated.ok) {
|
|
175
|
+
sendJsonError(res, validated.status, validated.error.code, validated.error.message)
|
|
176
|
+
return
|
|
177
|
+
}
|
|
178
|
+
const issueId = recordBrowserReport(validated.report)
|
|
179
|
+
sendJson(res, 202, { accepted: true, issueId: issueId ?? null })
|
|
180
|
+
return
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
if (req.method === 'POST' && url.pathname.startsWith(`${GATEWAY_NAMESPACE}/actions/`)) {
|
|
184
|
+
if (!isAuthorized(req)) {
|
|
185
|
+
sendJsonError(res, 403, 'forbidden', 'Invalid dev runtime token.')
|
|
186
|
+
return
|
|
187
|
+
}
|
|
188
|
+
if (!runAction) {
|
|
189
|
+
sendJsonError(res, 503, 'supervisor_unavailable', 'The supervisor cannot run recovery actions.')
|
|
190
|
+
return
|
|
191
|
+
}
|
|
192
|
+
const action = url.pathname.slice(`${GATEWAY_NAMESPACE}/actions/`.length)
|
|
193
|
+
if (!RUNTIME_RECOVERY_ACTIONS.includes(action)) {
|
|
194
|
+
sendJsonError(res, 400, 'unknown_action', 'Unknown recovery action.')
|
|
195
|
+
return
|
|
196
|
+
}
|
|
197
|
+
const result = await runAction(action)
|
|
198
|
+
if (!result?.ok) {
|
|
199
|
+
sendJsonError(res, result?.status ?? 409, result?.code ?? 'conflict', result?.message ?? 'The action could not be queued.')
|
|
200
|
+
return
|
|
201
|
+
}
|
|
202
|
+
sendJson(res, 202, { accepted: true, actionId: result.actionId, generation: result.generation })
|
|
203
|
+
return
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
sendJsonError(res, 404, 'not_found', 'Unknown dev runtime control route.')
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function serveSplash(req, res) {
|
|
210
|
+
res.statusCode = 200
|
|
211
|
+
res.setHeader('content-type', 'text/html; charset=utf-8')
|
|
212
|
+
res.setHeader('cache-control', 'no-store')
|
|
213
|
+
res.end(req.method === 'HEAD' ? '' : renderSplashHtml(req))
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function proxyRequest(req, res, upstream) {
|
|
217
|
+
const proxied = http.request({
|
|
218
|
+
host: upstream.host,
|
|
219
|
+
port: upstream.port,
|
|
220
|
+
method: req.method,
|
|
221
|
+
path: req.url,
|
|
222
|
+
headers: buildUpstreamHeaders(req, upstream),
|
|
223
|
+
}, (upstreamResponse) => {
|
|
224
|
+
res.statusCode = upstreamResponse.statusCode ?? 502
|
|
225
|
+
for (const [name, value] of Object.entries(stripHopByHopHeaders(upstreamResponse.headers))) {
|
|
226
|
+
if (value !== undefined) res.setHeader(name, value)
|
|
227
|
+
}
|
|
228
|
+
upstreamResponse.pipe(res)
|
|
229
|
+
})
|
|
230
|
+
|
|
231
|
+
proxied.on('error', (error) => {
|
|
232
|
+
if (res.headersSent) {
|
|
233
|
+
res.destroy()
|
|
234
|
+
return
|
|
235
|
+
}
|
|
236
|
+
if (isNavigationRequest(req.method, new URL(req.url, 'http://localhost').pathname, req.headers)) {
|
|
237
|
+
serveSplash(req, res)
|
|
238
|
+
return
|
|
239
|
+
}
|
|
240
|
+
sendJsonError(res, 502, 'upstream_unavailable', `The development runtime did not answer: ${error.code ?? 'ECONNRESET'}`)
|
|
241
|
+
})
|
|
242
|
+
|
|
243
|
+
// Abort propagation both ways so a cancelled download does not leak an
|
|
244
|
+
// upstream request.
|
|
245
|
+
res.on('close', () => { if (!res.writableFinished) proxied.destroy() })
|
|
246
|
+
req.pipe(proxied)
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
const server = http.createServer((req, res) => {
|
|
250
|
+
if (!req.url) {
|
|
251
|
+
sendJsonError(res, 400, 'bad_request', 'Missing request target.')
|
|
252
|
+
return
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
const url = new URL(req.url, 'http://localhost')
|
|
256
|
+
|
|
257
|
+
// Gateway-owned paths are never proxied, even if a module later declares a
|
|
258
|
+
// colliding route.
|
|
259
|
+
if (isGatewayControlPath(url.pathname)) {
|
|
260
|
+
void handleControlRequest(req, res, url)
|
|
261
|
+
return
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const upstream = resolveUpstream()
|
|
265
|
+
const health = currentHealth()
|
|
266
|
+
const navigation = isNavigationRequest(req.method, url.pathname, req.headers)
|
|
267
|
+
|
|
268
|
+
if (navigation && SERVE_SPLASH_HEALTH.has(health)) {
|
|
269
|
+
serveSplash(req, res)
|
|
270
|
+
return
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
if (!upstream) {
|
|
274
|
+
if (navigation) {
|
|
275
|
+
serveSplash(req, res)
|
|
276
|
+
return
|
|
277
|
+
}
|
|
278
|
+
sendJsonError(res, 503, 'upstream_unavailable', 'The development runtime is not listening yet.')
|
|
279
|
+
return
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
proxyRequest(req, res, upstream)
|
|
283
|
+
})
|
|
284
|
+
|
|
285
|
+
// An upgraded socket is detached from the server's connection tracking, so
|
|
286
|
+
// shutdown has to tear the tunnels down explicitly or `close()` never
|
|
287
|
+
// settles.
|
|
288
|
+
const tunnelSockets = new Set()
|
|
289
|
+
|
|
290
|
+
function trackTunnelSocket(socket) {
|
|
291
|
+
tunnelSockets.add(socket)
|
|
292
|
+
socket.once('close', () => tunnelSockets.delete(socket))
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// HMR rides on a raw WebSocket upgrade, which the request handler above never
|
|
296
|
+
// sees. Forwarding it explicitly is what keeps fast refresh working.
|
|
297
|
+
server.on('upgrade', (req, socket, head) => {
|
|
298
|
+
const upstream = resolveUpstream()
|
|
299
|
+
if (!upstream || !req.url) {
|
|
300
|
+
socket.end('HTTP/1.1 503 Service Unavailable\r\n\r\n')
|
|
301
|
+
return
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// `Connection`/`Upgrade` are hop-by-hop for a normal proxy hop, but they
|
|
305
|
+
// are exactly what makes this hop an upgrade — put them back deliberately.
|
|
306
|
+
const upgradeHeaders = buildUpstreamHeaders(req, upstream)
|
|
307
|
+
upgradeHeaders.connection = 'Upgrade'
|
|
308
|
+
upgradeHeaders.upgrade = req.headers.upgrade ?? 'websocket'
|
|
309
|
+
|
|
310
|
+
const proxied = http.request({
|
|
311
|
+
host: upstream.host,
|
|
312
|
+
port: upstream.port,
|
|
313
|
+
method: req.method,
|
|
314
|
+
path: req.url,
|
|
315
|
+
headers: upgradeHeaders,
|
|
316
|
+
})
|
|
317
|
+
|
|
318
|
+
proxied.on('upgrade', (upstreamResponse, upstreamSocket, upstreamHead) => {
|
|
319
|
+
const headerLines = Object.entries(upstreamResponse.headers)
|
|
320
|
+
.flatMap(([name, value]) => (Array.isArray(value) ? value.map((item) => `${name}: ${item}`) : [`${name}: ${value}`]))
|
|
321
|
+
socket.write(`HTTP/1.1 101 Switching Protocols\r\n${headerLines.join('\r\n')}\r\n\r\n`)
|
|
322
|
+
// Bytes the upstream already sent past its 101 belong to the tunnel, so
|
|
323
|
+
// push them back before piping instead of dropping them.
|
|
324
|
+
if (upstreamHead?.length) upstreamSocket.unshift(upstreamHead)
|
|
325
|
+
trackTunnelSocket(socket)
|
|
326
|
+
trackTunnelSocket(upstreamSocket)
|
|
327
|
+
upstreamSocket.pipe(socket)
|
|
328
|
+
socket.pipe(upstreamSocket)
|
|
329
|
+
upstreamSocket.on('error', () => socket.destroy())
|
|
330
|
+
socket.on('error', () => upstreamSocket.destroy())
|
|
331
|
+
})
|
|
332
|
+
|
|
333
|
+
proxied.on('error', () => {
|
|
334
|
+
socket.end('HTTP/1.1 502 Bad Gateway\r\n\r\n')
|
|
335
|
+
})
|
|
336
|
+
|
|
337
|
+
socket.on('error', () => proxied.destroy())
|
|
338
|
+
if (head?.length) proxied.write(head)
|
|
339
|
+
// The upgrade request itself carries no body beyond `head`.
|
|
340
|
+
proxied.end()
|
|
341
|
+
})
|
|
342
|
+
|
|
343
|
+
return {
|
|
344
|
+
server,
|
|
345
|
+
listen(port, host) {
|
|
346
|
+
return new Promise((resolve, reject) => {
|
|
347
|
+
const handleError = (error) => {
|
|
348
|
+
server.off('listening', handleListening)
|
|
349
|
+
reject(error)
|
|
350
|
+
}
|
|
351
|
+
const handleListening = () => {
|
|
352
|
+
server.off('error', handleError)
|
|
353
|
+
resolve(server.address())
|
|
354
|
+
}
|
|
355
|
+
server.once('error', handleError)
|
|
356
|
+
server.once('listening', handleListening)
|
|
357
|
+
server.listen(port, host)
|
|
358
|
+
})
|
|
359
|
+
},
|
|
360
|
+
close() {
|
|
361
|
+
return new Promise((resolve) => {
|
|
362
|
+
for (const socket of tunnelSockets) socket.destroy()
|
|
363
|
+
tunnelSockets.clear()
|
|
364
|
+
server.close(() => resolve())
|
|
365
|
+
server.closeAllConnections?.()
|
|
366
|
+
})
|
|
367
|
+
},
|
|
368
|
+
logger,
|
|
369
|
+
}
|
|
370
|
+
}
|