Skip to content

Commit 7931f81

Browse files
feat(cli): os validate --target fetches the restriction profile from an environment URL (#31766)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9Y2yLH3VS5En8ea6L8PLhow)_ Fixes #31240 Clause-②: no Metadata-protocol: none Route: the seat ruled (step 0, option B) that this cloud route needs no spec route ledger entry: the ledger records the routes this repository's runtime serves, and the CLI only reads this one as a client. `domain:server#3` · dev session `session_01ADHkmSfgXVignEEbsJjzMa` ## 维护者速读 - 改了什么:`os validate --target` 除了本地 profile 文件,现在也接受环境的 http(s) URL:从该 URL 的 origin 取 `GET /api/v1/discovery/restriction-profile`,按 `{ success, data }` 读出,`data` 用 `RestrictionProfileSchema` 解析,判定和文件形式完全一致。 - 为什么改:卡 #31240,cloud PR #3732 已合入并发布该路由,作者不必再先把 profile 存成文件。 - 风险与回滚:无法访问、超时、非 2xx(含 404 RESOURCE_NOT_FOUND)、非 JSON、信封不对、schema 不合法,一律拒绝并点名 URL,绝不当成「没有限制」。文件形式不变。回滚即还原本 PR。 - 先看:`packages/cli/src/utils/restriction-profile.ts` 的 `fetchRestrictionProfile` 与 `RESTRICTION_PROFILE_ROUTE`;`packages/cli/src/commands/validate.ts` 第 0 步改成 `await`。 - 两分钟验证:`pnpm --filter @objectstack/cli exec vitest run src/utils/restriction-profile.test.ts test/validate-target-restriction-profile.test.ts`,预期 58 条全绿。 - 需要你做的:无,席位落地。 ## What changes **Step 0 (read-only, `origin/main` 0105a68).** | Check | Reading | |:--|:--| | `discovery/restriction-profile` in the spec route surface (`packages/spec/src/api`) and the runtime route ledger (`packages/runtime/src/route-ledger.ts`) | 0 hits (`git grep -c restriction-profile`, exit 1). Control: the same trees name `/api/v1/discovery` (`dispatcher.zod.ts:103`, `plugin-rest-api.zod.ts:817`, `route-ledger.ts:248`). Seat ruling B above: no spec entry is owed. | | `loadRestrictionProfile` on `main` | any `scheme://` target refused (`isUrl`) with "no defined address yet, save it as a JSON file"; then file missing / not JSON / schema-invalid each refused. Synchronous. | | `validate.ts` step 0 on `main` | calls the loader first, before the stack is loaded; prints `Target profile` with the file path. | **The route.** `RESTRICTION_PROFILE_ROUTE = '/api/v1/discovery/restriction-profile'`, named once in `restriction-profile.ts`. Its source is cloud PR objectstack-ai/cloud#3732 (cloud#3713), with the shape recorded on this card in comment 6716619631: `GET`, no auth, a `{ success, data }` body, `404 RESOURCE_NOT_FOUND` when the host names no environment, `503` otherwise. The code comment beside the constant cites both. **The URL form.** `loadRestrictionProfile(target, cwd)` is now `async` and returns `{ profile, source }` (`source` = the file read or the URL fetched; it was `file`). For a `scheme://` target: - only `http:` / `https:` are fetched; any other scheme is refused before a request, naming the file form as the remedy; - the profile is fetched from `RESTRICTION_PROFILE_ROUTE` at the target's **origin** (a path, query or hash on the target is not used), with `accept: application/json` and a 15 s timeout; - the body must be JSON and the `{ success: true, data }` envelope, checked locally (no new spec schema is exported); `data` is parsed with `RestrictionProfileSchema`, the same parse as the file form; schema issues are named under `data.`; - every failure is refused, naming the URL fetched: unreachable or timed out, any non-2xx (the envelope's `error.code` is named when present; a 404 adds "no environment is served at this host"), non-JSON, wrong envelope, schema-invalid. None is read as "no restriction". The file branch is unchanged except for the shared issue formatter (`profileIssues`), which prints the same text it printed before. `validate.ts` awaits the loader, prints `source`, and the `--target` flag help names the URL form. ## Tests `src/utils/restriction-profile.test.ts`, new `describe('loadRestrictionProfile — an environment URL')` against a local `node:http` stub on `127.0.0.1:0` (never a real environment), 8 cases: - parity: the stub serves a Team-shaped profile; the fetched profile equals the same content read from a file, the stub saw exactly one `GET /api/v1/discovery/restriction-profile` (target given with a path and query, so the origin rule is pinned), `source` is the route URL, and `judgeRestrictionProfile` returns the same rows for both; - refused, each naming the URL: 404 `RESOURCE_NOT_FOUND`, 503, a 200 that is not JSON, JSON outside the envelope (bare profile; `success: false`), schema-invalid `data` (`data.allowCode`; and `{}`), a closed port (`ECONNREFUSED`); - a `file://` target is refused naming the file form, and the stub saw no request. `test/validate-target-restriction-profile.test.ts`, new `describe('os validate --target ENV_URL')`, 6 cases through `Command.run`: the same exit, `valid` and `errors` rows for an open and an `allowCode: false` profile from a URL as from a file; the text face prints the fetched URL; a 404, a non-JSON and a schema-invalid answer, and an unreachable environment, each exit 1 with `valid: false` and an `error` naming the URL. Forced test changes: - `src/utils/restriction-profile.test.ts`, the four existing file-form cases: `await` / `.rejects.toThrow` because the loader is now async. Their inputs and expected text are unchanged (CONTROL). - `src/utils/restriction-profile.test.ts`, `refuses a URL rather than fetching from a guessed route`: removed, the behaviour this card replaces. Its successor is the `file://` case above. - `test/validate-target-restriction-profile.test.ts`, `a URL target is refused, naming the file form as the remedy`: now feeds a `file://` URL (an `https://` one is fetched now); same assertion on the remedy, plus `valid: false`. **Ablation (fail-open).** With the fix committed, `scripts/ablation-replace.mjs` replaced the URL branch with one that turns any fetch failure into an all-open profile (marker `ABLATION_31240_FAIL_OPEN`; anchor 1 → 0, blob `1049b5a2cabe` → `13828918c01d`). Both files: `Tests 12 failed | 46 passed (58)`; the 12 are exactly the refusal cases: the 7 unit ones and the 5 command-level ones (the `file://` case included). The parity cases stay green, as they should. Restored with `git checkout HEAD -- …`; `git diff HEAD` 0 bytes, marker count 0. <details><summary>Ablation excerpt</summary> ```text FAIL |unit| src/utils/restriction-profile.test.ts > loadRestrictionProfile — an environment URL > refuses a 404 RESOURCE_NOT_FOUND (the host names no environment), naming the URL AssertionError: promise resolved "{ …(2) }" instead of rejecting FAIL |unit| test/validate-target-restriction-profile.test.ts > os validate --target ENV_URL > an environment it cannot reach is refused, naming the URL : expected +0 to be 1 // Object.is equality Test Files 2 failed (2) Tests 12 failed | 46 passed (58) ``` </details> ## Acceptance notes - The URL form uses the target's origin only. An environment served under a path prefix is not a shape the cloud route describes (`ENV_ORIGIN/api/v1/...`), so none is guessed. - No auth header is sent: the route is unauthenticated per comment 6716619631. ## Verification All on head `221901c7` (the last commit), worktree of this branch. - `pnpm --filter @objectstack/cli exec vitest run src/utils/restriction-profile.test.ts test/validate-target-restriction-profile.test.ts`: `Test Files 2 passed (2) · Tests 58 passed (58)`, lock VERDICT command-exit 0. - cli unit tier `pnpm --filter @objectstack/cli exec vitest run --project unit --maxWorkers=2`: `Test Files 2 failed | 405 passed (407) · Tests 5759 passed | 29 skipped`. The two failed files (`published-subpath-console.pin`, `published-subpath-hook-body.pin`) refused at collection because `packages/cli/dist` was not built yet ("packages/cli is not built … Run: pnpm --filter @objectstack/cli build"). After the build: `Test Files 2 passed (2) · Tests 29 passed (29)`. The integration tier is declared to CI (no spawn entry or integration file touched). - `pnpm --filter @objectstack/cli typecheck`: exit 0 (test layer: `check:test-typecheck: OK`, debt unchanged). - Lint: `@objectstack/cli` has no `lint` script; `pnpm exec eslint --no-inline-config packages/cli`: exit 0. - Derived gates: `node scripts/pm/dispatch-gates.mjs --commands` named 66 families; all 66 exit 0. Five first answered exit 3 (prerequisite, nothing measured): `check-plugin-teardown-shape --self-test` (fixture commit not fetched) and `check:dual-build-cjs-loads`, `check:i18n`, `check:i18n-coverage`, `check:i18n-walk-parity` (workspace not built). Each re-ran green after the fetch and `turbo run build --filter='./packages/**' --filter='./examples/**'`. `--ran` reconciliation: `66 derived, 66 run, 0 NOT-MEASURED, 0 UNRUN`. - Dogfood: not run (no `!` in the title, no `(narrowing)` arm). - CI families: see this PR's check-runs. --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmSfgXVignEEbsJjzMa)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent e253f3a commit 7931f81

5 files changed

Lines changed: 327 additions & 40 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/cli': patch
3+
---
4+
5+
feat(cli): `os validate --target <environment URL>` fetches the target environment's restriction profile
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
`os validate --target` now also takes an environment's `http://` or `https://` URL. The command fetches `GET /api/v1/discovery/restriction-profile` at that URL's origin (the route a hosted environment publishes its profile at), reads the `{ success, data }` body and parses `data` with `RestrictionProfileSchema`, the same parse the file form uses, so a fetched profile judges the stack exactly as the same profile saved to a file.
11+
12+
Every failure is refused and names the URL fetched: an environment that cannot be reached or does not answer within 15 seconds, any non-2xx answer (a `404 RESOURCE_NOT_FOUND` means no environment is served at that host), a body that is not JSON or not the `{ success: true, data }` envelope, and a profile the schema rejects. None of them is ever judged as "no restriction". A URL with any other scheme is refused before anything is fetched. The file form is unchanged.

‎packages/cli/src/commands/validate.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,8 @@ export default class Validate extends Command {
118118
json: Flags.boolean({ description: 'Output results as JSON' }),
119119
target: Flags.string({
120120
description:
121-
'Also judge the stack against a target environment\'s restriction profile (a JSON file): refuse what '
121+
'Also judge the stack against a target environment\'s restriction profile (a JSON file, or the '
122+
+ 'environment\'s http(s) URL, fetched from its published route): refuse what '
122123
+ 'it forbids, warn when the local @objectstack/spec / @objectstack/skills version differs from the target\'s',
123124
}),
124125
};
@@ -292,16 +293,17 @@ export default class Validate extends Command {
292293

293294
try {
294295
// 0. `--target`: read the target environment's restriction profile FIRST,
295-
// before the stack — an unreadable or invalid profile is refused
296+
// before the stack — a file, or an environment URL the profile is
297+
// fetched from. An unreadable, unreachable or invalid profile is refused
296298
// (thrown into the catch-all: `--json` gets `error`, exit 1) whatever
297299
// the stack holds, so no run ever judges against half a profile. No
298300
// `--target`, no profile: nothing below that reads it runs, and the
299301
// command is exactly what it was.
300302
let targetProfile: ParsedRestrictionProfile | undefined;
301303
if (flags.target !== undefined) {
302-
const loadedProfile = loadRestrictionProfile(flags.target);
304+
const loadedProfile = await loadRestrictionProfile(flags.target);
303305
targetProfile = loadedProfile.profile;
304-
if (!flags.json) printKV('Target profile', loadedProfile.file);
306+
if (!flags.json) printKV('Target profile', loadedProfile.source);
305307
}
306308

307309
// 1. Load configuration

‎packages/cli/src/utils/restriction-profile.test.ts‎

Lines changed: 106 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
*/
1010

1111
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
12+
import { createServer, type Server } from 'node:http';
13+
import type { AddressInfo } from 'node:net';
1214
import { tmpdir } from 'node:os';
1315
import { join } from 'node:path';
1416
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
@@ -25,6 +27,7 @@ import { RestrictionProfileNodeType } from '@objectstack/spec/system';
2527
import {
2628
judgeRestrictionProfile,
2729
loadRestrictionProfile,
30+
RESTRICTION_PROFILE_ROUTE,
2831
restrictionProfileVersionDrift,
2932
type ParsedRestrictionProfile,
3033
} from './restriction-profile.js';
@@ -344,29 +347,121 @@ describe('loadRestrictionProfile', () => {
344347
if (dir) rmSync(dir, { recursive: true, force: true });
345348
});
346349

347-
it('parses a valid profile file with the spec schema', () => {
350+
it('parses a valid profile file with the spec schema', async () => {
348351
writeFileSync(join(dir, 'ok.json'), JSON.stringify(OPEN));
349-
expect(loadRestrictionProfile('ok.json', dir).profile).toEqual(OPEN);
352+
expect((await loadRestrictionProfile('ok.json', dir)).profile).toEqual(OPEN);
350353
});
351354

352-
it('refuses an invalid profile, naming the schema issue', () => {
355+
it('refuses an invalid profile, naming the schema issue', async () => {
353356
writeFileSync(join(dir, 'bad.json'), JSON.stringify({ ...OPEN, allowedFlowNodeTypes: ['acme_sign'] }));
354-
expect(() => loadRestrictionProfile('bad.json', dir)).toThrow(/not a valid restriction profile.*allowedFlowNodeTypes\.0/);
357+
await expect(loadRestrictionProfile('bad.json', dir)).rejects.toThrow(/not a valid restriction profile.*allowedFlowNodeTypes\.0/);
355358
});
356359

357-
it('refuses {} — an absent dimension is not "no restriction"', () => {
360+
it('refuses {} — an absent dimension is not "no restriction"', async () => {
358361
writeFileSync(join(dir, 'empty.json'), '{}');
359-
expect(() => loadRestrictionProfile('empty.json', dir)).toThrow(/allowCode/);
362+
await expect(loadRestrictionProfile('empty.json', dir)).rejects.toThrow(/allowCode/);
360363
});
361364

362-
it('refuses a file that is not JSON, and a missing file', () => {
365+
it('refuses a file that is not JSON, and a missing file', async () => {
363366
writeFileSync(join(dir, 'garbled.json'), 'allowCode: false');
364-
expect(() => loadRestrictionProfile('garbled.json', dir)).toThrow(/is not JSON/);
365-
expect(() => loadRestrictionProfile('missing.json', dir)).toThrow(/no restriction profile file/);
367+
await expect(loadRestrictionProfile('garbled.json', dir)).rejects.toThrow(/is not JSON/);
368+
await expect(loadRestrictionProfile('missing.json', dir)).rejects.toThrow(/no restriction profile file/);
369+
});
370+
});
371+
372+
/**
373+
* The URL form, against a local stub environment (never a real one). The stub
374+
* answers whatever the current case sets and records every request it gets.
375+
*/
376+
describe('loadRestrictionProfile — an environment URL', () => {
377+
let dir = '';
378+
let server: Server;
379+
let origin = '';
380+
let answer: { status: number; type: string; body: string } = { status: 200, type: 'application/json', body: '' };
381+
const requests: Array<{ method?: string; url?: string }> = [];
382+
const serve = (status: number, body: unknown, type = 'application/json') => {
383+
answer = { status, type, body: typeof body === 'string' ? body : JSON.stringify(body) };
384+
};
385+
386+
beforeAll(async () => {
387+
dir = mkdtempSync(join(tmpdir(), 'os-restriction-profile-url-'));
388+
server = createServer((req, res) => {
389+
requests.push({ method: req.method, url: req.url });
390+
res.writeHead(answer.status, { 'content-type': answer.type });
391+
res.end(answer.body);
392+
});
393+
await new Promise<void>((done) => server.listen(0, '127.0.0.1', done));
394+
origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
395+
});
396+
afterAll(async () => {
397+
await new Promise<void>((done) => server.close(() => done()));
398+
if (dir) rmSync(dir, { recursive: true, force: true });
399+
});
400+
401+
const route = () => `${origin}${RESTRICTION_PROFILE_ROUTE}`;
402+
403+
it('fetches GET RESTRICTION_PROFILE_ROUTE at the URL\'s origin and parses it exactly as a file of the same content', async () => {
404+
const team = profile({ allowCode: false, allowScheduledAutomation: false, allowedFlowNodeTypes: ['approval', 'update_record'] });
405+
writeFileSync(join(dir, 'team.json'), JSON.stringify(team));
406+
serve(200, { success: true, data: team });
407+
requests.length = 0;
408+
const fetched = await loadRestrictionProfile(`${origin}/some/console/path?tab=1`, dir);
409+
expect(requests).toEqual([{ method: 'GET', url: '/api/v1/discovery/restriction-profile' }]);
410+
expect(fetched.source).toBe(route());
411+
expect(fetched.profile).toEqual((await loadRestrictionProfile('team.json', dir)).profile);
412+
// ...and judges the same stack identically.
413+
expect(judgeRestrictionProfile(STACK, fetched.profile)).toEqual(judgeRestrictionProfile(STACK, team));
414+
});
415+
416+
it('refuses a 404 RESOURCE_NOT_FOUND (the host names no environment), naming the URL', async () => {
417+
serve(404, { success: false, error: { code: 'RESOURCE_NOT_FOUND', message: 'No environment' } });
418+
await expect(loadRestrictionProfile(origin, dir)).rejects.toThrow(
419+
`${route()} answered HTTP 404 RESOURCE_NOT_FOUND — no environment is served at this host.`,
420+
);
421+
});
422+
423+
it('refuses a 503, naming the URL', async () => {
424+
serve(503, 'upstream unavailable', 'text/plain');
425+
await expect(loadRestrictionProfile(origin, dir)).rejects.toThrow(`${route()} answered HTTP 503.`);
426+
});
427+
428+
it('refuses a 200 that is not JSON, naming the URL', async () => {
429+
serve(200, '<html>console</html>', 'text/html');
430+
await expect(loadRestrictionProfile(origin, dir)).rejects.toThrow(`${route()} did not answer JSON (content-type text/html).`);
431+
});
432+
433+
it('refuses JSON outside the { success: true, data } envelope, naming the URL', async () => {
434+
serve(200, OPEN);
435+
await expect(loadRestrictionProfile(origin, dir)).rejects.toThrow(`${route()} did not answer the { success: true, data } envelope`);
436+
serve(200, { success: false, data: OPEN });
437+
await expect(loadRestrictionProfile(origin, dir)).rejects.toThrow(`${route()} did not answer the { success: true, data } envelope`);
438+
});
439+
440+
it('refuses a schema-invalid profile, naming the URL and the issue under data', async () => {
441+
serve(200, { success: true, data: { ...OPEN, allowCode: 'no' } });
442+
await expect(loadRestrictionProfile(origin, dir)).rejects.toThrow(
443+
new RegExp(`${route().replace(/[.?]/g, '\\$&')} answered an invalid restriction profile .* data\\.allowCode:`),
444+
);
445+
serve(200, { success: true, data: {} });
446+
await expect(loadRestrictionProfile(origin, dir)).rejects.toThrow(/data\.allowCode:/);
447+
});
448+
449+
it('refuses an environment it cannot reach, naming the URL', async () => {
450+
const closed = createServer();
451+
await new Promise<void>((done) => closed.listen(0, '127.0.0.1', done));
452+
const port = (closed.address() as AddressInfo).port;
453+
await new Promise<void>((done) => closed.close(() => done()));
454+
await expect(loadRestrictionProfile(`http://127.0.0.1:${port}`, dir)).rejects.toThrow(
455+
`http://127.0.0.1:${port}${RESTRICTION_PROFILE_ROUTE} could not be reached (ECONNREFUSED).`,
456+
);
366457
});
367458

368-
it('refuses a URL rather than fetching from a guessed route', () => {
369-
expect(() => loadRestrictionProfile('https://env.example.com', dir)).toThrow(/does not publish its restriction profile at a defined/);
459+
it('refuses a scheme other than http(s) without fetching, naming the file form', async () => {
460+
requests.length = 0;
461+
await expect(loadRestrictionProfile('file:///etc/profile.json', dir)).rejects.toThrow(
462+
/only an http:\/\/ or https:\/\/ environment URL can be fetched.*os validate --target \.\/restriction-profile\.json/,
463+
);
464+
expect(requests).toEqual([]);
370465
});
371466
});
372467

‎packages/cli/src/utils/restriction-profile.ts‎

Lines changed: 124 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,11 @@
1010
* reader that lets a local author see, before a deploy, what that profile
1111
* refuses. Three parts, each one function:
1212
*
13-
* - {@link loadRestrictionProfile} reads the profile from a file and parses it
14-
* with the spec's own schema. An invalid profile is REFUSED, naming the
13+
* - {@link loadRestrictionProfile} reads the profile from a file, or fetches
14+
* it from an environment URL ({@link RESTRICTION_PROFILE_ROUTE}), and parses
15+
* it with the spec's own schema. An unreachable or non-2xx environment, or
16+
* an answer that is not JSON, is REFUSED naming the URL — never read as "no
17+
* restriction". An invalid profile is REFUSED, naming the
1518
* schema issue: a reader that judged against half a profile would be the
1619
* lenient consumer Prime Directive 12 forbids.
1720
* - {@link judgeRestrictionProfile} refuses every item of the stack the
@@ -121,31 +124,64 @@ export interface RestrictionVersionDrift {
121124
}
122125

123126
/**
124-
* Whether `--target` names a URL rather than a file.
127+
* The route a target environment publishes its restriction profile at,
128+
* relative to the environment's ORIGIN. Named once, here.
125129
*
126-
* No environment publishes its restriction profile at a defined address yet,
127-
* so the URL form is refused rather than fetched from a guessed route.
130+
* The route is cloud's, not this repository's: objectstack-ai/cloud serves it
131+
* since cloud PR #3732 (cloud#3713), and the shape this reader relies on is
132+
* the one recorded on objectstack-ai/objectstack#31240, comment 6716619631 —
133+
* `GET`, no auth, a `{ success, data }` body whose `data` is a
134+
* `RestrictionProfileSchema` value, `404 RESOURCE_NOT_FOUND` when the host
135+
* names no environment and `503` otherwise. The CLI only reads it as a client,
136+
* so it is not in the spec route ledger (`packages/spec/src/api`), which
137+
* records the routes this repository's runtime serves.
138+
*/
139+
export const RESTRICTION_PROFILE_ROUTE = '/api/v1/discovery/restriction-profile';
140+
141+
/** How long `--target <url>` waits for the environment before refusing. */
142+
const RESTRICTION_PROFILE_FETCH_TIMEOUT_MS = 15_000;
143+
144+
/**
145+
* Whether `--target` names a URL rather than a file: any `scheme://`. Only
146+
* `http:` / `https:` are fetched; every other scheme is refused.
128147
*/
129148
function isUrl(target: string): boolean {
130149
return /^[a-z][a-z0-9+.-]*:\/\//i.test(target);
131150
}
132151

133152
/**
134-
* Read and parse the restriction profile `--target` names. Throws a plain
135-
* `Error` naming the file and the problem when the target is a URL, missing,
136-
* not JSON, or not a valid restriction profile.
153+
* One `path: message` per schema issue, the same text for both forms; `at`
154+
* prefixes each path with where the profile sits in the body (`data`).
155+
*/
156+
function profileIssues(error: z.ZodError, at?: string): string {
157+
return error.issues
158+
.map((issue) => {
159+
const path = at === undefined ? issue.path : [at, ...issue.path];
160+
return `${path.length > 0 ? path.join('.') : '(root)'}: ${issue.message}`;
161+
})
162+
.join('; ');
163+
}
164+
165+
/**
166+
* Read and parse the restriction profile `--target` names: a file path, or an
167+
* environment URL whose profile is fetched from {@link RESTRICTION_PROFILE_ROUTE}
168+
* at that URL's origin. Both forms parse with `RestrictionProfileSchema`, so a
169+
* profile judges the same whichever way it arrived.
170+
*
171+
* Throws a plain `Error` naming the target and the problem when the file is
172+
* missing, not JSON, or not a valid restriction profile — or, for a URL, when
173+
* the environment cannot be reached, answers anything but a 2xx, answers
174+
* something that is not JSON or not the `{ success, data }` envelope, or
175+
* answers an invalid profile. Every URL refusal names the URL fetched. ⛔ No
176+
* failure is ever read as "no restriction".
177+
*
178+
* `source` is the file read or the URL fetched.
137179
*/
138-
export function loadRestrictionProfile(
180+
export async function loadRestrictionProfile(
139181
target: string,
140182
cwd: string = process.cwd(),
141-
): { profile: ParsedRestrictionProfile; file: string } {
142-
if (isUrl(target)) {
143-
throw new Error(
144-
`--target ${target}: a target environment does not publish its restriction profile at a defined `
145-
+ 'address yet, so this command cannot fetch one. Save the environment\'s restriction profile as a '
146-
+ 'JSON file and pass its path: os validate --target ./restriction-profile.json',
147-
);
148-
}
183+
): Promise<{ profile: ParsedRestrictionProfile; source: string }> {
184+
if (isUrl(target)) return fetchRestrictionProfile(target);
149185
const file = isAbsolute(target) ? target : resolve(cwd, target);
150186
if (!existsSync(file)) {
151187
throw new Error(`--target ${target}: no restriction profile file at ${file}.`);
@@ -161,15 +197,81 @@ export function loadRestrictionProfile(
161197
}
162198
const parsed = RestrictionProfileSchema.safeParse(raw);
163199
if (!parsed.success) {
164-
const issues = parsed.error.issues
165-
.map((issue) => `${issue.path.length > 0 ? issue.path.join('.') : '(root)'}: ${issue.message}`)
166-
.join('; ');
167200
throw new Error(
168201
`--target ${target}: ${file} is not a valid restriction profile (RestrictionProfileSchema, `
169-
+ `@objectstack/spec/system) — ${issues}`,
202+
+ `@objectstack/spec/system) — ${profileIssues(parsed.error)}`,
203+
);
204+
}
205+
return { profile: parsed.data, source: file };
206+
}
207+
208+
/** The URL form of {@link loadRestrictionProfile}. */
209+
async function fetchRestrictionProfile(
210+
target: string,
211+
): Promise<{ profile: ParsedRestrictionProfile; source: string }> {
212+
let origin: URL;
213+
try {
214+
origin = new URL(target);
215+
} catch {
216+
throw new Error(`--target ${target}: not a valid URL.`);
217+
}
218+
if (origin.protocol !== 'http:' && origin.protocol !== 'https:') {
219+
throw new Error(
220+
`--target ${target}: only an http:// or https:// environment URL can be fetched. `
221+
+ 'To judge against a profile saved on disk, pass its path: os validate --target ./restriction-profile.json',
222+
);
223+
}
224+
const url = new URL(RESTRICTION_PROFILE_ROUTE, origin.origin).href;
225+
const refuse = (problem: string): Error => new Error(
226+
`--target ${target}: ${url} ${problem} A restriction profile that cannot be read is refused, `
227+
+ 'never judged as "no restriction".',
228+
);
229+
230+
let response: Response;
231+
try {
232+
response = await fetch(url, {
233+
headers: { accept: 'application/json' },
234+
signal: AbortSignal.timeout(RESTRICTION_PROFILE_FETCH_TIMEOUT_MS),
235+
});
236+
} catch (error) {
237+
const err = error as Error & { cause?: { code?: unknown; message?: unknown } };
238+
const reason = err.name === 'TimeoutError'
239+
? `no answer within ${RESTRICTION_PROFILE_FETCH_TIMEOUT_MS / 1000} s`
240+
: String(err.cause?.code ?? err.cause?.message ?? err.message);
241+
throw refuse(`could not be reached (${reason}).`);
242+
}
243+
244+
const text = await response.text();
245+
let body: unknown;
246+
let isJson = true;
247+
try {
248+
body = JSON.parse(text);
249+
} catch {
250+
isJson = false;
251+
}
252+
253+
if (!response.ok) {
254+
const error = isJson ? (body as { error?: { code?: unknown } } | null)?.error : undefined;
255+
const code = typeof error?.code === 'string' ? ` ${error.code}` : '';
256+
const meaning = response.status === 404 ? ' — no environment is served at this host' : '';
257+
throw refuse(`answered HTTP ${response.status}${code}${meaning}.`);
258+
}
259+
if (!isJson) {
260+
throw refuse(`did not answer JSON (content-type ${response.headers.get('content-type') ?? 'none'}).`);
261+
}
262+
const envelope = body as { success?: unknown; data?: unknown } | null;
263+
if (typeof envelope !== 'object' || envelope === null || Array.isArray(envelope)
264+
|| envelope.success !== true || !('data' in envelope)) {
265+
throw refuse('did not answer the { success: true, data } envelope a published restriction profile comes in.');
266+
}
267+
const parsed = RestrictionProfileSchema.safeParse(envelope.data);
268+
if (!parsed.success) {
269+
throw refuse(
270+
'answered an invalid restriction profile (RestrictionProfileSchema, @objectstack/spec/system) — '
271+
+ `${profileIssues(parsed.error, 'data')}.`,
170272
);
171273
}
172-
return { profile: parsed.data, file };
274+
return { profile: parsed.data, source: url };
173275
}
174276

175277
/**

0 commit comments

Comments
 (0)