Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions .changeset/metadata-file-read-stays-in-root.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
'@objectstack/metadata': patch
'@objectstack/metadata-fs': patch
---

fix(metadata): metadata is served from the compiled artifact and stored metadata, and a metadata file read or written by name stays inside the loader's root

Clause-②: no (narrowing)
Metadata-protocol: none

**BREAKING** for an app that keeps metadata as loose files in directories named after a metadata type: FROM `MetadataPlugin` reading those files by default TO reading them only with `filesystemLoader: true`.

**What changes for you.** An app's metadata is served from its compiled artifact (`objectstack.json`, built from the app's TypeScript source) and from stored metadata (what Studio and the save doors write). `MetadataPlugin` no longer reads metadata files placed under a directory of your project named after a metadata type (for example `view/my_view.json`) unless you opt in with the new `filesystemLoader: true` option. `os serve`, `os start`, `os dev` and `os verify` do not opt in.

**How to migrate.** If your app kept metadata as loose files in such directories, move each one into your TypeScript source (for example into `defineStack({ views: [...] })` or a `*.view.ts` file) and run `os build`. To keep reading the files for now, construct `MetadataPlugin` with `filesystemLoader: true`.

When files are read, by the opt-in or by a `NodeMetadataManager` you construct yourself, an item is read or written by name only under the directory of its type inside the root:

- A type is one directory name with no glob characters. A name may contain `/` to reach a nested file under its type directory.
- No part of a type or name may be empty, absolute, contain a backslash or NUL, begin with `.`, consist only of dots and spaces, or be `node_modules`.
- A file is read only at its real path, and only when that path is inside the root after symbolic links are followed. A file is written only in a directory that is inside the root after symbolic links are followed, and a by-name save writes only a target (and, when asked for, a backup) that does not exist yet or is inside the root after symbolic links are followed; its temporary file never reuses a name a file already holds.
- A `NodeMetadataManager` that has a type registry reads a directory as metadata only for a type it knows exactly. A manager with no type registry reads every type. Its `filesystemLoader: false` option makes it read and watch no metadata files at all, even with `watch: true`.

A read that breaks these rules is answered as not found, the same as a missing item. A by-name save that breaks them is refused before anything is written. An explicit `path` passed to `FilesystemLoader.save()` is used as given. The file-system metadata repository (`@objectstack/metadata-fs`) follows the same name rules.

