@rebasepro/server 0.28.1 → 0.29.0-canary.g0e3a0e7
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/dist/{GCSStorageController-LXeAF6Ks.js → GCSStorageController-Ch3Ridyt.js} +4 -4
- package/dist/{GCSStorageController-LXeAF6Ks.js.map → GCSStorageController-Ch3Ridyt.js.map} +1 -1
- package/dist/{S3StorageController-CVKMUXo_.js → S3StorageController-CmNMg7Gu.js} +4 -4
- package/dist/{S3StorageController-CVKMUXo_.js.map → S3StorageController-CmNMg7Gu.js.map} +1 -1
- package/dist/{access-BDz4FO9D.js → access-BZjeLhf5.js} +7 -7
- package/dist/{access-BDz4FO9D.js.map → access-BZjeLhf5.js.map} +1 -1
- package/dist/api/rest/api-generator.d.ts +19 -0
- package/dist/{ast-schema-editor-C4bDSb61.js → ast-schema-editor-Dg7BWKE3.js} +3 -3
- package/dist/{ast-schema-editor-C4bDSb61.js.map → ast-schema-editor-Dg7BWKE3.js.map} +1 -1
- package/dist/auth/cookie-utils.d.ts +14 -6
- package/dist/auth/rate-limiter.d.ts +8 -0
- package/dist/{auth-CZGfVKcL.js → auth-CSWKaSgJ.js} +70 -18
- package/dist/auth-CSWKaSgJ.js.map +1 -0
- package/dist/{auth_adapter-B7RUMk6e.js → auth_adapter-HFv5axIT.js} +20 -2
- package/dist/auth_adapter-HFv5axIT.js.map +1 -0
- package/dist/backend/options.d.ts +3 -0
- package/dist/backend-CaG_Jyso.js.map +1 -1
- package/dist/{backup-BmzY9xdN.js → backup-woinIDjt.js} +9 -9
- package/dist/{backup-BmzY9xdN.js.map → backup-woinIDjt.js.map} +1 -1
- package/dist/boot/driver.d.ts +4 -0
- package/dist/boot/sources.d.ts +7 -0
- package/dist/{branch-routes-DpgaeTJl.js → branch-routes-F5VIJrZp.js} +3 -3
- package/dist/{branch-routes-DpgaeTJl.js.map → branch-routes-F5VIJrZp.js.map} +1 -1
- package/dist/{contract-routes-vYiBHbjI.js → contract-routes-D8Vsxjx8.js} +3 -3
- package/dist/{contract-routes-vYiBHbjI.js.map → contract-routes-D8Vsxjx8.js.map} +1 -1
- package/dist/{cron-loader-C_C-lNgG.js → cron-loader-n9Uh_E1a.js} +3 -3
- package/dist/{cron-loader-C_C-lNgG.js.map → cron-loader-n9Uh_E1a.js.map} +1 -1
- package/dist/{cron-routes-DlwOV6zl.js → cron-routes-mLexIC9F.js} +4 -4
- package/dist/{cron-routes-DlwOV6zl.js.map → cron-routes-mLexIC9F.js.map} +1 -1
- package/dist/{cron-scheduler-6ipIm5mm.js → cron-scheduler-DhxuCDuI.js} +2 -2
- package/dist/{cron-scheduler-6ipIm5mm.js.map → cron-scheduler-DhxuCDuI.js.map} +1 -1
- package/dist/{cron-store-KIOM8LCC.js → cron-store-DzKz7jXF.js} +2 -2
- package/dist/{cron-store-KIOM8LCC.js.map → cron-store-DzKz7jXF.js.map} +1 -1
- package/dist/data_driver-D0mg1Y_x.js.map +1 -1
- package/dist/dist-B4YtgTMh.js +19359 -0
- package/dist/dist-B4YtgTMh.js.map +1 -0
- package/dist/env.d.ts +7 -0
- package/dist/{errors-DIWnZIDY.js → errors-DpTMfX77.js} +58 -8
- package/dist/errors-DpTMfX77.js.map +1 -0
- package/dist/{field-access-KYk8RGOx.js → field-access-CzKjatID.js} +3 -3
- package/dist/{field-access-KYk8RGOx.js.map → field-access-CzKjatID.js.map} +1 -1
- package/dist/{filter-dialect-CE4bloug.js → filter-dialect-C5wfpopB.js} +110 -9
- package/dist/{filter-dialect-CE4bloug.js.map → filter-dialect-C5wfpopB.js.map} +1 -1
- package/dist/{function-loader-CKB9b4uP.js → function-loader-BzKo2Oiu.js} +2 -2
- package/dist/{function-loader-CKB9b4uP.js.map → function-loader-BzKo2Oiu.js.map} +1 -1
- package/dist/{function-routes-DLaXaiQA.js → function-routes-CQ0z3WDt.js} +2 -2
- package/dist/{function-routes-DLaXaiQA.js.map → function-routes-CQ0z3WDt.js.map} +1 -1
- package/dist/functions/index.d.ts +1 -0
- package/dist/functions/index.js +10 -29
- package/dist/functions/index.js.map +1 -1
- package/dist/functions/wait-until.d.ts +29 -1
- package/dist/{history-recorder-BE4HWR-M.js → history-recorder-wkBuX7Np.js} +2 -2
- package/dist/{history-recorder-BE4HWR-M.js.map → history-recorder-wkBuX7Np.js.map} +1 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.es.js +2260 -1284
- package/dist/index.es.js.map +1 -1
- package/dist/init/surfaces.d.ts +19 -3
- package/dist/{jobs-CXTs9qXH.js → jobs-D61qYEGt.js} +2 -2
- package/dist/{jobs-CXTs9qXH.js.map → jobs-D61qYEGt.js.map} +1 -1
- package/dist/{jwt-5EvX3lQa.js → jwt-CBmQXYs-.js} +2 -2
- package/dist/{jwt-5EvX3lQa.js.map → jwt-CBmQXYs-.js.map} +1 -1
- package/dist/{keys-DJ1ZNcZi.js → keys-Cd_4l48g.js} +2 -2
- package/dist/{keys-DJ1ZNcZi.js.map → keys-Cd_4l48g.js.map} +1 -1
- package/dist/{logs-routes-DXLvMasE.js → logs-routes-08LiyYua.js} +2 -2
- package/dist/{logs-routes-DXLvMasE.js.map → logs-routes-08LiyYua.js.map} +1 -1
- package/dist/mcp/consent-page.d.ts +14 -1
- package/dist/mcp/mcp-apps.d.ts +51 -17
- package/dist/mcp/mcp-routes.d.ts +6 -1
- package/dist/mcp/mcp-tools.d.ts +44 -1
- package/dist/mcp/mcp-view.d.ts +107 -0
- package/dist/mcp/oauth-metadata.d.ts +7 -1
- package/dist/mcp/show-app-guide.d.ts +1 -0
- package/dist/metrics/database.d.ts +69 -0
- package/dist/metrics/db-connection-errors.d.ts +21 -0
- package/dist/{offline-BjJdcVBb-BOzzsnrh.js → offline-BjJdcVBb-B_bOcnDC.js} +4 -4
- package/dist/{offline-BjJdcVBb-BOzzsnrh.js.map → offline-BjJdcVBb-B_bOcnDC.js.map} +1 -1
- package/dist/{offline-store-Cxhh99Q--FB6fSf5A.js → offline-store-Cxhh99Q--DQ-M1M8d.js} +4 -4
- package/dist/{offline-store-Cxhh99Q--FB6fSf5A.js.map → offline-store-Cxhh99Q--DQ-M1M8d.js.map} +1 -1
- package/dist/{openapi-generator-B6aw_KuR.js → openapi-generator-B3LsKCon.js} +4 -4
- package/dist/{openapi-generator-B6aw_KuR.js.map → openapi-generator-B3LsKCon.js.map} +1 -1
- package/dist/{proxy-2nS5N63I.js → proxy-LUsudeht.js} +2 -2
- package/dist/{proxy-2nS5N63I.js.map → proxy-LUsudeht.js.map} +1 -1
- package/dist/{query-parser-DFVCjW5i.js → query-parser-C90z8csB.js} +6 -6
- package/dist/{query-parser-DFVCjW5i.js.map → query-parser-C90z8csB.js.map} +1 -1
- package/dist/{request-timeout-Cqm4JXtZ.js → request-timeout-DW2OBWfJ.js} +2 -2
- package/dist/{request-timeout-Cqm4JXtZ.js.map → request-timeout-DW2OBWfJ.js.map} +1 -1
- package/dist/{rls-simulator-routes-D5-XfjzW.js → rls-simulator-routes-igGu-giT.js} +4 -4
- package/dist/{rls-simulator-routes-D5-XfjzW.js.map → rls-simulator-routes-igGu-giT.js.map} +1 -1
- package/dist/{schema-editor-routes-DzSe6V0a.js → schema-editor-routes-kF1ZKCB2.js} +4 -4
- package/dist/{schema-editor-routes-DzSe6V0a.js.map → schema-editor-routes-kF1ZKCB2.js.map} +1 -1
- package/dist/serve-spa.d.ts +2 -10
- package/dist/{soft-delete-params-9lKBAlDw.js → soft-delete-params-DDRmxT2z.js} +2 -2
- package/dist/{soft-delete-params-9lKBAlDw.js.map → soft-delete-params-DDRmxT2z.js.map} +1 -1
- package/dist/{sql-export-routes-BxMqgAFX.js → sql-export-routes-DObpbf8x.js} +3 -3
- package/dist/{sql-export-routes-BxMqgAFX.js.map → sql-export-routes-DObpbf8x.js.map} +1 -1
- package/dist/{src-JQNz7cWv.js → src-BXDkXOtq.js} +2 -1
- package/dist/{src-JQNz7cWv.js.map → src-BXDkXOtq.js.map} +1 -1
- package/dist/{upload-validation-IYXn4xcm.js → upload-validation-B-psYLaN.js} +2 -2
- package/dist/{upload-validation-IYXn4xcm.js.map → upload-validation-B-psYLaN.js.map} +1 -1
- package/package.json +5 -5
- package/dist/auth-CZGfVKcL.js.map +0 -1
- package/dist/auth_adapter-B7RUMk6e.js.map +0 -1
- package/dist/dist-CT9HJehq.js +0 -22
- package/dist/dist-CT9HJehq.js.map +0 -1
- package/dist/errors-DIWnZIDY.js.map +0 -1
|
@@ -2,7 +2,7 @@ import { createRequire as __rebaseCreateRequire } from "module";
|
|
|
2
2
|
import __rebaseProcess from "process";
|
|
3
3
|
globalThis.process ??= __rebaseProcess;
|
|
4
4
|
__rebaseCreateRequire(import.meta.url);
|
|
5
|
-
import { k as DEFAULT_STORAGE_SOURCE_KEY } from "./src-
|
|
5
|
+
import { k as DEFAULT_STORAGE_SOURCE_KEY } from "./src-BXDkXOtq.js";
|
|
6
6
|
//#region src/storage/keys.ts
|
|
7
7
|
/**
|
|
8
8
|
* Canonical storage keys and bucket names.
|
|
@@ -228,4 +228,4 @@ var InvalidListOptionsError = class extends Error {
|
|
|
228
228
|
//#endregion
|
|
229
229
|
export { canonicalStorageId as a, listingPrefix as c, canonicalStorageBucket as i, InvalidStorageBucketError as n, canonicalStorageKey as o, InvalidStorageKeyError as r, folderKey as s, InvalidListOptionsError as t };
|
|
230
230
|
|
|
231
|
-
//# sourceMappingURL=keys-
|
|
231
|
+
//# sourceMappingURL=keys-Cd_4l48g.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"keys-DJ1ZNcZi.js","names":[],"sources":["../src/storage/keys.ts"],"sourcesContent":["/**\n * Canonical storage keys and bucket names.\n *\n * Storage is not under RLS, so a `storageAuthorize` hook is the whole access\n * control model — and a hook can only be correct if the key it is shown is the\n * key that is written. That is the invariant this module exists to hold: one\n * canonical string, computed once per request, handed to the hook, to the\n * controller, and to the download token alike.\n *\n * ## Why rejecting beats stripping\n *\n * The previous `sanitizeStorageKey` *stripped* `../` in a single pass. Two\n * things were wrong with that, and only one of them was the obvious one.\n *\n * The obvious one: a single pass is not a fixed point. `....//` contains `../`\n * at offset 2, so removing it leaves `../` behind — the sanitizer manufactured\n * the traversal it was there to remove. `users/alice/....//bob/x` came out as\n * `users/alice/../bob/x`, which a prefix hook reads as alice's (it starts with\n * `users/alice/`) and the filesystem reads as bob's. The hook approved one\n * object and the controller wrote another.\n *\n * The subtler one, and the reason this is a rewrite rather than a loop: even a\n * correct strip is a silent rewrite. A caller who asks to store at `a/../b` and\n * gets an object at `a/b` was not protected, they were misled — and every later\n * read, ownership row and audit line now refers to a path nobody chose. So a key\n * that means something other than what it says is refused (400), not repaired.\n *\n * Note what is NOT traversal under this rule: `....` is an ordinary directory\n * name, and `users/alice/....//bob/x` canonicalizes to\n * `users/alice/..../bob/x` — still comfortably inside alice's prefix, which is\n * exactly right. Only a real `..` segment is refused.\n */\n\nimport { DEFAULT_STORAGE_SOURCE_KEY } from \"@rebasepro/types\";\n\n/**\n * `path.posix.normalize`, without `node:path`.\n *\n * A storage key is a POSIX-shaped string that never touches a filesystem, so\n * reaching for `node:path` to fold `.` and `//` out of it was always a little\n * wrong on its own terms — on Windows the platform `path` would have applied\n * different rules to the same key. It also put the module that every storage\n * read, ownership row and audit line goes through on the list of things that\n * only run in a Node process.\n *\n * This is the algorithm Node implements, transcribed: segments are folded left\n * to right, `..` pops unless it would climb past the root of a relative path,\n * and both the leading and the trailing separator survive the round trip. The\n * `..` branch is unreachable from {@link canonicalStorageKey}, which refuses\n * those keys outright before it gets here — it exists so that this function is\n * *the* normalizer rather than a subset of one, and\n * `storage-keys.property.test.ts` holds it to that with a property test against\n * `path.posix.normalize` itself. Exported for exactly that — nothing outside\n * this module should be normalizing a key.\n */\nexport function normalizePosix(input: string): string {\n if (input.length === 0) return \".\";\n const isAbsolute = input.startsWith(\"/\");\n const trailingSeparator = input.endsWith(\"/\");\n\n const segments: string[] = [];\n for (const segment of input.split(\"/\")) {\n if (segment === \"\" || segment === \".\") continue;\n if (segment === \"..\") {\n if (segments.length > 0 && segments[segments.length - 1] !== \"..\") segments.pop();\n else if (!isAbsolute) segments.push(\"..\");\n continue;\n }\n segments.push(segment);\n }\n\n const joined = segments.join(\"/\");\n if (joined === \"\") {\n if (isAbsolute) return \"/\";\n return trailingSeparator ? \"./\" : \".\";\n }\n const withTrailing = trailingSeparator ? `${joined}/` : joined;\n return isAbsolute ? `/${withTrailing}` : withTrailing;\n}\n\n/** Longest key accepted, in UTF-16 code units. Matches the previous cap. */\nexport const MAX_STORAGE_KEY_LENGTH = 1024;\n\n/**\n * A key that cannot be canonicalized. Carries no path back to the caller\n * beyond what they sent, so it is safe to surface as a 400 message.\n */\nexport class InvalidStorageKeyError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"InvalidStorageKeyError\";\n }\n}\n\n/**\n * Canonicalize a caller-supplied storage key, or throw\n * {@link InvalidStorageKeyError}.\n *\n * Normalizations applied (safe, idempotent, and meaning-preserving):\n * - leading slashes removed — `/a/b` and `a/b` name the same object\n * - `.` segments and repeated slashes collapsed\n *\n * Refusals (the key means something other than what it says):\n * - any `..` segment, on either separator, at any depth\n * - null bytes\n * - keys longer than {@link MAX_STORAGE_KEY_LENGTH}\n *\n * A trailing slash is preserved: it is how the folder route marks a prefix.\n */\nexport function canonicalStorageKey(rawKey: string): string {\n if (rawKey.includes(\"\\0\")) {\n throw new InvalidStorageKeyError(\"Storage key contains a null byte.\");\n }\n if (rawKey.length > MAX_STORAGE_KEY_LENGTH) {\n throw new InvalidStorageKeyError(\n `Storage key exceeds the maximum length of ${MAX_STORAGE_KEY_LENGTH} characters.`\n );\n }\n\n // Split on both separators: `path.join` treats `\\` as a separator on\n // Windows, so `..\\` is traversal there even though POSIX reads it as a\n // filename. Checked against the RAW key, before any normalization — the\n // whole point is that `a/../b` is refused rather than quietly turned into\n // `b`.\n if (rawKey.split(/[\\\\/]/).some((segment) => segment === \"..\")) {\n throw new InvalidStorageKeyError(\n \"Storage key contains a '..' path segment. Keys must name an object directly.\"\n );\n }\n\n const withoutLeadingSlashes = rawKey.replace(/^\\/+/, \"\");\n if (withoutLeadingSlashes === \"\") return \"\";\n\n // Whether the key names a *directory* rather than an object: it ends with a\n // separator, or its last segment is the `.` that means \"this directory\".\n //\n // Recorded before normalizing, because normalization drops the\n // distinction in one of those two spellings and not the other: `public/.`\n // becomes `public` while `public/./` stays `public/`. That asymmetry breaks\n // the rule this module states — a trailing slash is preserved, because it is\n // how the folder route marks a prefix — and it is not cosmetic on `list`,\n // where a prefix of `public` also matches `publicity/` and hands back keys\n // the caller never asked for.\n const denotesDirectory = /(?:^|\\/)\\.?$/.test(withoutLeadingSlashes);\n\n // Safe now: with no `..` segment in the input, `normalize` can only collapse\n // `.` and duplicate slashes — it cannot climb.\n const normalized = normalizePosix(withoutLeadingSlashes);\n\n // `normalize(\".\")`, and `normalize(\"./\")` → `./`; neither names an object.\n if (normalized === \".\" || normalized === \"./\") return \"\";\n\n // Defensive: nothing reaching here still carries a leading `./`, since the\n // leading slashes are already gone and `normalize` only emits `./` for a\n // key that normalizes to nothing — which returned above.\n const key = normalized.replace(/^\\.\\//, \"\").replace(/^\\/+/, \"\");\n if (key === \"\") return \"\";\n return denotesDirectory && !key.endsWith(\"/\") ? `${key}/` : key;\n}\n\n/**\n * Canonicalize, or return `null` when the key is not canonicalizable.\n *\n * For callers that must fail closed without an exception — the download-token\n * middleware compares a request path against a granted path, and a key it\n * cannot canonicalize simply matches nothing.\n */\nexport function tryCanonicalStorageKey(rawKey: string): string | null {\n try {\n return canonicalStorageKey(rawKey);\n } catch {\n return null;\n }\n}\n\n/**\n * Canonicalize the storage *source* a request names (`?storageId=`), so that\n * \"the default source\" has exactly one spelling.\n *\n * The default source can be asked for three ways — the parameter omitted, sent\n * empty, or sent as the literal `(default)` — and all three resolve to the same\n * controller. Without a single spelling, the value derived when a download\n * token is minted and the value derived when it is presented can differ for the\n * same object, which is either a spurious 403 or, if the comparison is dropped\n * to stop those, no scoping at all.\n *\n * Deliberately *not* validated against the registry: this is a naming rule, not\n * an existence check, and it must give the same answer in `auth/` (which has no\n * registry) as in the storage routes. An id that names no source still\n * canonicalizes to itself and simply matches only itself.\n */\nexport function canonicalStorageId(rawStorageId: string | undefined | null): string {\n if (rawStorageId === undefined || rawStorageId === null) return DEFAULT_STORAGE_SOURCE_KEY;\n const trimmed = rawStorageId.trim();\n return trimmed === \"\" ? DEFAULT_STORAGE_SOURCE_KEY : trimmed;\n}\n\n/**\n * Longest bucket name accepted. 63 is the S3/GCS limit, and a local bucket is\n * one directory name, so the tighter of the two bounds everything.\n */\nexport const MAX_STORAGE_BUCKET_LENGTH = 63;\n\n/** A bucket name that does not name a bucket. See {@link canonicalStorageBucket}. */\nexport class InvalidStorageBucketError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"InvalidStorageBucketError\";\n }\n}\n\n/**\n * One path segment: letters, digits, `.`, `_`, `-`, first character\n * alphanumeric. Deliberately narrow — it is the intersection of what S3, GCS\n * and a filesystem directory all accept, and it makes `..`, `.tus-uploads`,\n * absolute paths and anything containing a separator unrepresentable.\n */\nconst STORAGE_BUCKET_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\n\n/**\n * Canonicalize a caller-supplied bucket name, or throw\n * {@link InvalidStorageBucketError}.\n *\n * The bucket is the *other* caller-controlled routing value in an upload\n * request, and it was the one nobody validated. `LocalStorageController`\n * builds `join(basePath, bucket)` and then checks containment against that\n * result, so a bucket of `../../etc` moved the boundary rather than crossing\n * it — the guard passed because the guard's reference point was the attacker's.\n * The containment check now resolves against the storage root, and this is the\n * check at the route boundary that stops the value before it gets there.\n *\n * A bucket is configuration, not user data: there is no legitimate caller that\n * needs a separator, a leading dot, or a `..` in one. So this refuses rather\n * than repairs, exactly as {@link canonicalStorageKey} does — a rewritten\n * bucket would silently store the object somewhere the caller did not ask for.\n *\n * Returns `undefined` when the caller named no bucket (absent, or an empty\n * form field), which is how every controller spells \"use my default\". An empty\n * string used to reach `getFullPath` and resolve to the storage *root* rather\n * than the `default` bucket, which is a third place a bare key did not\n * round-trip.\n */\nexport function canonicalStorageBucket(rawBucket: string | undefined | null): string | undefined {\n if (rawBucket === undefined || rawBucket === null || rawBucket === \"\") return undefined;\n if (rawBucket.length > MAX_STORAGE_BUCKET_LENGTH) {\n throw new InvalidStorageBucketError(\n `Storage bucket exceeds the maximum length of ${MAX_STORAGE_BUCKET_LENGTH} characters.`\n );\n }\n if (!STORAGE_BUCKET_PATTERN.test(rawBucket)) {\n throw new InvalidStorageBucketError(\n \"Storage bucket must be a single name of letters, digits, '.', '_' or '-', \" +\n \"starting with a letter or digit.\"\n );\n }\n return rawBucket;\n}\n\n/**\n * The prefix an object store's listing should be given for a caller's key, and\n * the key a listing should hand back for a folder.\n *\n * The three controllers answer the same question in two different ways, and\n * they used to disagree about the answer. `LocalStorageController` resolves a\n * *directory* on disk, so `listObjects(\"products/images\")` and\n * `listObjects(\"products/images/\")` both list what is inside it. An object\n * store under `Delimiter: \"/\"` does not: `Prefix: \"products/images\"` matches\n * `products/images.txt` and `productsomething/`, and returns none of the files\n * inside `products/images/`. So the same call — the SDK's own documented one —\n * answered one thing against local dev and another against the S3 bucket in\n * production, which is the worst place for a divergence to live.\n *\n * `listingPrefix` is what to *send*: a trailing slash, always, because that is\n * the only spelling that means \"inside this folder\" to a delimiter listing.\n * `folderKey` is what to *return* for a common prefix: no trailing slash, the\n * form the local controller has always used, so a `fullPath` from a listing is\n * a key you can pass straight back to any of them.\n */\nexport function listingPrefix(rawPrefix: string): string | undefined {\n const key = rawPrefix.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n return key === \"\" ? undefined : `${key}/`;\n}\n\n/** @see listingPrefix */\nexport function folderKey(rawPrefix: string): string {\n return rawPrefix.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n}\n\n/**\n * A listing asked for paging a controller cannot honour: a page size below one,\n * or a page token it never issued.\n *\n * Refused rather than coerced. A page size of 0 answered an empty page whose\n * next token was the one it had been handed, so `while (pageToken)` never\n * ended; a token of `-1` read before the first entry and crashed. The route\n * turns this into a 400.\n */\nexport class InvalidListOptionsError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"InvalidListOptionsError\";\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,SAAgB,eAAe,OAAuB;CAClD,IAAI,MAAM,WAAW,GAAG,OAAO;CAC/B,MAAM,aAAa,MAAM,WAAW,GAAG;CACvC,MAAM,oBAAoB,MAAM,SAAS,GAAG;CAE5C,MAAM,WAAqB,CAAC;CAC5B,KAAK,MAAM,WAAW,MAAM,MAAM,GAAG,GAAG;EACpC,IAAI,YAAY,MAAM,YAAY,KAAK;EACvC,IAAI,YAAY,MAAM;GAClB,IAAI,SAAS,SAAS,KAAK,SAAS,SAAS,SAAS,OAAO,MAAM,SAAS,IAAI;QAC3E,IAAI,CAAC,YAAY,SAAS,KAAK,IAAI;GACxC;EACJ;EACA,SAAS,KAAK,OAAO;CACzB;CAEA,MAAM,SAAS,SAAS,KAAK,GAAG;CAChC,IAAI,WAAW,IAAI;EACf,IAAI,YAAY,OAAO;EACvB,OAAO,oBAAoB,OAAO;CACtC;CACA,MAAM,eAAe,oBAAoB,GAAG,OAAO,KAAK;CACxD,OAAO,aAAa,IAAI,iBAAiB;AAC7C;;AAGA,IAAa,yBAAyB;;;;;AAMtC,IAAa,yBAAb,cAA4C,MAAM;CAC9C,YAAY,SAAiB;EACzB,MAAM,OAAO;EACb,KAAK,OAAO;CAChB;AACJ;;;;;;;;;;;;;;;;AAiBA,SAAgB,oBAAoB,QAAwB;CACxD,IAAI,OAAO,SAAS,IAAI,GACpB,MAAM,IAAI,uBAAuB,mCAAmC;CAExE,IAAI,OAAO,SAAA,MACP,MAAM,IAAI,uBACN,6CAA6C,uBAAuB,aACxE;CAQJ,IAAI,OAAO,MAAM,OAAO,CAAC,CAAC,MAAM,YAAY,YAAY,IAAI,GACxD,MAAM,IAAI,uBACN,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,QAAQ,EAAE;AAC3D;;;;;;;;;;AAWA,IAAa,0BAAb,cAA6C,MAAM;CAC/C,YAAY,SAAiB;EACzB,MAAM,OAAO;EACb,KAAK,OAAO;CAChB;AACJ"}
|
|
1
|
+
{"version":3,"file":"keys-Cd_4l48g.js","names":[],"sources":["../src/storage/keys.ts"],"sourcesContent":["/**\n * Canonical storage keys and bucket names.\n *\n * Storage is not under RLS, so a `storageAuthorize` hook is the whole access\n * control model — and a hook can only be correct if the key it is shown is the\n * key that is written. That is the invariant this module exists to hold: one\n * canonical string, computed once per request, handed to the hook, to the\n * controller, and to the download token alike.\n *\n * ## Why rejecting beats stripping\n *\n * The previous `sanitizeStorageKey` *stripped* `../` in a single pass. Two\n * things were wrong with that, and only one of them was the obvious one.\n *\n * The obvious one: a single pass is not a fixed point. `....//` contains `../`\n * at offset 2, so removing it leaves `../` behind — the sanitizer manufactured\n * the traversal it was there to remove. `users/alice/....//bob/x` came out as\n * `users/alice/../bob/x`, which a prefix hook reads as alice's (it starts with\n * `users/alice/`) and the filesystem reads as bob's. The hook approved one\n * object and the controller wrote another.\n *\n * The subtler one, and the reason this is a rewrite rather than a loop: even a\n * correct strip is a silent rewrite. A caller who asks to store at `a/../b` and\n * gets an object at `a/b` was not protected, they were misled — and every later\n * read, ownership row and audit line now refers to a path nobody chose. So a key\n * that means something other than what it says is refused (400), not repaired.\n *\n * Note what is NOT traversal under this rule: `....` is an ordinary directory\n * name, and `users/alice/....//bob/x` canonicalizes to\n * `users/alice/..../bob/x` — still comfortably inside alice's prefix, which is\n * exactly right. Only a real `..` segment is refused.\n */\n\nimport { DEFAULT_STORAGE_SOURCE_KEY } from \"@rebasepro/types\";\n\n/**\n * `path.posix.normalize`, without `node:path`.\n *\n * A storage key is a POSIX-shaped string that never touches a filesystem, so\n * reaching for `node:path` to fold `.` and `//` out of it was always a little\n * wrong on its own terms — on Windows the platform `path` would have applied\n * different rules to the same key. It also put the module that every storage\n * read, ownership row and audit line goes through on the list of things that\n * only run in a Node process.\n *\n * This is the algorithm Node implements, transcribed: segments are folded left\n * to right, `..` pops unless it would climb past the root of a relative path,\n * and both the leading and the trailing separator survive the round trip. The\n * `..` branch is unreachable from {@link canonicalStorageKey}, which refuses\n * those keys outright before it gets here — it exists so that this function is\n * *the* normalizer rather than a subset of one, and\n * `storage-keys.property.test.ts` holds it to that with a property test against\n * `path.posix.normalize` itself. Exported for exactly that — nothing outside\n * this module should be normalizing a key.\n */\nexport function normalizePosix(input: string): string {\n if (input.length === 0) return \".\";\n const isAbsolute = input.startsWith(\"/\");\n const trailingSeparator = input.endsWith(\"/\");\n\n const segments: string[] = [];\n for (const segment of input.split(\"/\")) {\n if (segment === \"\" || segment === \".\") continue;\n if (segment === \"..\") {\n if (segments.length > 0 && segments[segments.length - 1] !== \"..\") segments.pop();\n else if (!isAbsolute) segments.push(\"..\");\n continue;\n }\n segments.push(segment);\n }\n\n const joined = segments.join(\"/\");\n if (joined === \"\") {\n if (isAbsolute) return \"/\";\n return trailingSeparator ? \"./\" : \".\";\n }\n const withTrailing = trailingSeparator ? `${joined}/` : joined;\n return isAbsolute ? `/${withTrailing}` : withTrailing;\n}\n\n/** Longest key accepted, in UTF-16 code units. Matches the previous cap. */\nexport const MAX_STORAGE_KEY_LENGTH = 1024;\n\n/**\n * A key that cannot be canonicalized. Carries no path back to the caller\n * beyond what they sent, so it is safe to surface as a 400 message.\n */\nexport class InvalidStorageKeyError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"InvalidStorageKeyError\";\n }\n}\n\n/**\n * Canonicalize a caller-supplied storage key, or throw\n * {@link InvalidStorageKeyError}.\n *\n * Normalizations applied (safe, idempotent, and meaning-preserving):\n * - leading slashes removed — `/a/b` and `a/b` name the same object\n * - `.` segments and repeated slashes collapsed\n *\n * Refusals (the key means something other than what it says):\n * - any `..` segment, on either separator, at any depth\n * - null bytes\n * - keys longer than {@link MAX_STORAGE_KEY_LENGTH}\n *\n * A trailing slash is preserved: it is how the folder route marks a prefix.\n */\nexport function canonicalStorageKey(rawKey: string): string {\n if (rawKey.includes(\"\\0\")) {\n throw new InvalidStorageKeyError(\"Storage key contains a null byte.\");\n }\n if (rawKey.length > MAX_STORAGE_KEY_LENGTH) {\n throw new InvalidStorageKeyError(\n `Storage key exceeds the maximum length of ${MAX_STORAGE_KEY_LENGTH} characters.`\n );\n }\n\n // Split on both separators: `path.join` treats `\\` as a separator on\n // Windows, so `..\\` is traversal there even though POSIX reads it as a\n // filename. Checked against the RAW key, before any normalization — the\n // whole point is that `a/../b` is refused rather than quietly turned into\n // `b`.\n if (rawKey.split(/[\\\\/]/).some((segment) => segment === \"..\")) {\n throw new InvalidStorageKeyError(\n \"Storage key contains a '..' path segment. Keys must name an object directly.\"\n );\n }\n\n const withoutLeadingSlashes = rawKey.replace(/^\\/+/, \"\");\n if (withoutLeadingSlashes === \"\") return \"\";\n\n // Whether the key names a *directory* rather than an object: it ends with a\n // separator, or its last segment is the `.` that means \"this directory\".\n //\n // Recorded before normalizing, because normalization drops the\n // distinction in one of those two spellings and not the other: `public/.`\n // becomes `public` while `public/./` stays `public/`. That asymmetry breaks\n // the rule this module states — a trailing slash is preserved, because it is\n // how the folder route marks a prefix — and it is not cosmetic on `list`,\n // where a prefix of `public` also matches `publicity/` and hands back keys\n // the caller never asked for.\n const denotesDirectory = /(?:^|\\/)\\.?$/.test(withoutLeadingSlashes);\n\n // Safe now: with no `..` segment in the input, `normalize` can only collapse\n // `.` and duplicate slashes — it cannot climb.\n const normalized = normalizePosix(withoutLeadingSlashes);\n\n // `normalize(\".\")`, and `normalize(\"./\")` → `./`; neither names an object.\n if (normalized === \".\" || normalized === \"./\") return \"\";\n\n // Defensive: nothing reaching here still carries a leading `./`, since the\n // leading slashes are already gone and `normalize` only emits `./` for a\n // key that normalizes to nothing — which returned above.\n const key = normalized.replace(/^\\.\\//, \"\").replace(/^\\/+/, \"\");\n if (key === \"\") return \"\";\n return denotesDirectory && !key.endsWith(\"/\") ? `${key}/` : key;\n}\n\n/**\n * Canonicalize, or return `null` when the key is not canonicalizable.\n *\n * For callers that must fail closed without an exception — the download-token\n * middleware compares a request path against a granted path, and a key it\n * cannot canonicalize simply matches nothing.\n */\nexport function tryCanonicalStorageKey(rawKey: string): string | null {\n try {\n return canonicalStorageKey(rawKey);\n } catch {\n return null;\n }\n}\n\n/**\n * Canonicalize the storage *source* a request names (`?storageId=`), so that\n * \"the default source\" has exactly one spelling.\n *\n * The default source can be asked for three ways — the parameter omitted, sent\n * empty, or sent as the literal `(default)` — and all three resolve to the same\n * controller. Without a single spelling, the value derived when a download\n * token is minted and the value derived when it is presented can differ for the\n * same object, which is either a spurious 403 or, if the comparison is dropped\n * to stop those, no scoping at all.\n *\n * Deliberately *not* validated against the registry: this is a naming rule, not\n * an existence check, and it must give the same answer in `auth/` (which has no\n * registry) as in the storage routes. An id that names no source still\n * canonicalizes to itself and simply matches only itself.\n */\nexport function canonicalStorageId(rawStorageId: string | undefined | null): string {\n if (rawStorageId === undefined || rawStorageId === null) return DEFAULT_STORAGE_SOURCE_KEY;\n const trimmed = rawStorageId.trim();\n return trimmed === \"\" ? DEFAULT_STORAGE_SOURCE_KEY : trimmed;\n}\n\n/**\n * Longest bucket name accepted. 63 is the S3/GCS limit, and a local bucket is\n * one directory name, so the tighter of the two bounds everything.\n */\nexport const MAX_STORAGE_BUCKET_LENGTH = 63;\n\n/** A bucket name that does not name a bucket. See {@link canonicalStorageBucket}. */\nexport class InvalidStorageBucketError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"InvalidStorageBucketError\";\n }\n}\n\n/**\n * One path segment: letters, digits, `.`, `_`, `-`, first character\n * alphanumeric. Deliberately narrow — it is the intersection of what S3, GCS\n * and a filesystem directory all accept, and it makes `..`, `.tus-uploads`,\n * absolute paths and anything containing a separator unrepresentable.\n */\nconst STORAGE_BUCKET_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\n\n/**\n * Canonicalize a caller-supplied bucket name, or throw\n * {@link InvalidStorageBucketError}.\n *\n * The bucket is the *other* caller-controlled routing value in an upload\n * request, and it was the one nobody validated. `LocalStorageController`\n * builds `join(basePath, bucket)` and then checks containment against that\n * result, so a bucket of `../../etc` moved the boundary rather than crossing\n * it — the guard passed because the guard's reference point was the attacker's.\n * The containment check now resolves against the storage root, and this is the\n * check at the route boundary that stops the value before it gets there.\n *\n * A bucket is configuration, not user data: there is no legitimate caller that\n * needs a separator, a leading dot, or a `..` in one. So this refuses rather\n * than repairs, exactly as {@link canonicalStorageKey} does — a rewritten\n * bucket would silently store the object somewhere the caller did not ask for.\n *\n * Returns `undefined` when the caller named no bucket (absent, or an empty\n * form field), which is how every controller spells \"use my default\". An empty\n * string used to reach `getFullPath` and resolve to the storage *root* rather\n * than the `default` bucket, which is a third place a bare key did not\n * round-trip.\n */\nexport function canonicalStorageBucket(rawBucket: string | undefined | null): string | undefined {\n if (rawBucket === undefined || rawBucket === null || rawBucket === \"\") return undefined;\n if (rawBucket.length > MAX_STORAGE_BUCKET_LENGTH) {\n throw new InvalidStorageBucketError(\n `Storage bucket exceeds the maximum length of ${MAX_STORAGE_BUCKET_LENGTH} characters.`\n );\n }\n if (!STORAGE_BUCKET_PATTERN.test(rawBucket)) {\n throw new InvalidStorageBucketError(\n \"Storage bucket must be a single name of letters, digits, '.', '_' or '-', \" +\n \"starting with a letter or digit.\"\n );\n }\n return rawBucket;\n}\n\n/**\n * The prefix an object store's listing should be given for a caller's key, and\n * the key a listing should hand back for a folder.\n *\n * The three controllers answer the same question in two different ways, and\n * they used to disagree about the answer. `LocalStorageController` resolves a\n * *directory* on disk, so `listObjects(\"products/images\")` and\n * `listObjects(\"products/images/\")` both list what is inside it. An object\n * store under `Delimiter: \"/\"` does not: `Prefix: \"products/images\"` matches\n * `products/images.txt` and `productsomething/`, and returns none of the files\n * inside `products/images/`. So the same call — the SDK's own documented one —\n * answered one thing against local dev and another against the S3 bucket in\n * production, which is the worst place for a divergence to live.\n *\n * `listingPrefix` is what to *send*: a trailing slash, always, because that is\n * the only spelling that means \"inside this folder\" to a delimiter listing.\n * `folderKey` is what to *return* for a common prefix: no trailing slash, the\n * form the local controller has always used, so a `fullPath` from a listing is\n * a key you can pass straight back to any of them.\n */\nexport function listingPrefix(rawPrefix: string): string | undefined {\n const key = rawPrefix.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n return key === \"\" ? undefined : `${key}/`;\n}\n\n/** @see listingPrefix */\nexport function folderKey(rawPrefix: string): string {\n return rawPrefix.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n}\n\n/**\n * A listing asked for paging a controller cannot honour: a page size below one,\n * or a page token it never issued.\n *\n * Refused rather than coerced. A page size of 0 answered an empty page whose\n * next token was the one it had been handed, so `while (pageToken)` never\n * ended; a token of `-1` read before the first entry and crashed. The route\n * turns this into a 400.\n */\nexport class InvalidListOptionsError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"InvalidListOptionsError\";\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,SAAgB,eAAe,OAAuB;CAClD,IAAI,MAAM,WAAW,GAAG,OAAO;CAC/B,MAAM,aAAa,MAAM,WAAW,GAAG;CACvC,MAAM,oBAAoB,MAAM,SAAS,GAAG;CAE5C,MAAM,WAAqB,CAAC;CAC5B,KAAK,MAAM,WAAW,MAAM,MAAM,GAAG,GAAG;EACpC,IAAI,YAAY,MAAM,YAAY,KAAK;EACvC,IAAI,YAAY,MAAM;GAClB,IAAI,SAAS,SAAS,KAAK,SAAS,SAAS,SAAS,OAAO,MAAM,SAAS,IAAI;QAC3E,IAAI,CAAC,YAAY,SAAS,KAAK,IAAI;GACxC;EACJ;EACA,SAAS,KAAK,OAAO;CACzB;CAEA,MAAM,SAAS,SAAS,KAAK,GAAG;CAChC,IAAI,WAAW,IAAI;EACf,IAAI,YAAY,OAAO;EACvB,OAAO,oBAAoB,OAAO;CACtC;CACA,MAAM,eAAe,oBAAoB,GAAG,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cAAc,QAAQ,cAAc,IAAI,OAAO,KAAA;CAC9E,IAAI,UAAU,SAAA,IACV,MAAM,IAAI,0BACN,6DACJ;CAEJ,IAAI,CAAC,uBAAuB,KAAK,SAAS,GACtC,MAAM,IAAI,0BACN,4GAEJ;CAEJ,OAAO;AACX;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,cAAc,WAAuC;CACjE,MAAM,MAAM,UAAU,QAAQ,QAAQ,EAAE,CAAC,CAAC,QAAQ,QAAQ,EAAE;CAC5D,OAAO,QAAQ,KAAK,KAAA,IAAY,GAAG,IAAI;AAC3C;;AAGA,SAAgB,UAAU,WAA2B;CACjD,OAAO,UAAU,QAAQ,QAAQ,EAAE,CAAC,CAAC,QAAQ,QAAQ,EAAE;AAC3D;;;;;;;;;;AAWA,IAAa,0BAAb,cAA6C,MAAM;CAC/C,YAAY,SAAiB;EACzB,MAAM,OAAO;EACb,KAAK,OAAO;CAChB;AACJ"}
|
|
@@ -4,7 +4,7 @@ globalThis.process ??= __rebaseProcess;
|
|
|
4
4
|
__rebaseCreateRequire(import.meta.url);
|
|
5
5
|
import { n as __exportAll } from "./rolldown-runtime-dW7B1o5h.js";
|
|
6
6
|
import { n as addLogSink } from "./logger-SigQ2oZJ.js";
|
|
7
|
-
import { i as errorHandler, t as ApiError } from "./errors-
|
|
7
|
+
import { i as errorHandler, t as ApiError } from "./errors-DpTMfX77.js";
|
|
8
8
|
import { Hono } from "hono";
|
|
9
9
|
import { streamSSE } from "hono/streaming";
|
|
10
10
|
//#region src/api/logs-routes.ts
|
|
@@ -380,4 +380,4 @@ createLogsRoutes();
|
|
|
380
380
|
//#endregion
|
|
381
381
|
export { logs_routes_exports as n, logMiddleware as t };
|
|
382
382
|
|
|
383
|
-
//# sourceMappingURL=logs-routes-
|
|
383
|
+
//# sourceMappingURL=logs-routes-08LiyYua.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logs-routes-DXLvMasE.js","names":[],"sources":["../src/api/logs-routes.ts"],"sourcesContent":["import { Hono } from \"hono\";\nimport type { MiddlewareHandler } from \"hono\";\nimport { streamSSE } from \"hono/streaming\";\nimport type { HonoEnv } from \"./types\";\nimport { ApiError, errorHandler } from \"./errors\";\nimport { addLogSink } from \"../utils/logger\";\n\nexport interface LogEntry {\n id: string;\n timestamp: string;\n level: \"debug\" | \"info\" | \"warn\" | \"error\";\n source: \"api\" | \"auth\" | \"storage\" | \"realtime\" | \"system\";\n message: string;\n metadata?: Record<string, unknown>;\n}\n\n/** What a caller can narrow the log by, in either direction (query or stream). */\nexport interface LogFilterOptions {\n level?: string;\n source?: string;\n search?: string;\n since?: string;\n}\n\n/**\n * A filter with the search term already lowercased.\n *\n * The distinction matters on the stream path: `query()` lowercases once and then\n * scans, but a subscriber tests one entry at a time and would otherwise redo the\n * same `toLowerCase()` on every request the server handles.\n */\ntype NormalizedFilter = LogFilterOptions;\n\nfunction normalizeFilter(options: LogFilterOptions): NormalizedFilter {\n return { ...options,\n search: options.search?.toLowerCase() };\n}\n\n/**\n * Whether one entry belongs in a filtered view.\n *\n * Shared by the query and the stream on purpose: two copies of this would drift,\n * and the failure that produces is invisible — a tail that quietly shows a\n * different set of lines than the snapshot it started from.\n */\nfunction matchesFilter(entry: LogEntry, filter: NormalizedFilter): boolean {\n if (filter.level && entry.level !== filter.level) return false;\n if (filter.source && entry.source !== filter.source) return false;\n if (filter.search && !entry.message.toLowerCase().includes(filter.search)) return false;\n if (filter.since && entry.timestamp < filter.since) return false;\n return true;\n}\n\n/** Notified for every entry pushed, in push order. */\nexport type LogListener = (entry: LogEntry) => void;\n\nclass LogRingBuffer {\n private buffer: LogEntry[] = [];\n private maxSize: number;\n private idCounter = 0;\n private listeners = new Set<LogListener>();\n\n constructor(maxSize = 10000) {\n this.maxSize = maxSize;\n }\n\n push(entry: Omit<LogEntry, \"id\">): void {\n const id = `log_${++this.idCounter}`;\n const stored: LogEntry = { ...entry,\n id };\n this.buffer.push(stored);\n if (this.buffer.length > this.maxSize) {\n this.buffer.shift();\n }\n // This runs on the request hot path, so a listener must never be able to\n // take the request down with it: a tail that throws loses its own tail,\n // not the response the log line was describing.\n for (const listener of this.listeners) {\n try {\n listener(stored);\n } catch {\n /* a broken tail is not the request's problem */\n }\n }\n }\n\n /**\n * Follow the buffer. Returns the unsubscribe — call it, always: a listener\n * left behind holds its whole closure, and on this class that closure is a\n * pending-entry array.\n *\n * A listener must not log. It is called from inside `push`, so anything that\n * reaches `addLog` from here recurses until the stack gives out.\n */\n subscribe(listener: LogListener): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n query(options: LogFilterOptions & {\n limit?: number;\n offset?: number;\n }): { entries: LogEntry[]; total: number } {\n const filter = normalizeFilter(options);\n const filtered = this.buffer.filter(e => matchesFilter(e, filter));\n\n // Newest first\n const sorted = [...filtered].reverse();\n const total = sorted.length;\n const limit = options.limit || 100;\n const offset = options.offset || 0;\n\n return {\n entries: sorted.slice(offset, offset + limit),\n total\n };\n }\n\n getLatest(count = 50): LogEntry[] {\n return this.buffer.slice(-count).reverse();\n }\n}\n\n// Global singleton\nexport const logBuffer = new LogRingBuffer();\n\n/**\n * Which process this log belongs to.\n *\n * The ring is this process's memory, and nothing gathers the rings of a\n * deployment's other replicas or of its split runtime roles. So a reader is\n * told whose log it is: `HOSTNAME` is the pod name on Kubernetes and the\n * container id under Docker; the pid tells two local processes apart.\n */\nexport function logInstanceName(): string {\n return process.env.HOSTNAME?.trim() || `pid-${process.pid}`;\n}\n\n/** Add a log entry */\nexport function addLog(\n level: LogEntry[\"level\"],\n source: LogEntry[\"source\"],\n message: string,\n metadata?: Record<string, unknown>\n): void {\n logBuffer.push({\n timestamp: new Date().toISOString(),\n level,\n source,\n message,\n metadata\n });\n}\n\nexport interface LogMiddlewareOptions {\n /**\n * Paths this sink ignores, matched exactly against `c.req.path`.\n *\n * For requests whose only reason to exist is to read the log. Recording\n * those makes the reader the loudest thing in its own output, and on a quiet\n * server it is also the thing evicting real entries out of the ring.\n */\n ignorePaths?: string[];\n /**\n * Where the API is mounted (`/api`). The segment after it names the\n * subsystem a request is filed under — see {@link sourceForRequestPath}.\n * Unset, the first segment of the path is read.\n */\n basePath?: string;\n}\n\n/** The first path segment under the base path that files a request under a source other than `api`. */\nconst SOURCE_BY_SEGMENT: Readonly<Record<string, LogEntry[\"source\"]>> = {\n auth: \"auth\",\n oauth: \"auth\",\n storage: \"storage\"\n};\n\n/**\n * The `source` of a request entry: the subsystem its path addresses.\n *\n * `/api/auth/*` and the MCP authorization server under `/api/oauth/*` are\n * `auth`, `/api/storage/*` is `storage`, and everything else is `api`. The\n * Logs Explorer's Source filter matches this field, so a sign-in filed as\n * `api` was invisible under Auth. The realtime socket is not an HTTP request\n * and is not recorded here.\n *\n * Exported for its test.\n */\nexport function sourceForRequestPath(path: string, basePath = \"\"): LogEntry[\"source\"] {\n const base = basePath.replace(/\\/+$/, \"\");\n if (base && path !== base && !path.startsWith(`${base}/`)) return \"api\";\n const segment = path.slice(base.length).split(\"/\").find(part => part !== \"\")?.toLowerCase();\n return (segment !== undefined && Object.prototype.hasOwnProperty.call(SOURCE_BY_SEGMENT, segment))\n ? SOURCE_BY_SEGMENT[segment]\n : \"api\";\n}\n\n/** Hono middleware to log API requests */\nexport function logMiddleware(options: LogMiddlewareOptions = {}): MiddlewareHandler<HonoEnv> {\n const ignored = new Set(options.ignorePaths ?? []);\n return async (c, next) => {\n const start = Date.now();\n await next();\n if (ignored.has(c.req.path)) return;\n const duration = Date.now() - start;\n const reqId = c.get(\"requestId\");\n // Every request used to be recorded at `info`, whatever it answered, so\n // the Logs Explorer's level filter could not find a single failure: a\n // 500 sat at the same level as the 200 above it, in a wall of them.\n const status = c.res.status;\n const level: LogEntry[\"level\"] = status >= 500 ? \"error\" : status >= 400 ? \"warn\" : \"info\";\n // What the error handler answered, so the failure is on the entry\n // rather than in a stdout line the panel cannot see. See\n // `HonoEnv.Variables.errorSummary`.\n const failure = c.get(\"errorSummary\");\n addLog(\n level,\n sourceForRequestPath(c.req.path, options.basePath),\n `${c.req.method} ${c.req.path} ${status} ${duration}ms`\n + (failure ? ` — ${failure.code}: ${failure.message}` : \"\"),\n {\n method: c.req.method,\n path: c.req.path,\n status,\n duration,\n ...(reqId && { requestId: reqId }),\n ...(c.get(\"collection\") && { collection: c.get(\"collection\") }),\n ...(failure && { errorCode: failure.code, errorMessage: failure.message })\n }\n );\n };\n}\n\n/**\n * Prefixes the server writes at the head of a log message, and the `source`\n * each one belongs to.\n *\n * The ring's `source` is a closed set the Studio filters on, and the messages\n * carry their origin as a bracketed prefix — `[API]`, `[Auth]`, `[functions]`,\n * `[schema]`. Matching them is what makes a teed line filterable beside the\n * request entries rather than a heap under \"system\".\n */\nconst SOURCE_BY_PREFIX: Array<[RegExp, LogEntry[\"source\"]]> = [\n [/^\\[?(api|rest)\\b/i, \"api\"],\n [/^\\[?auth\\b/i, \"auth\"],\n [/^\\[?(storage|s3|gcs)\\b/i, \"storage\"],\n [/^\\[?(realtime|ws|websocket|cdc)\\b/i, \"realtime\"]\n];\n\n/**\n * The `source` for a teed line, from whatever prefix it carries.\n *\n * Exported for its test: the mapping is a string match on wording somebody else\n * writes, which is the shape of check that stops working without failing.\n */\nexport function sourceForMessage(message: string): LogEntry[\"source\"] {\n // The level emoji comes first on several call sites (`⚠️ [API] …`), so the\n // prefix is whatever is inside the first bracket, wherever that is.\n const bracketed = message.match(/\\[([^\\]]{1,32})\\]/);\n const candidate = bracketed?.[1] ?? message;\n for (const [pattern, source] of SOURCE_BY_PREFIX) {\n if (pattern.test(candidate)) return source;\n }\n return \"system\";\n}\n\n/**\n * Feed the Logs Explorer everything the server says at warn and above.\n *\n * The ring used to be filled by `logMiddleware` alone, so the panel showed a\n * wall of `GET /api/data/posts 200 4ms` and not one of the errors, warnings or\n * boot diagnoses being written to stdout at the same moment. A function that\n * threw was the sharpest case: the request entry said `500` and the reason\n * existed only in a terminal the person looking at the panel does not have.\n *\n * Warn and above, deliberately. `info` is where the steady-state chatter lives,\n * and a 10,000-entry ring filled with it evicts the lines somebody opened the\n * panel to find.\n *\n * Idempotent: called from `createLogsRoutes`, which a split deployment may\n * reach more than once.\n */\nlet detachLoggerTee: (() => void) | undefined;\nexport function teeLoggerIntoLogBuffer(): () => void {\n if (detachLoggerTee) return detachLoggerTee;\n const detach = addLogSink((level, message, data) => {\n if (level !== \"warn\" && level !== \"error\") return;\n // `requestLogger` writes this one to stdout for every request, and\n // `logMiddleware` has already recorded the same request here with the\n // fields this panel renders. Teeing it too would double every failure.\n if (message === \"request\") return;\n addLog(level, sourceForMessage(message), message, Object.keys(data).length > 0 ? data : undefined);\n });\n detachLoggerTee = () => {\n detach();\n detachLoggerTee = undefined;\n };\n return detachLoggerTee;\n}\n\n/**\n * How long entries accumulate before a batch goes out.\n *\n * Not zero, and that is the point. A busy server logs faster than a browser can\n * render, and one SSE frame per line would hand the client a re-render per\n * request served — worse than the 3s poll this replaces, precisely when the logs\n * are worth watching. Coalescing keeps the frame rate bounded by the window\n * rather than by traffic, and 250ms still reads as \"live\" to a person.\n */\nconst STREAM_FLUSH_MS = 250;\n\n/**\n * Idle gap after which the stream sends a comment line.\n *\n * A silent SSE connection is indistinguishable from a dead one to everything in\n * between — proxies, load balancers and laptop NICs all reap idle sockets, and a\n * server with nothing to say is the normal state here.\n */\nconst STREAM_HEARTBEAT_MS = 25_000;\n\n/**\n * Entries a single connection will hold between flushes.\n *\n * This is a *rate* ceiling, not just a memory bound, and that is easy to get\n * wrong: nothing drains `pending` between flushes, so the most a connection can\n * carry losslessly is `maxPending` per `flushMs` — here 2000 per 250ms, or 8000\n * entries a second. Above that the oldest pending entries go and the client is\n * told how many, whatever speed it is reading at.\n *\n * It was 500, which put that ceiling at 2000/s. A healthy reader on a loopback\n * socket lost 85% of a 20k burst to it — the cap fired on the server's own\n * coalescing window rather than on any slowness at the client, which is a drop\n * notice that says nothing true about why. 8000/s is past what one Node process\n * serves, so reaching it now means genuinely more log than a person can be shown.\n *\n * The memory this bounds is the copy a *stalled* reader causes: roughly 2000\n * entries, a few MB, per stuck connection.\n */\nconst STREAM_MAX_PENDING = 2000;\n\n/**\n * The largest window any of these routes will hand back.\n *\n * The ring buffer holds 10,000 entries, so asking for more than all of it is a\n * mistake worth naming rather than silently clamping — and a clamped answer is\n * indistinguishable from \"that is all there is\".\n */\nconst LOG_WINDOW_MAX = 10_000;\n\n/**\n * The stream's timings, injectable only so they can be tested.\n *\n * The defaults above are the contract and nothing in production passes this. A\n * heartbeat is a 25-second wait to observe, and a suite that cannot observe it is\n * a suite where the keepalive can rot — which surfaces as \"the tail dies after a\n * few minutes behind the load balancer\", months later, on someone else's cluster.\n */\nexport interface LogStreamTiming {\n flushMs?: number;\n heartbeatMs?: number;\n maxPending?: number;\n}\n\n/** What ends the stream from the server's side. */\nexport interface LogsRoutesOptions {\n /**\n * Aborted when the backend shuts down. Every open stream ends then, rather\n * than when its client happens to leave: `server.close()` waits on every\n * open connection, so one Studio → Logs tab held a SIGTERM for the whole\n * force timeout — longer than Cloud Run's or `docker stop`'s grace period,\n * which killed the process before the pool was closed.\n */\n closeSignal?: AbortSignal;\n}\n\nexport function createLogsRoutes(timing: LogStreamTiming = {}, options: LogsRoutesOptions = {}): Hono<HonoEnv> {\n // Here rather than at module load: the ring exists whether or not anything\n // reads it, but there is no reason to fill it on a process that serves no\n // logs surface. Idempotent, so the repeated calls a split deployment makes\n // do not stack up sinks.\n teeLoggerIntoLogBuffer();\n\n const flushMs = timing.flushMs ?? STREAM_FLUSH_MS;\n const heartbeatMs = timing.heartbeatMs ?? STREAM_HEARTBEAT_MS;\n const maxPending = timing.maxPending ?? STREAM_MAX_PENDING;\n\n const app = new Hono<HonoEnv>();\n // Its own, like every other router here: nothing registers one on the host\n // app — not `boot.ts`, not the scaffolded backend, not the eject template —\n // so a router that throws without this answers Hono's default 500 in plain\n // text, outside the `{ error: { code, message } }` envelope the rest of the\n // API keeps to.\n app.onError(errorHandler);\n\n /**\n * A window into the ring buffer, or a 400 saying why not.\n *\n * `parseInt` was the whole of it before, and every malformed value failed\n * differently and silently: `?limit=abc` fell through to the default,\n * `?limit=-5` sliced an empty window and answered 200 with no entries, and\n * `?count=abc` made `slice(-NaN)` return the *entire* buffer. Three ways to\n * be wrong, none of them visible to the caller. The data plane refuses the\n * same input with a 400 — see `resolveListLimitParam`.\n *\n * `min` is 1 for a size and 0 for an offset: `?offset=0` is the first page,\n * which is where every pager starts, and it was a 400.\n */\n const window = (raw: string | undefined, what: string, max: number, min = 1): number | undefined => {\n if (raw === undefined || raw.trim() === \"\") return undefined;\n const parsed = Number(raw.trim());\n if (!Number.isInteger(parsed) || parsed < min || parsed > max) {\n throw new ApiError(\n 400,\n \"INVALID_PARAM\",\n `Invalid \\`${what}\\`: ${raw}. Expected a whole number between ${min} and ${max}.`,\n undefined,\n true\n );\n }\n return parsed;\n };\n\n // GET /api/logs — Query logs\n app.get(\"/\", (c) => {\n const query = c.req.query();\n const result = logBuffer.query({\n level: query.level,\n source: query.source,\n search: query.search,\n limit: window(query.limit, \"limit\", LOG_WINDOW_MAX),\n offset: window(query.offset, \"offset\", Number.MAX_SAFE_INTEGER, 0),\n since: query.since\n });\n return c.json(result);\n });\n\n // GET /api/logs/latest — Get latest logs (for real-time)\n app.get(\"/latest\", (c) => {\n const count = window(c.req.query(\"count\"), \"count\", LOG_WINDOW_MAX) ?? 50;\n return c.json({ entries: logBuffer.getLatest(count) });\n });\n\n // GET /api/logs/stream — tail the buffer over SSE.\n //\n // The Logs Explorer used to poll this router every 3 seconds, which cost a\n // request per client per 3s to say \"nothing happened\" and still showed each\n // line up to 3s late. Here the buffer pushes instead, so an idle server is an\n // idle socket.\n //\n // Events:\n // snapshot {entries, total, instance}\n // the filtered window, oldest-first, at open,\n // and the process whose ring it is\n // append {entries, dropped} entries since the last frame, oldest-first\n // `: ping` comment, keepalive only\n //\n // Snapshot and appends come down the same connection deliberately. A client\n // that fetched its backlog separately would race the subscription — entries\n // logged between the two calls belong to neither — and closing that race from\n // the outside needs an id cursor and dedupe on every frame.\n app.get(\"/stream\", (c) => {\n const query = c.req.query();\n const filter = normalizeFilter({\n level: query.level,\n source: query.source,\n search: query.search\n });\n const limit = window(query.limit, \"limit\", LOG_WINDOW_MAX) ?? 200;\n\n // Reverse proxies buffer text responses by default, which turns a live\n // tail into nothing at all until the buffer fills. nginx (and the ingress\n // in front of the managed runtime) reads this header; everything else\n // ignores it. The rest of the SSE headers are set by `streamSSE`.\n c.header(\"X-Accel-Buffering\", \"no\");\n\n return streamSSE(c, async (stream) => {\n let pending: LogEntry[] = [];\n let dropped = 0;\n\n // Subscribe *before* reading the backlog, with nothing awaited\n // between the two. Both are synchronous, so the two halves meet\n // exactly: an entry logged after the query but before the\n // subscription would otherwise be in neither, and that gap is the one\n // thing this route exists to close.\n const unsubscribe = logBuffer.subscribe(entry => {\n if (!matchesFilter(entry, filter)) return;\n if (pending.length >= maxPending) {\n pending.shift();\n dropped++;\n }\n pending.push(entry);\n });\n const snapshot = logBuffer.query({ ...filter,\n limit });\n\n // A client that goes away has to end this handler, or the\n // subscription outlives the socket. `streamSSE` only wires the\n // request signal through on old Bun, so do it here and let\n // `stream.aborted` be the one condition the loop tests.\n //\n // The `aborted` check is not belt-and-braces. A listener added to an\n // already-aborted signal is never called, so a client that leaves\n // during the snapshot write — a fast navigation, or a reconnect storm\n // against a restarting server — would leave this handler with no way\n // to learn it had gone: a subscriber and a flush loop, per attempt,\n // for the life of the process.\n const abortOnDisconnect = () => {\n if (!stream.closed) stream.abort();\n };\n c.req.raw.signal.addEventListener(\"abort\", abortOnDisconnect, { once: true });\n if (c.req.raw.signal.aborted) abortOnDisconnect();\n // The server going away ends it the same way, for the same reason\n // the client going away does — and a stream opened after shutdown\n // began still sends its snapshot, then ends.\n const closeSignal = options.closeSignal;\n closeSignal?.addEventListener(\"abort\", abortOnDisconnect, { once: true });\n if (closeSignal?.aborted) abortOnDisconnect();\n\n try {\n await stream.writeSSE({\n event: \"snapshot\",\n // The view tails like a terminal; both frames are oldest-first\n // so the client only ever appends.\n data: JSON.stringify({\n entries: snapshot.entries.slice().reverse(),\n total: snapshot.total,\n instance: logInstanceName()\n })\n });\n\n let idleMs = 0;\n while (!stream.aborted && !stream.closed) {\n await stream.sleep(flushMs);\n if (stream.aborted || stream.closed) break;\n\n if (pending.length === 0) {\n idleMs += flushMs;\n if (idleMs >= heartbeatMs) {\n await stream.write(\": ping\\n\\n\");\n idleMs = 0;\n }\n continue;\n }\n\n const entries = pending;\n const lost = dropped;\n pending = [];\n dropped = 0;\n idleMs = 0;\n await stream.writeSSE({\n event: \"append\",\n data: JSON.stringify(lost > 0 ? { entries,\n dropped: lost } : { entries })\n });\n }\n } finally {\n unsubscribe();\n c.req.raw.signal.removeEventListener(\"abort\", abortOnDisconnect);\n closeSignal?.removeEventListener(\"abort\", abortOnDisconnect);\n }\n });\n });\n\n return app;\n}\n\nexport default createLogsRoutes();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAiCA,SAAS,gBAAgB,SAA6C;CAClE,OAAO;EAAE,GAAG;EACR,QAAQ,QAAQ,QAAQ,YAAY;CAAE;AAC9C;;;;;;;;AASA,SAAS,cAAc,OAAiB,QAAmC;CACvE,IAAI,OAAO,SAAS,MAAM,UAAU,OAAO,OAAO,OAAO;CACzD,IAAI,OAAO,UAAU,MAAM,WAAW,OAAO,QAAQ,OAAO;CAC5D,IAAI,OAAO,UAAU,CAAC,MAAM,QAAQ,YAAY,CAAC,CAAC,SAAS,OAAO,MAAM,GAAG,OAAO;CAClF,IAAI,OAAO,SAAS,MAAM,YAAY,OAAO,OAAO,OAAO;CAC3D,OAAO;AACX;AAKA,IAAM,gBAAN,MAAoB;CAChB,SAA6B,CAAC;CAC9B;CACA,YAAoB;CACpB,4BAAoB,IAAI,IAAiB;CAEzC,YAAY,UAAU,KAAO;EACzB,KAAK,UAAU;CACnB;CAEA,KAAK,OAAmC;EACpC,MAAM,KAAK,OAAO,EAAE,KAAK;EACzB,MAAM,SAAmB;GAAE,GA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O,iBAAiB,SAAS,mBAAmB,EAAE,MAAM,KAAK,CAAC;GAC5E,IAAI,EAAE,IAAI,IAAI,OAAO,SAAS,kBAAkB;GAIhD,MAAM,cAAc,QAAQ;GAC5B,aAAa,iBAAiB,SAAS,mBAAmB,EAAE,MAAM,KAAK,CAAC;GACxE,IAAI,aAAa,SAAS,kBAAkB;GAE5C,IAAI;IACA,MAAM,OAAO,SAAS;KAClB,OAAO;KAGP,MAAM,KAAK,UAAU;MACjB,SAAS,SAAS,QAAQ,MAAM,CAAC,CAAC,QAAQ;MAC1C,OAAO,SAAS;MAChB,UAAU,gBAAgB;KAC9B,CAAC;IACL,CAAC;IAED,IAAI,SAAS;IACb,OAAO,CAAC,OAAO,WAAW,CAAC,OAAO,QAAQ;KACtC,MAAM,OAAO,MAAM,OAAO;KAC1B,IAAI,OAAO,WAAW,OAAO,QAAQ;KAErC,IAAI,QAAQ,WAAW,GAAG;MACtB,UAAU;MACV,IAAI,UAAU,aAAa;OACvB,MAAM,OAAO,MAAM,YAAY;OAC/B,SAAS;MACb;MACA;KACJ;KAEA,MAAM,UAAU;KAChB,MAAM,OAAO;KACb,UAAU,CAAC;KACX,UAAU;KACV,SAAS;KACT,MAAM,OAAO,SAAS;MAClB,OAAO;MACP,MAAM,KAAK,UAAU,OAAO,IAAI;OAAE;OAC9B,SAAS;MAAK,IAAI,EAAE,QAAQ,CAAC;KACrC,CAAC;IACL;GACJ,UAAU;IACN,YAAY;IACZ,EAAE,IAAI,IAAI,OAAO,oBAAoB,SAAS,iBAAiB;IAC/D,aAAa,oBAAoB,SAAS,iBAAiB;GAC/D;EACJ,CAAC;CACL,CAAC;CAED,OAAO;AACX;AAEe,iBAAiB"}
|
|
1
|
+
{"version":3,"file":"logs-routes-08LiyYua.js","names":[],"sources":["../src/api/logs-routes.ts"],"sourcesContent":["import { Hono } from \"hono\";\nimport type { MiddlewareHandler } from \"hono\";\nimport { streamSSE } from \"hono/streaming\";\nimport type { HonoEnv } from \"./types\";\nimport { ApiError, errorHandler } from \"./errors\";\nimport { addLogSink } from \"../utils/logger\";\n\nexport interface LogEntry {\n id: string;\n timestamp: string;\n level: \"debug\" | \"info\" | \"warn\" | \"error\";\n source: \"api\" | \"auth\" | \"storage\" | \"realtime\" | \"system\";\n message: string;\n metadata?: Record<string, unknown>;\n}\n\n/** What a caller can narrow the log by, in either direction (query or stream). */\nexport interface LogFilterOptions {\n level?: string;\n source?: string;\n search?: string;\n since?: string;\n}\n\n/**\n * A filter with the search term already lowercased.\n *\n * The distinction matters on the stream path: `query()` lowercases once and then\n * scans, but a subscriber tests one entry at a time and would otherwise redo the\n * same `toLowerCase()` on every request the server handles.\n */\ntype NormalizedFilter = LogFilterOptions;\n\nfunction normalizeFilter(options: LogFilterOptions): NormalizedFilter {\n return { ...options,\n search: options.search?.toLowerCase() };\n}\n\n/**\n * Whether one entry belongs in a filtered view.\n *\n * Shared by the query and the stream on purpose: two copies of this would drift,\n * and the failure that produces is invisible — a tail that quietly shows a\n * different set of lines than the snapshot it started from.\n */\nfunction matchesFilter(entry: LogEntry, filter: NormalizedFilter): boolean {\n if (filter.level && entry.level !== filter.level) return false;\n if (filter.source && entry.source !== filter.source) return false;\n if (filter.search && !entry.message.toLowerCase().includes(filter.search)) return false;\n if (filter.since && entry.timestamp < filter.since) return false;\n return true;\n}\n\n/** Notified for every entry pushed, in push order. */\nexport type LogListener = (entry: LogEntry) => void;\n\nclass LogRingBuffer {\n private buffer: LogEntry[] = [];\n private maxSize: number;\n private idCounter = 0;\n private listeners = new Set<LogListener>();\n\n constructor(maxSize = 10000) {\n this.maxSize = maxSize;\n }\n\n push(entry: Omit<LogEntry, \"id\">): void {\n const id = `log_${++this.idCounter}`;\n const stored: LogEntry = { ...entry,\n id };\n this.buffer.push(stored);\n if (this.buffer.length > this.maxSize) {\n this.buffer.shift();\n }\n // This runs on the request hot path, so a listener must never be able to\n // take the request down with it: a tail that throws loses its own tail,\n // not the response the log line was describing.\n for (const listener of this.listeners) {\n try {\n listener(stored);\n } catch {\n /* a broken tail is not the request's problem */\n }\n }\n }\n\n /**\n * Follow the buffer. Returns the unsubscribe — call it, always: a listener\n * left behind holds its whole closure, and on this class that closure is a\n * pending-entry array.\n *\n * A listener must not log. It is called from inside `push`, so anything that\n * reaches `addLog` from here recurses until the stack gives out.\n */\n subscribe(listener: LogListener): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n query(options: LogFilterOptions & {\n limit?: number;\n offset?: number;\n }): { entries: LogEntry[]; total: number } {\n const filter = normalizeFilter(options);\n const filtered = this.buffer.filter(e => matchesFilter(e, filter));\n\n // Newest first\n const sorted = [...filtered].reverse();\n const total = sorted.length;\n const limit = options.limit || 100;\n const offset = options.offset || 0;\n\n return {\n entries: sorted.slice(offset, offset + limit),\n total\n };\n }\n\n getLatest(count = 50): LogEntry[] {\n return this.buffer.slice(-count).reverse();\n }\n}\n\n// Global singleton\nexport const logBuffer = new LogRingBuffer();\n\n/**\n * Which process this log belongs to.\n *\n * The ring is this process's memory, and nothing gathers the rings of a\n * deployment's other replicas or of its split runtime roles. So a reader is\n * told whose log it is: `HOSTNAME` is the pod name on Kubernetes and the\n * container id under Docker; the pid tells two local processes apart.\n */\nexport function logInstanceName(): string {\n return process.env.HOSTNAME?.trim() || `pid-${process.pid}`;\n}\n\n/** Add a log entry */\nexport function addLog(\n level: LogEntry[\"level\"],\n source: LogEntry[\"source\"],\n message: string,\n metadata?: Record<string, unknown>\n): void {\n logBuffer.push({\n timestamp: new Date().toISOString(),\n level,\n source,\n message,\n metadata\n });\n}\n\nexport interface LogMiddlewareOptions {\n /**\n * Paths this sink ignores, matched exactly against `c.req.path`.\n *\n * For requests whose only reason to exist is to read the log. Recording\n * those makes the reader the loudest thing in its own output, and on a quiet\n * server it is also the thing evicting real entries out of the ring.\n */\n ignorePaths?: string[];\n /**\n * Where the API is mounted (`/api`). The segment after it names the\n * subsystem a request is filed under — see {@link sourceForRequestPath}.\n * Unset, the first segment of the path is read.\n */\n basePath?: string;\n}\n\n/** The first path segment under the base path that files a request under a source other than `api`. */\nconst SOURCE_BY_SEGMENT: Readonly<Record<string, LogEntry[\"source\"]>> = {\n auth: \"auth\",\n oauth: \"auth\",\n storage: \"storage\"\n};\n\n/**\n * The `source` of a request entry: the subsystem its path addresses.\n *\n * `/api/auth/*` and the MCP authorization server under `/api/oauth/*` are\n * `auth`, `/api/storage/*` is `storage`, and everything else is `api`. The\n * Logs Explorer's Source filter matches this field, so a sign-in filed as\n * `api` was invisible under Auth. The realtime socket is not an HTTP request\n * and is not recorded here.\n *\n * Exported for its test.\n */\nexport function sourceForRequestPath(path: string, basePath = \"\"): LogEntry[\"source\"] {\n const base = basePath.replace(/\\/+$/, \"\");\n if (base && path !== base && !path.startsWith(`${base}/`)) return \"api\";\n const segment = path.slice(base.length).split(\"/\").find(part => part !== \"\")?.toLowerCase();\n return (segment !== undefined && Object.prototype.hasOwnProperty.call(SOURCE_BY_SEGMENT, segment))\n ? SOURCE_BY_SEGMENT[segment]\n : \"api\";\n}\n\n/** Hono middleware to log API requests */\nexport function logMiddleware(options: LogMiddlewareOptions = {}): MiddlewareHandler<HonoEnv> {\n const ignored = new Set(options.ignorePaths ?? []);\n return async (c, next) => {\n const start = Date.now();\n await next();\n if (ignored.has(c.req.path)) return;\n const duration = Date.now() - start;\n const reqId = c.get(\"requestId\");\n // Every request used to be recorded at `info`, whatever it answered, so\n // the Logs Explorer's level filter could not find a single failure: a\n // 500 sat at the same level as the 200 above it, in a wall of them.\n const status = c.res.status;\n const level: LogEntry[\"level\"] = status >= 500 ? \"error\" : status >= 400 ? \"warn\" : \"info\";\n // What the error handler answered, so the failure is on the entry\n // rather than in a stdout line the panel cannot see. See\n // `HonoEnv.Variables.errorSummary`.\n const failure = c.get(\"errorSummary\");\n addLog(\n level,\n sourceForRequestPath(c.req.path, options.basePath),\n `${c.req.method} ${c.req.path} ${status} ${duration}ms`\n + (failure ? ` — ${failure.code}: ${failure.message}` : \"\"),\n {\n method: c.req.method,\n path: c.req.path,\n status,\n duration,\n ...(reqId && { requestId: reqId }),\n ...(c.get(\"collection\") && { collection: c.get(\"collection\") }),\n ...(failure && { errorCode: failure.code, errorMessage: failure.message })\n }\n );\n };\n}\n\n/**\n * Prefixes the server writes at the head of a log message, and the `source`\n * each one belongs to.\n *\n * The ring's `source` is a closed set the Studio filters on, and the messages\n * carry their origin as a bracketed prefix — `[API]`, `[Auth]`, `[functions]`,\n * `[schema]`. Matching them is what makes a teed line filterable beside the\n * request entries rather than a heap under \"system\".\n */\nconst SOURCE_BY_PREFIX: Array<[RegExp, LogEntry[\"source\"]]> = [\n [/^\\[?(api|rest)\\b/i, \"api\"],\n [/^\\[?auth\\b/i, \"auth\"],\n [/^\\[?(storage|s3|gcs)\\b/i, \"storage\"],\n [/^\\[?(realtime|ws|websocket|cdc)\\b/i, \"realtime\"]\n];\n\n/**\n * The `source` for a teed line, from whatever prefix it carries.\n *\n * Exported for its test: the mapping is a string match on wording somebody else\n * writes, which is the shape of check that stops working without failing.\n */\nexport function sourceForMessage(message: string): LogEntry[\"source\"] {\n // The level emoji comes first on several call sites (`⚠️ [API] …`), so the\n // prefix is whatever is inside the first bracket, wherever that is.\n const bracketed = message.match(/\\[([^\\]]{1,32})\\]/);\n const candidate = bracketed?.[1] ?? message;\n for (const [pattern, source] of SOURCE_BY_PREFIX) {\n if (pattern.test(candidate)) return source;\n }\n return \"system\";\n}\n\n/**\n * Feed the Logs Explorer everything the server says at warn and above.\n *\n * The ring used to be filled by `logMiddleware` alone, so the panel showed a\n * wall of `GET /api/data/posts 200 4ms` and not one of the errors, warnings or\n * boot diagnoses being written to stdout at the same moment. A function that\n * threw was the sharpest case: the request entry said `500` and the reason\n * existed only in a terminal the person looking at the panel does not have.\n *\n * Warn and above, deliberately. `info` is where the steady-state chatter lives,\n * and a 10,000-entry ring filled with it evicts the lines somebody opened the\n * panel to find.\n *\n * Idempotent: called from `createLogsRoutes`, which a split deployment may\n * reach more than once.\n */\nlet detachLoggerTee: (() => void) | undefined;\nexport function teeLoggerIntoLogBuffer(): () => void {\n if (detachLoggerTee) return detachLoggerTee;\n const detach = addLogSink((level, message, data) => {\n if (level !== \"warn\" && level !== \"error\") return;\n // `requestLogger` writes this one to stdout for every request, and\n // `logMiddleware` has already recorded the same request here with the\n // fields this panel renders. Teeing it too would double every failure.\n if (message === \"request\") return;\n addLog(level, sourceForMessage(message), message, Object.keys(data).length > 0 ? data : undefined);\n });\n detachLoggerTee = () => {\n detach();\n detachLoggerTee = undefined;\n };\n return detachLoggerTee;\n}\n\n/**\n * How long entries accumulate before a batch goes out.\n *\n * Not zero, and that is the point. A busy server logs faster than a browser can\n * render, and one SSE frame per line would hand the client a re-render per\n * request served — worse than the 3s poll this replaces, precisely when the logs\n * are worth watching. Coalescing keeps the frame rate bounded by the window\n * rather than by traffic, and 250ms still reads as \"live\" to a person.\n */\nconst STREAM_FLUSH_MS = 250;\n\n/**\n * Idle gap after which the stream sends a comment line.\n *\n * A silent SSE connection is indistinguishable from a dead one to everything in\n * between — proxies, load balancers and laptop NICs all reap idle sockets, and a\n * server with nothing to say is the normal state here.\n */\nconst STREAM_HEARTBEAT_MS = 25_000;\n\n/**\n * Entries a single connection will hold between flushes.\n *\n * This is a *rate* ceiling, not just a memory bound, and that is easy to get\n * wrong: nothing drains `pending` between flushes, so the most a connection can\n * carry losslessly is `maxPending` per `flushMs` — here 2000 per 250ms, or 8000\n * entries a second. Above that the oldest pending entries go and the client is\n * told how many, whatever speed it is reading at.\n *\n * It was 500, which put that ceiling at 2000/s. A healthy reader on a loopback\n * socket lost 85% of a 20k burst to it — the cap fired on the server's own\n * coalescing window rather than on any slowness at the client, which is a drop\n * notice that says nothing true about why. 8000/s is past what one Node process\n * serves, so reaching it now means genuinely more log than a person can be shown.\n *\n * The memory this bounds is the copy a *stalled* reader causes: roughly 2000\n * entries, a few MB, per stuck connection.\n */\nconst STREAM_MAX_PENDING = 2000;\n\n/**\n * The largest window any of these routes will hand back.\n *\n * The ring buffer holds 10,000 entries, so asking for more than all of it is a\n * mistake worth naming rather than silently clamping — and a clamped answer is\n * indistinguishable from \"that is all there is\".\n */\nconst LOG_WINDOW_MAX = 10_000;\n\n/**\n * The stream's timings, injectable only so they can be tested.\n *\n * The defaults above are the contract and nothing in production passes this. A\n * heartbeat is a 25-second wait to observe, and a suite that cannot observe it is\n * a suite where the keepalive can rot — which surfaces as \"the tail dies after a\n * few minutes behind the load balancer\", months later, on someone else's cluster.\n */\nexport interface LogStreamTiming {\n flushMs?: number;\n heartbeatMs?: number;\n maxPending?: number;\n}\n\n/** What ends the stream from the server's side. */\nexport interface LogsRoutesOptions {\n /**\n * Aborted when the backend shuts down. Every open stream ends then, rather\n * than when its client happens to leave: `server.close()` waits on every\n * open connection, so one Studio → Logs tab held a SIGTERM for the whole\n * force timeout — longer than Cloud Run's or `docker stop`'s grace period,\n * which killed the process before the pool was closed.\n */\n closeSignal?: AbortSignal;\n}\n\nexport function createLogsRoutes(timing: LogStreamTiming = {}, options: LogsRoutesOptions = {}): Hono<HonoEnv> {\n // Here rather than at module load: the ring exists whether or not anything\n // reads it, but there is no reason to fill it on a process that serves no\n // logs surface. Idempotent, so the repeated calls a split deployment makes\n // do not stack up sinks.\n teeLoggerIntoLogBuffer();\n\n const flushMs = timing.flushMs ?? STREAM_FLUSH_MS;\n const heartbeatMs = timing.heartbeatMs ?? STREAM_HEARTBEAT_MS;\n const maxPending = timing.maxPending ?? STREAM_MAX_PENDING;\n\n const app = new Hono<HonoEnv>();\n // Its own, like every other router here: nothing registers one on the host\n // app — not `boot.ts`, not the scaffolded backend, not the eject template —\n // so a router that throws without this answers Hono's default 500 in plain\n // text, outside the `{ error: { code, message } }` envelope the rest of the\n // API keeps to.\n app.onError(errorHandler);\n\n /**\n * A window into the ring buffer, or a 400 saying why not.\n *\n * `parseInt` was the whole of it before, and every malformed value failed\n * differently and silently: `?limit=abc` fell through to the default,\n * `?limit=-5` sliced an empty window and answered 200 with no entries, and\n * `?count=abc` made `slice(-NaN)` return the *entire* buffer. Three ways to\n * be wrong, none of them visible to the caller. The data plane refuses the\n * same input with a 400 — see `resolveListLimitParam`.\n *\n * `min` is 1 for a size and 0 for an offset: `?offset=0` is the first page,\n * which is where every pager starts, and it was a 400.\n */\n const window = (raw: string | undefined, what: string, max: number, min = 1): number | undefined => {\n if (raw === undefined || raw.trim() === \"\") return undefined;\n const parsed = Number(raw.trim());\n if (!Number.isInteger(parsed) || parsed < min || parsed > max) {\n throw new ApiError(\n 400,\n \"INVALID_PARAM\",\n `Invalid \\`${what}\\`: ${raw}. Expected a whole number between ${min} and ${max}.`,\n undefined,\n true\n );\n }\n return parsed;\n };\n\n // GET /api/logs — Query logs\n app.get(\"/\", (c) => {\n const query = c.req.query();\n const result = logBuffer.query({\n level: query.level,\n source: query.source,\n search: query.search,\n limit: window(query.limit, \"limit\", LOG_WINDOW_MAX),\n offset: window(query.offset, \"offset\", Number.MAX_SAFE_INTEGER, 0),\n since: query.since\n });\n return c.json(result);\n });\n\n // GET /api/logs/latest — Get latest logs (for real-time)\n app.get(\"/latest\", (c) => {\n const count = window(c.req.query(\"count\"), \"count\", LOG_WINDOW_MAX) ?? 50;\n return c.json({ entries: logBuffer.getLatest(count) });\n });\n\n // GET /api/logs/stream — tail the buffer over SSE.\n //\n // The Logs Explorer used to poll this router every 3 seconds, which cost a\n // request per client per 3s to say \"nothing happened\" and still showed each\n // line up to 3s late. Here the buffer pushes instead, so an idle server is an\n // idle socket.\n //\n // Events:\n // snapshot {entries, total, instance}\n // the filtered window, oldest-first, at open,\n // and the process whose ring it is\n // append {entries, dropped} entries since the last frame, oldest-first\n // `: ping` comment, keepalive only\n //\n // Snapshot and appends come down the same connection deliberately. A client\n // that fetched its backlog separately would race the subscription — entries\n // logged between the two calls belong to neither — and closing that race from\n // the outside needs an id cursor and dedupe on every frame.\n app.get(\"/stream\", (c) => {\n const query = c.req.query();\n const filter = normalizeFilter({\n level: query.level,\n source: query.source,\n search: query.search\n });\n const limit = window(query.limit, \"limit\", LOG_WINDOW_MAX) ?? 200;\n\n // Reverse proxies buffer text responses by default, which turns a live\n // tail into nothing at all until the buffer fills. nginx (and the ingress\n // in front of the managed runtime) reads this header; everything else\n // ignores it. The rest of the SSE headers are set by `streamSSE`.\n c.header(\"X-Accel-Buffering\", \"no\");\n\n return streamSSE(c, async (stream) => {\n let pending: LogEntry[] = [];\n let dropped = 0;\n\n // Subscribe *before* reading the backlog, with nothing awaited\n // between the two. Both are synchronous, so the two halves meet\n // exactly: an entry logged after the query but before the\n // subscription would otherwise be in neither, and that gap is the one\n // thing this route exists to close.\n const unsubscribe = logBuffer.subscribe(entry => {\n if (!matchesFilter(entry, filter)) return;\n if (pending.length >= maxPending) {\n pending.shift();\n dropped++;\n }\n pending.push(entry);\n });\n const snapshot = logBuffer.query({ ...filter,\n limit });\n\n // A client that goes away has to end this handler, or the\n // subscription outlives the socket. `streamSSE` only wires the\n // request signal through on old Bun, so do it here and let\n // `stream.aborted` be the one condition the loop tests.\n //\n // The `aborted` check is not belt-and-braces. A listener added to an\n // already-aborted signal is never called, so a client that leaves\n // during the snapshot write — a fast navigation, or a reconnect storm\n // against a restarting server — would leave this handler with no way\n // to learn it had gone: a subscriber and a flush loop, per attempt,\n // for the life of the process.\n const abortOnDisconnect = () => {\n if (!stream.closed) stream.abort();\n };\n c.req.raw.signal.addEventListener(\"abort\", abortOnDisconnect, { once: true });\n if (c.req.raw.signal.aborted) abortOnDisconnect();\n // The server going away ends it the same way, for the same reason\n // the client going away does — and a stream opened after shutdown\n // began still sends its snapshot, then ends.\n const closeSignal = options.closeSignal;\n closeSignal?.addEventListener(\"abort\", abortOnDisconnect, { once: true });\n if (closeSignal?.aborted) abortOnDisconnect();\n\n try {\n await stream.writeSSE({\n event: \"snapshot\",\n // The view tails like a terminal; both frames are oldest-first\n // so the client only ever appends.\n data: JSON.stringify({\n entries: snapshot.entries.slice().reverse(),\n total: snapshot.total,\n instance: logInstanceName()\n })\n });\n\n let idleMs = 0;\n while (!stream.aborted && !stream.closed) {\n await stream.sleep(flushMs);\n if (stream.aborted || stream.closed) break;\n\n if (pending.length === 0) {\n idleMs += flushMs;\n if (idleMs >= heartbeatMs) {\n await stream.write(\": ping\\n\\n\");\n idleMs = 0;\n }\n continue;\n }\n\n const entries = pending;\n const lost = dropped;\n pending = [];\n dropped = 0;\n idleMs = 0;\n await stream.writeSSE({\n event: \"append\",\n data: JSON.stringify(lost > 0 ? { entries,\n dropped: lost } : { entries })\n });\n }\n } finally {\n unsubscribe();\n c.req.raw.signal.removeEventListener(\"abort\", abortOnDisconnect);\n closeSignal?.removeEventListener(\"abort\", abortOnDisconnect);\n }\n });\n });\n\n return app;\n}\n\nexport default createLogsRoutes();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAiCA,SAAS,gBAAgB,SAA6C;CAClE,OAAO;EAAE,GAAG;EACR,QAAQ,QAAQ,QAAQ,YAAY;CAAE;AAC9C;;;;;;;;AASA,SAAS,cAAc,OAAiB,QAAmC;CACvE,IAAI,OAAO,SAAS,MAAM,UAAU,OAAO,OAAO,OAAO;CACzD,IAAI,OAAO,UAAU,MAAM,WAAW,OAAO,QAAQ,OAAO;CAC5D,IAAI,OAAO,UAAU,CAAC,MAAM,QAAQ,YAAY,CAAC,CAAC,SAAS,OAAO,MAAM,GAAG,OAAO;CAClF,IAAI,OAAO,SAAS,MAAM,YAAY,OAAO,OAAO,OAAO;CAC3D,OAAO;AACX;AAKA,IAAM,gBAAN,MAAoB;CAChB,SAA6B,CAAC;CAC9B;CACA,YAAoB;CACpB,4BAAoB,IAAI,IAAiB;CAEzC,YAAY,UAAU,KAAO;EACzB,KAAK,UAAU;CACnB;CAEA,KAAK,OAAmC;EACpC,MAAM,KAAK,OAAO,EAAE,KAAK;EACzB,MAAM,SAAmB;GAAE,GAAG;GAC1B;EAAG;EACP,KAAK,OAAO,KAAK,MAAM;EACvB,IAAI,KAAK,OAAO,SAAS,KAAK,SAC1B,KAAK,OAAO,MAAM;EAKtB,KAAK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,QAAQ;GAC5B,aAAa,iBAAiB,SAAS,mBAAmB,EAAE,MAAM,KAAK,CAAC;GACxE,IAAI,aAAa,SAAS,kBAAkB;GAE5C,IAAI;IACA,MAAM,OAAO,SAAS;KAClB,OAAO;KAGP,MAAM,KAAK,UAAU;MACjB,SAAS,SAAS,QAAQ,MAAM,CAAC,CAAC,QAAQ;MAC1C,OAAO,SAAS;MAChB,UAAU,gBAAgB;KAC9B,CAAC;IACL,CAAC;IAED,IAAI,SAAS;IACb,OAAO,CAAC,OAAO,WAAW,CAAC,OAAO,QAAQ;KACtC,MAAM,OAAO,MAAM,OAAO;KAC1B,IAAI,OAAO,WAAW,OAAO,QAAQ;KAErC,IAAI,QAAQ,WAAW,GAAG;MACtB,UAAU;MACV,IAAI,UAAU,aAAa;OACvB,MAAM,OAAO,MAAM,YAAY;OAC/B,SAAS;MACb;MACA;KACJ;KAEA,MAAM,UAAU;KAChB,MAAM,OAAO;KACb,UAAU,CAAC;KACX,UAAU;KACV,SAAS;KACT,MAAM,OAAO,SAAS;MAClB,OAAO;MACP,MAAM,KAAK,UAAU,OAAO,IAAI;OAAE;OAC9B,SAAS;MAAK,IAAI,EAAE,QAAQ,CAAC;KACrC,CAAC;IACL;GACJ,UAAU;IACN,YAAY;IACZ,EAAE,IAAI,IAAI,OAAO,oBAAoB,SAAS,iBAAiB;IAC/D,aAAa,oBAAoB,SAAS,iBAAiB;GAC/D;EACJ,CAAC;CACL,CAAC;CAED,OAAO;AACX;AAEe,iBAAiB"}
|
|
@@ -110,7 +110,20 @@ export interface ConsentPageParams {
|
|
|
110
110
|
* in this URL do not travel to whatever the redirect target loads. `form-action
|
|
111
111
|
* 'self'`, so an injection cannot repoint the form at its own collector.
|
|
112
112
|
*/
|
|
113
|
-
|
|
113
|
+
/**
|
|
114
|
+
* The `form-action` source for where Allow and Deny end up.
|
|
115
|
+
*
|
|
116
|
+
* The page posts to this origin, which answers 302 to the client's
|
|
117
|
+
* `redirect_uri` — and Chrome holds a redirect after a form submission to the
|
|
118
|
+
* submitting page's `form-action` too. With `'self'` alone the decision was
|
|
119
|
+
* made, the code issued, and the browser refused to follow it home: no client
|
|
120
|
+
* on another origin (claude.ai, an IDE on a loopback port) could ever finish
|
|
121
|
+
* connecting. The redirect URI here is the one the client registered, already
|
|
122
|
+
* checked by `/authorize`, so naming exactly its origin widens nothing else.
|
|
123
|
+
* A custom scheme (`cursor://…`) has no origin; its scheme is the source.
|
|
124
|
+
*/
|
|
125
|
+
export declare function formActionSource(redirectUri: string): string | undefined;
|
|
126
|
+
export declare function consentPageHeaders(nonce: string, redirectUri?: string): Record<string, string>;
|
|
114
127
|
export declare function renderConsentPage(params: ConsentPageParams): string;
|
|
115
128
|
/**
|
|
116
129
|
* What to call the redirect target on the consent screen.
|
package/dist/mcp/mcp-apps.d.ts
CHANGED
|
@@ -1,21 +1,17 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
* `ui://` resource in its `_meta.ui.resourceUri`. A host that supports it
|
|
6
|
-
* reads that resource — one self-contained HTML document — renders it in a
|
|
7
|
-
* sandboxed iframe next to the conversation, and hands it the tool's input and
|
|
8
|
-
* result over `postMessage`. Everything the view does after that (page, edit a
|
|
9
|
-
* cell) is a `tools/call` the host relays back to this endpoint, with the same
|
|
10
|
-
* token, so it runs as the same person under the same RLS as the model's own
|
|
11
|
-
* calls. The view holds no credential and opens no connection of its own.
|
|
12
|
-
*
|
|
13
|
-
* A host without the extension ignores `_meta` and reads the tool's text
|
|
14
|
-
* result, which is the full answer on its own.
|
|
15
|
-
*
|
|
16
|
-
* The HTML itself is built by `@rebasepro/mcp-apps`; this file only knows its
|
|
17
|
-
* shape, so `@rebasepro/server` carries no UI code.
|
|
2
|
+
* Compile an app the model wrote for the view (show_app's `code`): the code
|
|
3
|
+
* to run, or the error to hand back. Built by `@rebasepro/mcp-apps`, and
|
|
4
|
+
* loaded with the views.
|
|
18
5
|
*/
|
|
6
|
+
export type McpAppCompiler = (source: string) => {
|
|
7
|
+
ok: true;
|
|
8
|
+
code: string;
|
|
9
|
+
} | {
|
|
10
|
+
ok: false;
|
|
11
|
+
error: string;
|
|
12
|
+
};
|
|
13
|
+
/** Where the compiler comes from, asked once, on the first show_app. */
|
|
14
|
+
export type McpAppCompilerSource = () => Promise<McpAppCompiler>;
|
|
19
15
|
/** The MIME type a view resource is served as. */
|
|
20
16
|
export declare const MCP_APP_MIME_TYPE = "text/html;profile=mcp-app";
|
|
21
17
|
/** One view: a `ui://` resource and the document behind it. */
|
|
@@ -40,10 +36,37 @@ export type McpAppsSource = () => Promise<readonly McpAppResource[]>;
|
|
|
40
36
|
* `resources/read`.
|
|
41
37
|
*
|
|
42
38
|
* No CSP domains: the view fetches nothing, so the host's default — no
|
|
43
|
-
* network at all — is the policy it should run under.
|
|
39
|
+
* network at all — is the policy it should run under. An image cell tries
|
|
40
|
+
* the image and shows a label when the host blocks it: a project's image
|
|
41
|
+
* hosts are its data, unknown when this is listed, and the spec takes only
|
|
42
|
+
* named origins. `prefersBorder` because
|
|
44
43
|
* a table reads as an object of its own in the transcript.
|
|
45
44
|
*/
|
|
46
45
|
export declare function mcpAppResourceMeta(): Record<string, unknown>;
|
|
46
|
+
/**
|
|
47
|
+
* The address a view is advertised at: its base `ui://` address with `?v=` and
|
|
48
|
+
* the first 12 hex digits of the document's SHA-256.
|
|
49
|
+
*
|
|
50
|
+
* A host may fetch a view once and cache it per URI (the MCP Apps
|
|
51
|
+
* specification allows it), and Claude does: under one fixed address a
|
|
52
|
+
* deploy's new view was never fetched, and the conversation ran the old one
|
|
53
|
+
* against the new tools. With the document's hash in it, a new build is a new
|
|
54
|
+
* address and an unchanged build keeps its cache. The specification asks only
|
|
55
|
+
* that the URI be `ui://` and served; the version rides in the query string,
|
|
56
|
+
* the part a reader strips to find the base ({@link mcpAppBaseUri}).
|
|
57
|
+
*/
|
|
58
|
+
export declare function versionedMcpAppUri(baseUri: string, html: string): Promise<string>;
|
|
59
|
+
/** The version {@link versionedMcpAppUri} puts in a document's address. */
|
|
60
|
+
export declare function mcpAppVersion(html: string): Promise<string>;
|
|
61
|
+
/** `baseUri` at `version`. */
|
|
62
|
+
export declare function withMcpAppVersion(baseUri: string, version: string): string;
|
|
63
|
+
/**
|
|
64
|
+
* A view address without its version: the base address that a hashed one, and
|
|
65
|
+
* the bare one hosts held before versions, both name. `resources/read` serves
|
|
66
|
+
* the current document for any version of a base it serves, so a host holding
|
|
67
|
+
* an older tool listing gets the current view rather than a not-found.
|
|
68
|
+
*/
|
|
69
|
+
export declare function mcpAppBaseUri(uri: string): string;
|
|
47
70
|
/**
|
|
48
71
|
* The `_meta` a tool that opens a view is listed with.
|
|
49
72
|
*
|
|
@@ -51,3 +74,14 @@ export declare function mcpAppResourceMeta(): Record<string, unknown>;
|
|
|
51
74
|
* key is the one hosts read before it, still checked by the reference host.
|
|
52
75
|
*/
|
|
53
76
|
export declare function mcpAppToolMeta(resourceUri: string): Record<string, unknown>;
|
|
77
|
+
/** The file a project's admin build writes its own view to (`rebaseMcpViewPlugin`). */
|
|
78
|
+
export declare const PROJECT_VIEW_FILE = "rebase-view.html";
|
|
79
|
+
/**
|
|
80
|
+
* The views to serve, with the project's own document in place of the
|
|
81
|
+
* generic one where the project built it: its admin app, started inside the
|
|
82
|
+
* view, so its custom views, fields and actions are what the client draws.
|
|
83
|
+
*
|
|
84
|
+
* Looked for at `REBASE_MCP_VIEW` (a path to the file), then beside each
|
|
85
|
+
* frontend `serveSPA` serves. Read once, with the views.
|
|
86
|
+
*/
|
|
87
|
+
export declare function withProjectView(apps: readonly McpAppResource[], candidates: readonly string[], readFile: (file: string) => string | undefined): readonly McpAppResource[];
|
package/dist/mcp/mcp-routes.d.ts
CHANGED
|
@@ -31,7 +31,7 @@ import { type DataRateLimitConfig } from "../auth/rate-limiter.js";
|
|
|
31
31
|
import { type McpScopeVocabulary } from "./oauth-metadata.js";
|
|
32
32
|
import { type McpCaller, type McpToolDefinition } from "./mcp-tools.js";
|
|
33
33
|
import { type McpConfirmationStore } from "./confirmation.js";
|
|
34
|
-
import { type McpAppsSource } from "./mcp-apps.js";
|
|
34
|
+
import { type McpAppCompilerSource, type McpAppsSource } from "./mcp-apps.js";
|
|
35
35
|
import type { ApiKeyIdentity, ApiKeyRefusal } from "../auth/api-keys/api-key-middleware.js";
|
|
36
36
|
import type { McpGrantIdentity } from "./oauth-routes.js";
|
|
37
37
|
/** What `initialize` tells a client about the default data tools. */
|
|
@@ -103,6 +103,11 @@ export interface McpRoutesConfig {
|
|
|
103
103
|
* offered. See `mcp-apps.ts`.
|
|
104
104
|
*/
|
|
105
105
|
apps?: McpAppsSource;
|
|
106
|
+
/**
|
|
107
|
+
* The compiler for the apps the model writes (show_app's `code`), loaded
|
|
108
|
+
* with the views. Without it, show_app refuses.
|
|
109
|
+
*/
|
|
110
|
+
appCompiler?: McpAppCompilerSource;
|
|
106
111
|
/**
|
|
107
112
|
* The tools this endpoint serves, in place of the default data tools
|
|
108
113
|
* (`MCP_TOOLS`). Each still refuses an argument it does not declare, and
|
package/dist/mcp/mcp-tools.d.ts
CHANGED
|
@@ -23,6 +23,8 @@
|
|
|
23
23
|
*/
|
|
24
24
|
import type { AuthAdapter, CallerCredential, CollectionConfig, DataDriver } from "@rebasepro/types";
|
|
25
25
|
import type { McpConfirmationPlan } from "./confirmation.js";
|
|
26
|
+
import { SHOW_APP_CODE_GUIDE } from "./show-app-guide.js";
|
|
27
|
+
export { SHOW_APP_CODE_GUIDE };
|
|
26
28
|
/** The identity a tool call runs as. Comes from the verified access token. */
|
|
27
29
|
export interface McpCaller {
|
|
28
30
|
uid: string;
|
|
@@ -47,6 +49,17 @@ export interface McpToolContext {
|
|
|
47
49
|
* do. See `api/rest/auth-collection-writes.ts`.
|
|
48
50
|
*/
|
|
49
51
|
authAdapter?: AuthAdapter;
|
|
52
|
+
/**
|
|
53
|
+
* Compile an app the model wrote for the view (show_app). Present where
|
|
54
|
+
* the views are served.
|
|
55
|
+
*/
|
|
56
|
+
compileApp?: (source: string) => Promise<{
|
|
57
|
+
ok: true;
|
|
58
|
+
code: string;
|
|
59
|
+
} | {
|
|
60
|
+
ok: false;
|
|
61
|
+
error: string;
|
|
62
|
+
}>;
|
|
50
63
|
}
|
|
51
64
|
/**
|
|
52
65
|
* What a host may assume about a tool, sent with it on `tools/list` (MCP's
|
|
@@ -93,6 +106,14 @@ export interface McpToolDefinition {
|
|
|
93
106
|
ui?: {
|
|
94
107
|
resourceUri: string;
|
|
95
108
|
};
|
|
109
|
+
/**
|
|
110
|
+
* What of the result the model reads, where that is less than the view
|
|
111
|
+
* needs: the text block carries this, `structuredContent` the whole
|
|
112
|
+
* result. For a tool that opens a view, whose collection configs are the
|
|
113
|
+
* view's business and would only cost the model tokens. Defaults to the
|
|
114
|
+
* result.
|
|
115
|
+
*/
|
|
116
|
+
modelResult?(result: unknown): unknown;
|
|
96
117
|
/**
|
|
97
118
|
* Make the tool take two calls (`confirmation.ts`): the first answers the
|
|
98
119
|
* plan this returns and a token, and changes nothing; the second, with
|
|
@@ -107,9 +128,31 @@ export interface McpToolDefinition {
|
|
|
107
128
|
/** An error whose message is safe to hand back to the model. */
|
|
108
129
|
export declare class McpToolError extends Error {
|
|
109
130
|
}
|
|
110
|
-
/**
|
|
131
|
+
/**
|
|
132
|
+
* The `ui://` resource show_collection, show_record and show_app open: the
|
|
133
|
+
* admin panel's views, built by `@rebasepro/mcp-apps`.
|
|
134
|
+
*
|
|
135
|
+
* The base address. `/mcp` lists and advertises the view at this address
|
|
136
|
+
* plus its document's version (`versionedMcpAppUri`), and reads it at any
|
|
137
|
+
* version or none.
|
|
138
|
+
*/
|
|
139
|
+
export declare const MCP_APP_URI = "ui://rebase/app.html";
|
|
140
|
+
/**
|
|
141
|
+
* The view show_collection named before {@link MCP_APP_URI}: a table of its
|
|
142
|
+
* own. Still served — the same document as the app — for a host holding a
|
|
143
|
+
* tool listing from before.
|
|
144
|
+
*/
|
|
111
145
|
export declare const COLLECTION_TABLE_URI = "ui://rebase/collection-table.html";
|
|
112
146
|
export declare const MCP_TOOLS: McpToolDefinition[];
|
|
147
|
+
/** The tools that open the {@link MCP_APP_URI} view. */
|
|
148
|
+
export declare const MCP_VIEW_TOOLS: readonly ["show_collection", "show_record", "show_app"];
|
|
149
|
+
export type McpViewToolName = (typeof MCP_VIEW_TOOLS)[number];
|
|
150
|
+
/**
|
|
151
|
+
* A show_* tool's arguments, for a server that relays it to an app's own
|
|
152
|
+
* `/mcp` — the hosted connector, which takes them plus its own `project` — so
|
|
153
|
+
* the two never disagree about what a block is.
|
|
154
|
+
*/
|
|
155
|
+
export declare function mcpViewToolInputSchema(name: McpViewToolName): Record<string, unknown>;
|
|
113
156
|
/**
|
|
114
157
|
* The tool, refusing any argument it does not declare. Every tool `/mcp`
|
|
115
158
|
* serves goes through this — the default data tools and an app's own.
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What an MCP App view needs to run the admin panel's own components on a
|
|
3
|
+
* project's collections: the collections themselves, reduced to data, for
|
|
4
|
+
* the one person the view is drawn for, and what to put on screen — a
|
|
5
|
+
* collection, a record, or an app the model wrote.
|
|
6
|
+
*
|
|
7
|
+
* The view (`@rebasepro/mcp-apps`) mounts `<Rebase>` with a data driver that
|
|
8
|
+
* calls this endpoint's tools, and renders the admin panel's collection views
|
|
9
|
+
* and record forms from these configs. So a config here is the project's own —
|
|
10
|
+
* fields, enums, validation, relations, security rules, the `admin` block's
|
|
11
|
+
* presentation — with everything a `postMessage` cannot carry taken out
|
|
12
|
+
* (callbacks, custom components, a data source the view has no driver for),
|
|
13
|
+
* and narrowed to the caller:
|
|
14
|
+
*
|
|
15
|
+
* - a field this caller never receives (`excludeFromApi`, `access.read`) is
|
|
16
|
+
* not in the form at all;
|
|
17
|
+
* - a field they may not set (`access.write`) is read-only in it;
|
|
18
|
+
* - an operation their connection was not granted (`data:write`,
|
|
19
|
+
* `data:delete`) is closed by a restrictive security rule, which is what the
|
|
20
|
+
* admin panel asks before it offers Add, Save or Delete.
|
|
21
|
+
*
|
|
22
|
+
* None of that is a permission: every save goes through the write tools,
|
|
23
|
+
* which check the field rules, the scopes and RLS again. It keeps the view
|
|
24
|
+
* from offering what would be refused.
|
|
25
|
+
*
|
|
26
|
+
* @module
|
|
27
|
+
*/
|
|
28
|
+
import type { CollectionConfig } from "@rebasepro/types";
|
|
29
|
+
import { type FieldViewer } from "@rebasepro/common";
|
|
30
|
+
/** The ways a collection block lays out its rows, as the admin panel names them. */
|
|
31
|
+
export declare const VIEW_MODES: readonly ["table", "list", "cards", "kanban"];
|
|
32
|
+
export type McpViewMode = (typeof VIEW_MODES)[number];
|
|
33
|
+
/** A collection block: rows of one collection, opened in the admin panel's collection view (show_collection). */
|
|
34
|
+
export interface McpCollectionBlock {
|
|
35
|
+
key: string;
|
|
36
|
+
type: "collection";
|
|
37
|
+
collection: string;
|
|
38
|
+
view?: McpViewMode;
|
|
39
|
+
where?: Record<string, unknown>;
|
|
40
|
+
orderBy?: unknown;
|
|
41
|
+
searchString?: string;
|
|
42
|
+
limit?: number;
|
|
43
|
+
}
|
|
44
|
+
/** A record block: one row's form, or a new row's (show_record). */
|
|
45
|
+
export interface McpRecordBlock {
|
|
46
|
+
key: string;
|
|
47
|
+
type: "record";
|
|
48
|
+
collection: string;
|
|
49
|
+
/** The row to open. Absent, the form creates a new one. */
|
|
50
|
+
id?: string;
|
|
51
|
+
/** A new row's starting values. */
|
|
52
|
+
values?: Record<string, unknown>;
|
|
53
|
+
}
|
|
54
|
+
/** An app block: code the model wrote, compiled, and the collections it reads (show_app). */
|
|
55
|
+
export interface McpAppBlock {
|
|
56
|
+
key: string;
|
|
57
|
+
type: "app";
|
|
58
|
+
/** CommonJS, with the source's line numbers; `require` is the view's. */
|
|
59
|
+
code: string;
|
|
60
|
+
collections: string[];
|
|
61
|
+
}
|
|
62
|
+
export type McpViewBlock = McpCollectionBlock | McpRecordBlock | McpAppBlock;
|
|
63
|
+
/** What a show_* tool hands its view, besides what the model reads. */
|
|
64
|
+
export interface McpViewPayload {
|
|
65
|
+
/** The payload's own version: a view refuses one it does not know rather than misdraw it. */
|
|
66
|
+
version: 1;
|
|
67
|
+
title?: string;
|
|
68
|
+
/** One block: the collection, the record or the app the tool opens. */
|
|
69
|
+
blocks: McpViewBlock[];
|
|
70
|
+
/** The configs the block needs: its collections and their relations' targets, serialized. */
|
|
71
|
+
collections: unknown[];
|
|
72
|
+
/** Who the security rules are evaluated for, as the server knows them. */
|
|
73
|
+
viewer: {
|
|
74
|
+
uid: string;
|
|
75
|
+
roles: string[];
|
|
76
|
+
};
|
|
77
|
+
/**
|
|
78
|
+
* show_app's: the first page of each collection the app names, read as
|
|
79
|
+
* the caller before the view opens, so its first render reads none of
|
|
80
|
+
* them through the host. Absent where a read failed.
|
|
81
|
+
*/
|
|
82
|
+
seeds?: McpViewSeed[];
|
|
83
|
+
}
|
|
84
|
+
/** A page read ahead for a view: the rows, the read's arguments, and the count where the server took it. */
|
|
85
|
+
export interface McpViewSeed {
|
|
86
|
+
collection: string;
|
|
87
|
+
args: Record<string, unknown>;
|
|
88
|
+
rows: unknown[];
|
|
89
|
+
total?: number;
|
|
90
|
+
}
|
|
91
|
+
/** What the caller's connection may do to one collection. */
|
|
92
|
+
export interface McpViewGrant {
|
|
93
|
+
read: boolean;
|
|
94
|
+
write: boolean;
|
|
95
|
+
delete: boolean;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* The collections a set of blocks needs, ready for the view: each named
|
|
99
|
+
* collection and, one hop out, the targets of its relations — the form's
|
|
100
|
+
* relation fields read and pick rows of those.
|
|
101
|
+
*
|
|
102
|
+
* `grant` answers what this connection was granted on a collection; a target
|
|
103
|
+
* it cannot read is left out, and the relation field pointing at it with it.
|
|
104
|
+
*/
|
|
105
|
+
export declare function viewCollections(named: readonly CollectionConfig[], all: readonly CollectionConfig[], viewer: FieldViewer, grant: (collection: CollectionConfig) => McpViewGrant): unknown[];
|
|
106
|
+
/** The tool arguments a block's collection is named by: the collection's data path. */
|
|
107
|
+
export declare function viewCollectionName(collection: CollectionConfig): string;
|
|
@@ -27,7 +27,13 @@ export interface McpScopeVocabulary {
|
|
|
27
27
|
scope: string;
|
|
28
28
|
description: string;
|
|
29
29
|
}[];
|
|
30
|
-
/**
|
|
30
|
+
/**
|
|
31
|
+
* What a client that asks for nothing gets, and what the `401` challenge
|
|
32
|
+
* names in its `scope`, which is what Claude requests. Space-separated
|
|
33
|
+
* scopes from `supported`. The consent screen grants what was asked and
|
|
34
|
+
* cannot widen it, so a scope left out here is one a Claude user can
|
|
35
|
+
* never grant.
|
|
36
|
+
*/
|
|
31
37
|
defaultScope: string;
|
|
32
38
|
}
|
|
33
39
|
/** The data-plane vocabulary: `/mcp`'s own, and every backend's unless it brings its own tools. */
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const SHOW_APP_CODE_GUIDE: string;
|