<!-- adr-0087: not-required (runtime-interface-only packages/metadata/src/plugin.ts#MetadataPluginOptions) the changed default belongs to a runtime plugin option with no metadata surface, so the ledger has nothing to rewrite; the opt-in and the move into source are stated above -->
9 changes: 6 additions & 3 deletions content/docs/permissions/capabilities.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,9 @@ capability name travels through five stations:
```

1. **Declare** — `defineCapability(...)` on the stack's `capabilities` array,
or a `*.capability.ts` / `*.capability.yml` file the filesystem loader globs.
or a `*.capability.ts` file in the app's source, compiled into its artifact.
(A `*.capability.yml` file is read only by a `MetadataPlugin` built with
`filesystemLoader: true`.)
2. **Register** — at boot, `AppPlugin` puts each stack-declared capability into
the metadata registry under the `capability` kind, so the security catalog
and runtime resolvers can list it.
Expand Down Expand Up @@ -308,8 +310,9 @@ operator reads the walled refusal every environment-metadata write takes there
(ADR-0131 D3, D12 items 7–8) before any of these.

The package-declaration channel is untouched: `AppPlugin` registers stack
`capabilities[]` through the in-memory registry and the filesystem loader globs
`filePatterns`; neither goes through the runtime write door.
`capabilities[]` through the in-memory registry, and a `MetadataPlugin` built
with `filesystemLoader: true` globs `filePatterns`; neither goes through the
runtime write door.
`supportsOverlay: false` still holds — a capability is a name, a label and a
scope, with no merge semantic.

Expand Down
15 changes: 9 additions & 6 deletions content/docs/protocol/kernel/metadata-service.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,12 @@ The `MetadataManager` is the single entry point for all metadata operations. It
```typescript
import { NodeMetadataManager } from '@objectstack/metadata/node';

// NodeMetadataManager wires up the FilesystemLoader and file watcher.
// The browser-safe base `MetadataManager` (from '@objectstack/metadata')
// registers no loaders on its own — callers must provide them.
// An app's metadata comes from its compiled artifact and from stored
// metadata. A NodeMetadataManager you construct yourself reads metadata
// files under `rootDir`, and only inside it; `MetadataPlugin` reads them
// only with `filesystemLoader: true`. The browser-safe base
// `MetadataManager` (from '@objectstack/metadata') registers no loaders on
// its own — callers must provide them.
const manager = new NodeMetadataManager({
rootDir: './src',
watch: true // Enable hot reload
Expand All @@ -62,7 +65,7 @@ Loaders adapt different storage backends to a common interface.

| Loader | Type | Description |
| :--- | :--- | :--- |
| **FilesystemLoader** | `filesystem` | Reads/Writes `.json`, `.yaml`, `.ts` files from disk. Primary for development. |
| **FilesystemLoader** | `filesystem` | Reads/Writes `.json`, `.yaml`, `.ts` files under its root, only inside it. `MetadataPlugin` registers it only with `filesystemLoader: true`; metadata normally comes from the compiled artifact and stored metadata. |
| **MemoryLoader** | `memory` | Hydrates compiled artifact items into the runtime metadata registry. |
| **DatabaseLoader** | `database` | Stores metadata revisions in control-plane services that explicitly configure it. Not auto-enabled by ObjectStack. |
| **RemoteLoader** | `http` | Fetches metadata from a remote HTTP API. |
Expand Down Expand Up @@ -111,13 +114,13 @@ await manager.save('object', 'workflow_config', data, {

### Loading Strategy

When `load()` is called, the Manager iterates through registered loaders. In ObjectStack runtime boot this means "artifact/file first"; database-backed metadata is reserved for explicitly configured control-plane services.
When `load()` is called, the Manager iterates through registered loaders. In ObjectStack runtime boot metadata comes from the compiled artifact and stored metadata; the filesystem loader is consulted only when `MetadataPlugin` is built with `filesystemLoader: true`, and database-backed metadata is reserved for explicitly configured control-plane services.

```mermaid
graph LR
A[Request: load('object', 'user')] --> B{Metadata Manager}
B --> C[Check Artifact / Memory Loader]
C -- Not Found --> D[Check Filesystem Loader]
C -- Not Found --> D[Check Filesystem Loader, when opted in]
D -- Found --> E[Return & Cache]
C -- Found --> E
```
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,11 @@
* collections and keeps the default `'app-plugin'` registrar. ⛔ The wrap's
* `'artifact-door'` declaration is never keyed on this door.
* • `bootstrap: 'lazy'`: the default `eager` mode runs a filesystem priming
* pass when no artifact is named, which would register a second copy of
* anything under `rootDir/<type>/`. The behavioural leg below shows the
* option is load-bearing: the same root primes an item under `eager` and
* none under `lazy`.
* pass when no artifact is named, which, for a plugin that opts in to
* metadata files (`filesystemLoader: true`), would register a second copy
* of anything under `rootDir/<type>/`. The behavioural leg below pins both
* facts: without the opt-in neither mode primes an item, and with it the
* same root primes an item under `eager` and none under `lazy`.
* • `rootDir` is `hostRoot`, the served app's root, never the operator's cwd.
* • It is `kernel.use`d after the HTTP server plugin, at the dev door's site.
* • Under production it mounts no dev `GET /api/v1/dev/metadata-events`; the
Expand Down Expand Up @@ -148,7 +149,7 @@ describe('#22989 A — `os serve` of a HOST config composes an artifact-less Met
expect(await mounted('development')).toContain('GET /api/v1/dev/metadata-events');
});

it('behavioural: `bootstrap: \'lazy\'` is load-bearing — the same root primes an item under eager and none under lazy', async () => {
it('behavioural: without the file opt-in neither mode primes an item; with it, `bootstrap: \'lazy\'` is load-bearing — eager primes the item and lazy none', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'os-22989-door-'));
try {
fs.mkdirSync(path.join(root, 'object'), { recursive: true });
Expand Down Expand Up @@ -179,10 +180,14 @@ describe('#22989 A — `os serve` of a HOST config composes an artifact-less Met
await plugin.destroy();
}
};
// CONTROL: the default mode primes the item this root holds.
expect(await primed({ watch: false, rootDir: root })).toEqual(['object/probe_door']);
// Without the opt-in, metadata files are not read: neither mode primes.
expect(await primed({ watch: false, rootDir: root })).toEqual([]);
// The composition's options: nothing is primed.
expect(await primed({ watch: false, config: { bootstrap: 'lazy' }, rootDir: root })).toEqual([]);
// CONTROL, opted in: the default mode primes the item this root holds...
expect(await primed({ watch: false, filesystemLoader: true, rootDir: root })).toEqual(['object/probe_door']);
// ...and `lazy` still primes none, so the option stays load-bearing.
expect(await primed({ watch: false, filesystemLoader: true, config: { bootstrap: 'lazy' }, rootDir: root })).toEqual([]);
// Attaching the repository writes nothing at boot.
expect(fs.existsSync(path.join(root, '.objectstack', 'metadata'))).toBe(false);
} finally {
Expand Down
5 changes: 4 additions & 1 deletion packages/cli/src/utils/metadata-file-name.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,10 @@ export function metadataFileInfix(type: string): string | null {
* reaches `_loadFromFileSystem` on exactly ONE branch: `bootstrap` is `eager`
* (the default) AND `options.artifactSource` is unset. An artifact source
* routes eager to `_loadFromLocalFile` instead, and `lazy` / `artifact-only`
* never glob at all. Re-measured on `origin/main` while writing this note:
* never glob at all. Even on that branch the glob finds files only when the
* plugin is built with `filesystemLoader: true`: metadata comes from the
* compiled artifact and stored metadata, and files under `rootDir` are read
* only on that opt-in. Re-measured on `origin/main` while writing this note:
*
* - Both non-test `new MetadataPlugin(...)` sites in this repo pass
* `artifactSource: { mode: 'local-file', path }` unconditionally —
Expand Down
78 changes: 76 additions & 2 deletions packages/metadata-fs/src/layout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
* <root>/.objectstack/.log/main.jsonl — append-only change log
*/

import fs from 'node:fs/promises';
import path from 'node:path';
import type { MetadataType } from '@objectstack/metadata-core';

Expand All @@ -15,8 +16,79 @@ export interface FsLayout {
root: string;
}

export function itemPath(layout: FsLayout, type: MetadataType, name: string): string {
return path.join(layout.root, type, `${name}.json`);
/**
* The canonical body's path for `(type, name)`, or `null` when the pair cannot
* name a file under `<root>/<type>/`.
*
* THE RULE: an item read or written by name stays inside the store's root,
* under its own type directory. `type` and `name` come from callers, so they
* are checked, not trusted: neither may be empty, carry a NUL or a backslash,
* or be absolute; no segment may be `node_modules`, begin with `.`, or consist
* only of dots and spaces; `type` is one segment. The syntactic check is
* backed by a resolved containment check; both are lexical, and
* {@link realPathInside} and {@link writableDirInside} are the on-disk half.
*/
export function itemPath(layout: FsLayout, type: MetadataType, name: string): string | null {
if (!isPlainPath(type) || type.includes('/') || !isPlainPath(name)) return null;
const dir = path.join(layout.root, type);
const file = path.join(dir, `${name}.json`);
const root = path.resolve(layout.root);
return isStrictlyInside(root, path.resolve(dir)) && isStrictlyInside(path.resolve(dir), path.resolve(file))
? file
: null;
}

/** A relative, `/`-separated path whose every segment is a plain, non-empty name. */
function isPlainPath(value: string): boolean {
if (typeof value !== 'string' || value === '') return false;
if (value.includes('\u0000') || value.includes('\\')) return false;
if (path.posix.isAbsolute(value) || path.win32.isAbsolute(value)) return false;
return value.split('/').every(
(segment) => segment !== ''
&& !segment.startsWith('.')
&& !/^[. ]+$/.test(segment)
&& segment !== 'node_modules',
);
}

/**
* The real path of an existing `target` when it is strictly inside the
* existing `root` with every symbolic link followed, or `null`. A caller reads
* the path this returns, not `target`.
*/
export async function realPathInside(root: string, target: string): Promise<string | null> {
try {
const [realRoot, realTarget] = await Promise.all([fs.realpath(root), fs.realpath(target)]);
return isStrictlyInside(realRoot, realTarget) ? realTarget : null;
} catch {
return null;
}
}

/**
* Whether a file may be written in `dir`: the deepest part of `dir` that
* exists is, with every symbolic link followed, the root itself or inside it.
*/
export async function writableDirInside(root: string, dir: string): Promise<boolean> {
let realRoot: string;
try {
realRoot = await fs.realpath(root);
} catch {
return false;
}
for (let probe = path.resolve(dir); ; probe = path.dirname(probe)) {
try {
const real = await fs.realpath(probe);
return real === realRoot || isStrictlyInside(realRoot, real);
} catch (error) {
if ((error as NodeJS.ErrnoException | null)?.code !== 'ENOENT' || path.dirname(probe) === probe) return false;
}
}
}

function isStrictlyInside(parent: string, child: string): boolean {
const rel = path.relative(parent, child);
return rel !== '' && rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);
}

export function typeDir(layout: FsLayout, type: MetadataType): string {
Expand Down Expand Up @@ -46,5 +118,7 @@ export function parseItemPath(
const file = segments[1]!;
if (!file.endsWith('.json')) return null;
const name = file.slice(0, -'.json'.length);
// Only a pair `itemPath` can address is an item: what is seen is what is readable.
if (itemPath(layout, type as MetadataType, name) === null) return null;
return { type, name };
}
Loading
Loading