@blinkhost/cli 2.3.0 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +246 -0
  2. package/README.md +251 -3
  3. package/dist/api.d.ts +1 -0
  4. package/dist/api.js +129 -2
  5. package/dist/assistant.d.ts +7 -0
  6. package/dist/assistant.js +460 -0
  7. package/dist/auth.d.ts +1 -0
  8. package/dist/auth.js +21 -24
  9. package/dist/cli.js +39 -13
  10. package/dist/compatibility.d.ts +1 -0
  11. package/dist/compatibility.js +43 -0
  12. package/dist/config.d.ts +2 -0
  13. package/dist/config.js +9 -1
  14. package/dist/credential-process.d.ts +19 -0
  15. package/dist/credential-process.js +75 -0
  16. package/dist/credentials.d.ts +4 -0
  17. package/dist/credentials.js +45 -46
  18. package/dist/device-flow.d.ts +24 -0
  19. package/dist/device-flow.js +76 -0
  20. package/dist/guidance.d.ts +1 -1
  21. package/dist/guidance.js +68 -5
  22. package/dist/macos-keychain-input.d.ts +6 -0
  23. package/dist/macos-keychain-input.js +22 -0
  24. package/dist/module-build.d.ts +7 -0
  25. package/dist/module-build.js +37 -0
  26. package/dist/peer-review.d.ts +8 -0
  27. package/dist/peer-review.js +55 -0
  28. package/dist/project-export.d.ts +1 -0
  29. package/dist/project-export.js +79 -0
  30. package/dist/research.d.ts +1 -0
  31. package/dist/research.js +42 -0
  32. package/dist/starter.d.ts +11 -0
  33. package/dist/starter.js +45 -0
  34. package/dist/templates.js +10 -8
  35. package/dist/terminal.d.ts +2 -0
  36. package/dist/terminal.js +12 -0
  37. package/dist/version.d.ts +1 -1
  38. package/dist/version.js +1 -1
  39. package/dist/windows-vault-command.d.ts +12 -0
  40. package/dist/windows-vault-command.js +42 -0
  41. package/dist/workflows.d.ts +17 -1
  42. package/dist/workflows.js +76 -4
  43. package/package.json +2 -2
package/dist/guidance.js CHANGED
@@ -27,6 +27,57 @@ const resource = (name, summary, extra = []) => ({
27
27
  url: DOCUMENTATION_URL,
28
28
  });
29
29
  const TOPICS = {
30
+ ai: {
31
+ name: 'ai', title: 'Idam assistant — limited preview', summary: 'Inspect tasks and explicitly review source proposals through the BlinkHost control plane.',
32
+ usage: ['blinkhost ai start --request @request.json', 'blinkhost ai list --project PROJECT_UUID',
33
+ 'blinkhost ai status|events TASK_UUID', 'blinkhost ai export TASK_UUID [--include-source]', 'blinkhost ai review TASK_UUID [--path src/file.ts]',
34
+ 'blinkhost ai approve TASK_UUID --digest REVIEW_ACTION_DIGEST --confirm TASK_UUID',
35
+ 'blinkhost ai peer-options TASK_UUID --project PROJECT_UUID',
36
+ 'blinkhost ai peer-invite TASK_UUID --project PROJECT_UUID --reviewer USER_ID --digest ACTION_DIGEST --confirm TASK_UUID',
37
+ 'blinkhost ai peer-inbox --project PROJECT_UUID',
38
+ 'blinkhost ai peer-review PEER_UUID --project PROJECT_UUID',
39
+ 'blinkhost ai peer-approve|peer-decline PEER_UUID --project PROJECT_UUID --digest REVIEW_DIGEST --confirm PEER_UUID',
40
+ 'blinkhost ai peer-withdraw TASK_UUID --project PROJECT_UUID --peer PEER_UUID --confirm TASK_UUID',
41
+ 'blinkhost ai rollback-review TASK_UUID', 'blinkhost ai rollback-approve TASK_UUID --digest UNDO_ACTION_DIGEST --confirm TASK_UUID',
42
+ 'blinkhost ai workflow-plan TASK_UUID --maximum-units TOTAL_LIMIT --confirm TASK_UUID',
43
+ 'blinkhost ai workflow-revise WORKFLOW_UUID --request @plan.json --expected-revision VERSION --digest PLAN_DIGEST --confirm WORKFLOW_UUID',
44
+ 'blinkhost ai workflow-approve WORKFLOW_UUID --expected-revision VERSION --digest PLAN_DIGEST --confirm WORKFLOW_UUID',
45
+ 'blinkhost ai workflow-status WORKFLOW_UUID', 'blinkhost ai workflow-cancel WORKFLOW_UUID --confirm WORKFLOW_UUID',
46
+ 'blinkhost ai memory-show --project PROJECT_UUID',
47
+ 'blinkhost ai compatibility --project PROJECT_UUID',
48
+ 'blinkhost ai sources --project PROJECT_UUID',
49
+ 'blinkhost ai memory-save --project PROJECT_UUID --file @guidance.txt --expected-version VERSION --confirm PROJECT_UUID',
50
+ 'blinkhost ai memory-clear --project PROJECT_UUID --expected-version VERSION --confirm PROJECT_UUID',
51
+ 'blinkhost ai cancel TASK_UUID --confirm TASK_UUID',
52
+ 'blinkhost ai resume TASK_UUID --confirm TASK_UUID',
53
+ 'blinkhost ai starters --project PROJECT_UUID',
54
+ 'blinkhost ai starter-review --project PROJECT_UUID --name api --language LANGUAGE_ID --revision SOURCE_REVISION --request-id REQUEST_UUID',
55
+ 'blinkhost ai starter-status REVIEW_UUID --project PROJECT_UUID',
56
+ 'blinkhost ai starter-approve REVIEW_UUID --project PROJECT_UUID --digest ACTION_DIGEST --confirm REVIEW_UUID',
57
+ 'blinkhost ai build-modules --project PROJECT_UUID',
58
+ 'blinkhost ai build-review --project PROJECT_UUID --module MODULE_UUID --revision SOURCE_REVISION --request-id REQUEST_UUID',
59
+ 'blinkhost ai build-status REVIEW_UUID --project PROJECT_UUID',
60
+ 'blinkhost ai build-approve REVIEW_UUID --project PROJECT_UUID --digest ACTION_DIGEST --confirm REVIEW_UUID'],
61
+ details: ['Idam is a limited preview. Availability depends on server rollout, workspace membership and billing limits. Installing the CLI does not grant access or enable a feature. Requests use the BlinkHost control plane.',
62
+ 'starters and starter-status require ai:read. starter-review requires ai:execute and prepares files from the current platform template without saving them. Retain a stable request UUID; use the current revision and language ID from starters. Inspect every returned file before starter-approve (ai:approve), using the exact review UUID and action digest. Saving adds a backend module through normal project limits; it does not overwrite source, call a model, build, commit or publish. Source, permissions, template and policy are checked again. Reviews expire after 15 minutes. Save the review UUID before approval. If the response is lost or invalid, use starter-status with that same UUID; never repeat an uncertain save automatically. A withdrawn template can hide its preview while keeping its historical save receipt. A receipt remains historical after later edits or module deletion and never recreates source. These commands require current Idam access.',
63
+ 'sources requires ai:read and lists reviewed public-document excerpts only; it does not search or fetch the web. In a research-mode request, research_source_ids can select up to four unique IDs from this catalog. Review attribution, capture date and review due date. Source text counts toward the credit estimate; expired or withdrawn sources stop queued work before model dispatch. Inspect status or export for the original excerpts and whether the model referenced each. A citation is not independent verification of a conclusion. Availability has a separate feature gate and is off by default.',
64
+ 'compatibility requires ai:read and reviews saved project declarations without uploads, model calls, credit reservations or code execution. Findings retain manifest paths and dependency sections, with revision and inspection limits. Fixed npm and Python name rules inspect package.json, single-line requirements.txt and static pyproject.toml declarations; aliases, imports, versions and transitives are not resolved. Python runtime, optional and build-system requirements keep distinct labels. Dynamic dependencies and tool-specific overrides need manual review. Python markers/extras are not evaluated; includes, URLs and pip options are not followed. Other manifest formats need manual review. No findings is not a compatibility pass. Development and build-system dependencies do not necessarily run on the backend. WASM-only backend limits still apply. Review metadata before sharing output and rerun after changes. This is not an adaptation, build, test, preview or deployment command.',
65
+ 'Sign in with explicit scopes: auth login --scope ai:read --scope ai:execute --scope ai:approve. account:read is included for session checks. Other scopes must be requested separately when using --scope. Existing sessions do not gain AI permissions automatically. Workload identities cannot use this personal Idam preview, even if their token lists AI scopes.',
66
+ 'Project guidance is optional, private to your own tasks, and sent to the model as unverified user context. memory-show requires ai:read and prints private text to normal output. Review that version before memory-save or memory-clear (ai:execute), using --expected-version and --confirm PROJECT_UUID. Saving uploads one explicitly selected regular UTF-8 text file of at most 4 KiB; symlinks, empty text and unsupported control characters are refused. Keep credentials out; screening is not exhaustive. No automatic write retries: after a timeout or conflict, run memory-show, compare the saved text/version, then decide whether to submit a new write. Guidance never grants permissions, changes hosting support or bypasses billing. Editing or clearing stops queued tasks and later workflow steps using old guidance; already dispatched work can finish. Clearing keeps a version fence and does not erase copies in task history or backups. Project transfers cannot carry guidance into another organization.',
67
+ 'A start request is a regular UTF-8 JSON file of at most 16 KiB containing project_id, client_request_id (stable UUID), prompt, and maximum_units (1–2000); mode and model are optional. Keep credentials out of prompts. Reuse the same file and client_request_id only for a retry of the same request. Choose a new UUID for a new task.',
68
+ 'The preview uses structural metadata by default. To authorize sharing saved workspace files with Azure OpenAI for this task, add source_paths: an array of up to eight unique project-relative paths. Each file must be at most 16 KiB and all selected files at most 24 KiB; the encoded context limit may reduce this. No local files are uploaded and production data is excluded. Review files first: credential screening is not exhaustive. Task status lists the selected paths. Generated source is unverified. It cannot browse, run tests or deploy.',
69
+ 'Review returns annotated diffs and an action_digest bound to the original source. Invisible controls appear as [U+…] markers; newline annotations are also display-only, not an executable patch. JSON output escapes terminal controls without changing decoded values. Approval requires the digest and explicit task confirmation. A changed project, policy, selection or expired review requires fresh review. Saving source neither creates a Git commit nor builds or publishes it.',
70
+ 'rollback-review prepares an undo of the originally saved files. Inspect every restore and delete operation, then use rollback-approve with its new action_digest and --confirm TASK_UUID. Preparing needs ai:execute; applying needs ai:approve. Later edits to affected files block undo; any workspace edit after review requires a fresh review. Reviews expire after 15 minutes. New files are removed only if unchanged and not open for live editing; folders and other files are kept. There is no force option. Original source must still be retained. Undo is source-only: it does not reverse deployments, Git commits or charges. Duplicate approval does not overwrite later edits. Check task status after a timeout; no automatic retries.',
71
+ 'Peer review lets another current owner or administrator with Idam access review selected code. Sharing is optional, but your workspace may require independent approval before Idam source saves. After preparing an ai review, use peer-options to select a named reviewer. peer-invite explicitly shares only the selected before-and-after code, not conversations, other proposed files or tool history. It can replace the current request. Read commands need ai:read; invite, withdraw and decisions need ai:approve and exact confirmation. A review lasts at most 15 minutes and is bound to the source and current permissions. The reviewer uses peer-inbox, then peer-review, then peer-approve or peer-decline with that review_digest. A decision never saves, builds or publishes; the requester must separately approve the source save. Active pending or declined reviews block saving. Withdrawal ends sharing and preserves history; it does not bypass workspace-required review. This policy covers Idam source saves only, not starter creation, builds or deployments; those retain their separate permissions and approvals. After uncertainty refresh the original review, do not retry automatically. Output is private and diffs are display-only, not executable patches. Commands require current Idam access.',
72
+ 'There is no automatic resubmission after a timeout. Use list/status to inspect state. Usage with an unknown outcome remains reserved, including after cancellation.',
73
+ 'blinkhost ai resume TASK_UUID --confirm TASK_UUID requires ai:execute and asks an eligible multi-step task to continue from its saved checkpoint. It preserves the original task, credit limit, active work, retry delays and usage records. It does not restart completed, cancelled, stopped or usage-reconciliation tasks, approve source changes, or increase spending. Current access, project revision and saved guidance must still match. No automatic retries: inspect status after a timeout. This command requires current Idam access.',
74
+ 'Build commands operate on saved WASM backend modules, not unsaved IDE edits or native server frameworks. build-modules and build-status need ai:read. build-review needs ai:execute, a current source revision and a UUID request-id you retain for reconciliation; preparation stores a review only and does not upload source or start compilation. Inspect the saved source, module, source digest, expiry and usage policy. build-approve needs ai:approve, the exact action digest and review confirmation. It requests one normal metered build, including configured overages and duration usage, with no AI credits. It never promotes an artifact, commits source or publishes. After a timeout use build-status with the same review ID; never start another review to retry an uncertain build. Approvals expire after 15 minutes and source, access, compiler availability and current policy are rechecked. A successful receipt is not a successful compilation; inspect the build state and IDE diagnostics. Commands require current Idam access.',
75
+ 'Connected reviews require a separate feature gate. For an existing plan, diagnose or review task, inspect its maximum_units using status, then workflow-plan with a total limit covering that original cap plus 160 credits (80 for investigation, 80 for review), at most 2000 total. workflow-start is a compatibility alias: it now saves a draft, never approves it. The original task continues independently. Saving, editing and approving a plan do not grant or reserve additional credits. Each later step rechecks access, source revision and available credits. No builds, tools, source changes or deployment are authorized.',
76
+ 'Inspect workflow-status for the saved steps, limits, plan_revision, plan_digest and version history. workflow-revise accepts a regular UTF-8 JSON file up to 16 KiB with exactly steps, maximum_units and maximum_context_units. Use one to three steps, each with mode (plan, diagnose or review), model (gpt-6-luna, gpt-5.6-terra or gpt-6-sol) and maximum_units (1–2000). The total must cover the original task cap plus all steps, at most 2000; the context limit is 1–393216 conservative units, not measured provider tokens. Pass the inspected revision/digest and exact workflow confirmation to revise or approve. Each changed save creates a new version (up to 100); approval binds the exact saved version. Approved and stopped plans cannot be edited or resumed. After a timeout inspect status before any manual retry; do not reuse stale approval. workflow-status needs ai:read; plan, revise and cancel need ai:execute; workflow-approve needs ai:approve. Plan approval never grants source-write authority. Follow-ups retain the original request and previous draft under their own task retention; removing one does not erase copies in another. Version history keeps metadata, not prompt/source/result bodies. Stopping prevents later steps, not charges for dispatched work.',
77
+ 'export prints a versioned, private task snapshot (blinkhost.idam.task-export/v1) to normal output. Use --json for machine-readable output. Proposed source-file copies require --include-source; input files, internal context, tool receipts and approval tokens are never included. Requests and narrative may still contain private information. Review before sharing. Removed content stays removed, and history above 1,000 events is explicitly marked partial. Downloads are not project backups or proof of deployment, and task-history removal cannot erase existing downloads. Exports over 4 MiB are refused, not silently cut short.'],
78
+ examples: ['blinkhost docs ai', 'blinkhost ai start --request @request.json --json', 'blinkhost ai status TASK_UUID --json'],
79
+ related: ['auth', 'security', 'projects', 'builds'], url: DOCUMENTATION_URL,
80
+ },
30
81
  quickstart: {
31
82
  name: 'quickstart', title: 'Safe first steps', summary: 'Inspect local readiness and receive a non-destructive path to your first BlinkHost project.',
32
83
  usage: ['blinkhost quickstart [path]', 'blinkhost quickstart [path] --json'],
@@ -65,15 +116,27 @@ const TOPICS = {
65
116
  },
66
117
  auth: {
67
118
  name: 'auth', title: 'Authentication and sessions', summary: 'Connect a device through browser approval and manage its CLI sessions.',
68
- usage: ['blinkhost auth login [--no-browser] [--api-origin URL]', 'blinkhost auth status', 'blinkhost auth sessions', 'blinkhost auth revoke SESSION_ID', 'blinkhost auth logout'],
69
- details: ['Passwords are never entered in the terminal. Refresh credentials are stored only in macOS Keychain, Windows Password Vault, or Linux Secret Service through secret-tool.', 'Headless automation should use a registered GitHub OIDC workload or a short-lived BLINKHOST_ACCESS_TOKEN supplied by an approved CI secret service. Never persist it in source or CLI configuration.', '--non-interactive prevents browser authorization and fails closed when interaction would be required.'],
119
+ usage: ['blinkhost auth login [--no-browser] [--api-origin URL] [--scope PERMISSION]', 'blinkhost auth status', 'blinkhost auth sessions', 'blinkhost auth revoke SESSION_ID', 'blinkhost auth logout'],
120
+ details: ['Passwords are never entered in the terminal. Refresh credentials are stored only in macOS Keychain, Windows Password Vault, or Linux Secret Service through secret-tool.',
121
+ 'If your session is rejected after signing out of all devices, an account security change or a BlinkHost security update, run blinkhost auth login again with the same --profile and any explicit --scope options you need. Review and approve the new browser request in the correct account. An old approval link cannot reconnect the CLI. Your project files, deployments and billing plan are unchanged by reauthentication.',
122
+ 'If a fresh sign-in is blocked, check email verification and required legal acceptance in the dashboard. Do not copy credentials from another device to bypass the check.',
123
+ 'Headless automation should use a registered GitHub OIDC workload or a short-lived BLINKHOST_ACCESS_TOKEN supplied by an approved CI secret service. Never persist it in source or CLI configuration.', '--non-interactive prevents browser authorization and fails closed when interaction would be required.'],
70
124
  examples: ['blinkhost auth login', 'blinkhost auth login --no-browser', 'blinkhost auth sessions --json'], related: ['profile', 'ci', 'security', 'portability'], url: DOCUMENTATION_URL,
71
125
  },
72
126
  profile: {
73
127
  name: 'profile', title: 'Account profiles', summary: 'Keep personal and work BlinkHost sessions separate.',
74
128
  usage: ['blinkhost profile list', 'blinkhost profile use NAME'], details: ['--profile NAME selects a profile for one command. BLINKHOST_PROFILE selects a default for the current process. Profile names contain lowercase letters, numbers, hyphens or underscores.'], examples: ['blinkhost auth login --profile work', 'blinkhost profile use work'], related: ['auth', 'security'], url: DOCUMENTATION_URL,
75
129
  },
76
- projects: resource('projects', 'Manage projects and explicit local project links.', ['`projects link PROJECT_ID [path]` writes only a local .blinkhost/project.json pointer and does not change or deploy the remote project.', '`projects unlink [path]` removes only that local pointer. `projects pull|push CONNECTION_ID` synchronizes through a configured source connection.']),
130
+ projects: {
131
+ ...resource('projects', 'Manage projects and explicit local project links.'),
132
+ usage: [...resource('projects', '').usage, 'blinkhost projects export PROJECT_UUID [--source-only] --output ./project.zip'],
133
+ details: [...resource('projects', '').details,
134
+ 'projects link/unlink manage only the local pointer. projects pull/push synchronize through a configured source connection.',
135
+ 'projects export downloads a source ZIP through the existing project export service. Requires projects:read and an owner, admin or developer role. A GitHub connection is not required.',
136
+ 'Default portable export requires a supported frontend configuration. Use --source-only for backend-only projects or to preserve source without generating or validating build configuration, READMEs, database schemas or lockfiles. Existing files and validated project assets are retained; a connected repository uses its saved base with workspace changes, not a fresh remote fetch. The server must confirm source-only mode. Both modes enforce the same authorization and screening; neither changes stored source.',
137
+ 'The CLI accepts archives up to 32 MiB, never overwrites files, follows no download redirects, and does not extract or run source. Use a new .zip path in an existing directory without symbolic links. The file is private to your account where POSIX permissions apply.',
138
+ 'This exports source and portable configuration, not database rows, runtime secret values, deployed artifacts or complete Git history. Review before sharing: secret screening is not a guarantee. Recreate bindings and resources separately and validate runtime compatibility at the destination. ai export is a separate task-history snapshot.'],
139
+ },
77
140
  repositories: resource('repositories', 'Inspect and manage connected source repositories.'),
78
141
  connections: resource('connections', 'Manage project-to-repository source connections.'),
79
142
  previews: resource('previews', 'Manage temporary preview environments.', ['`previews wait ID [--timeout 10..3600]` waits for a terminal state. `previews open ID` accepts only trusted BlinkHost HTTPS preview hosts. Preview operations can consume plan resources.']),
@@ -115,7 +178,7 @@ const TOPICS = {
115
178
  name: 'completion', title: 'Shell completion', summary: 'Generate deterministic completion for Bash, Zsh, Fish or PowerShell.', usage: ['blinkhost completion bash|zsh|fish|powershell'], details: ['The command prints a script to standard output; source or install it using your shell configuration.'], examples: ['source <(blinkhost completion bash)', 'blinkhost completion zsh > ~/.zfunc/_blinkhost'], related: ['portability'], url: DOCUMENTATION_URL,
116
179
  },
117
180
  update: {
118
- name: 'update', title: 'Check for CLI updates', summary: 'Compare this CLI version with the latest signed GitHub release.', usage: ['blinkhost update check'], details: ['The command reports an update but never installs one automatically. Pin a version with `npm install --global @blinkhost/cli@VERSION`; roll back with the same command and an earlier reviewed version.'], examples: ['blinkhost update check --json'], related: ['supply-chain'], url: DOCUMENTATION_URL,
181
+ name: 'update', title: 'CLI releases and updates', summary: 'Compare this CLI version with the verified BlinkHost release registry and read its release notes.', usage: ['blinkhost update check', 'blinkhost update notes [VERSION]'], details: ['Update checks and notices never install software automatically. Interactive notices are cached for 48 hours and stay silent in CI, JSON output and non-interactive sessions.', 'Pin a version with `npm install --global @blinkhost/cli@VERSION`; roll back with the same command and an earlier reviewed version.'], examples: ['blinkhost update check --json', 'blinkhost update notes 2.4.0'], related: ['supply-chain'], url: DOCUMENTATION_URL,
119
182
  },
120
183
  ci: {
121
184
  name: 'ci', title: 'CI readiness', summary: 'Verify the active workload identity and server-reported CLI capabilities.', usage: ['blinkhost ci check'], details: ['GitHub Actions should use an exact registered OIDC subject and id-token: write. No long-lived BlinkHost token is required.', 'Other CI systems may provide a short-lived BLINKHOST_ACCESS_TOKEN from an approved secret service; never commit or print it.'], examples: ['blinkhost ci check --non-interactive --json'], related: ['automation', 'auth', 'workloads'], url: DOCUMENTATION_URL,
@@ -160,7 +223,7 @@ const TOPICS = {
160
223
  },
161
224
  };
162
225
  const COMMANDS = [
163
- 'quickstart', 'docs', 'create', 'init', 'validate', 'manifest', 'doctor', 'test', 'auth', 'profile', 'projects',
226
+ 'quickstart', 'docs', 'create', 'init', 'validate', 'manifest', 'doctor', 'test', 'auth', 'ai', 'profile', 'projects',
164
227
  'repositories', 'connections', 'previews', 'builds', 'deployments', 'modules', 'functions', 'databases', 'bindings', 'assets',
165
228
  'secrets', 'organizations', 'templates', 'approvals', 'handoffs', 'policies', 'workloads', 'dev', 'logs', 'metrics',
166
229
  'analytics', 'support', 'completion', 'update', 'ci', 'plugins', 'api',
@@ -0,0 +1,6 @@
1
+ /** One command for security's stdin parser, not a shell or process argument. */
2
+ export declare function macosKeychainWrite(profile: string, token: string): {
3
+ command: string;
4
+ args: string[];
5
+ input: string;
6
+ };
@@ -0,0 +1,22 @@
1
+ import { CliError, EXIT } from './errors.js';
2
+ /** One command for security's stdin parser, not a shell or process argument. */
3
+ export function macosKeychainWrite(profile, token) {
4
+ if (!/^bhr_[A-Za-z0-9_-]{32,256}$/.test(token)) {
5
+ throw new CliError('The server returned an invalid refresh credential.', EXIT.auth, 'invalid_refresh_credential');
6
+ }
7
+ // Normal CLI profiles are more restrictive. This boundary also handles the
8
+ // quoted synthetic native-vault fixtures without admitting another input line.
9
+ if (!profile || profile.length > 128 || !/^[\x20-\x7e]+$/.test(profile)) {
10
+ throw new CliError('The credential profile is invalid.', EXIT.auth, 'invalid_profile');
11
+ }
12
+ const quote = (value) => `"${value.replace(/["\\]/g, '\\$&')}"`;
13
+ const input = `add-generic-password -U -s blinkhost-cli -a ${quote(profile)} -w ${quote(token)}\n`;
14
+ // Apple's security input buffer is 4096 bytes. Keep newline and NUL inside
15
+ // it. Exactly one line followed by EOF preserves this command's exit status;
16
+ // adding "quit" or a readback command could mask a failed write.
17
+ if (Buffer.byteLength(input, 'utf8') >= 4096) {
18
+ throw new CliError('The credential request is too large.', EXIT.auth, 'credential_store_configuration_invalid');
19
+ }
20
+ return { command: '/usr/bin/security', args: ['-q', '-i'], input };
21
+ }
22
+ //# sourceMappingURL=macos-keychain-input.js.map
@@ -0,0 +1,7 @@
1
+ export declare function validateModuleBuild(value: unknown, expected: {
2
+ project: string;
3
+ review?: string;
4
+ module?: string;
5
+ revision?: string;
6
+ digest?: string;
7
+ }, action: string): void;
@@ -0,0 +1,37 @@
1
+ import { CliError, EXIT } from './errors.js';
2
+ const uuid = (value) => typeof value === 'string' && /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.exec(value)?.[0] === value;
3
+ const hash = (value) => typeof value === 'string' && /^[a-f0-9]{64}$/.exec(value)?.[0] === value;
4
+ const date = (value) => typeof value === 'string' && Number.isFinite(Date.parse(value));
5
+ const states = ['requested', 'queued', 'provisioning', 'compiling', 'validating', 'signing',
6
+ 'succeeded', 'rejected', 'failed_user', 'failed_security', 'failed_platform', 'cancelled'];
7
+ export function validateModuleBuild(value, expected, action) {
8
+ const fail = () => { throw new CliError('The build response could not be verified. Inspect build-status for the existing review before any further approval; never retry automatically.', EXIT.remote, 'build_response_invalid'); };
9
+ if (!value || typeof value !== 'object' || Array.isArray(value))
10
+ return fail();
11
+ const item = value;
12
+ if (item.project_id !== expected.project || !hash(item.revision))
13
+ return fail();
14
+ if (action === 'build-modules') {
15
+ if (!Array.isArray(item.modules) || item.modules.length > 1000 || item.modules.some(module => !module
16
+ || !uuid(module.id) || typeof module.name !== 'string' || /^[a-z0-9](?:[a-z0-9-]{0,98}[a-z0-9])?$/.exec(module.name)?.[0] !== module.name
17
+ || typeof module.language !== 'string' || /^[a-z]{1,24}-wasi$/.exec(module.language)?.[0] !== module.language
18
+ || typeof module.build_available !== 'boolean')
19
+ || new Set(item.modules.map(module => module.id)).size !== item.modules.length)
20
+ return fail();
21
+ return;
22
+ }
23
+ const usage = item.usage;
24
+ if (!uuid(item.id) || !uuid(item.module_id) || !hash(item.source_digest) || !hash(item.action_digest)
25
+ || !date(item.expires_at) || (expected.review && item.id !== expected.review)
26
+ || (expected.module && item.module_id !== expected.module) || (expected.revision && item.revision !== expected.revision)
27
+ || (expected.digest && item.action_digest !== expected.digest) || !usage || usage.metric !== 'preview_builds'
28
+ || usage.quantity !== 1 || usage.ai_units !== 0 || usage.policy !== 'standard_build_allowance_and_configured_overages'
29
+ || (item.build_id !== null && !uuid(item.build_id)) || (item.artifact_id !== null && !uuid(item.artifact_id))
30
+ || (item.build_state !== null && !states.includes(String(item.build_state)))
31
+ || (item.build_id === null ? item.build_state !== null || item.artifact_id !== null : item.build_state === null)
32
+ || (item.applied_at === null ? item.verification !== 'not_applied' || item.build_id !== null
33
+ : !date(item.applied_at) || item.verification !== 'build_requested_not_published')
34
+ || (action === 'build-approve' && !item.applied_at))
35
+ return fail();
36
+ }
37
+ //# sourceMappingURL=module-build.js.map
@@ -0,0 +1,8 @@
1
+ export type PeerExpected = {
2
+ project: string;
3
+ task?: string;
4
+ peer?: string;
5
+ reviewer?: number;
6
+ digest?: string;
7
+ };
8
+ export declare function validatePeerResponse(value: unknown, expected: PeerExpected, action: string): void;
@@ -0,0 +1,55 @@
1
+ import { CliError, EXIT } from './errors.js';
2
+ const uuid = (v) => typeof v === 'string' && /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.exec(v)?.[0] === v;
3
+ const date = (v) => typeof v === 'string' && Number.isFinite(Date.parse(v));
4
+ const object = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
5
+ const keys = (v, allowed) => Object.keys(v).every(k => allowed.includes(k));
6
+ export function validatePeerResponse(value, expected, action) {
7
+ const fail = () => { throw new CliError('The peer review response could not be verified. Refresh peer-options or peer-review before another action; never retry automatically.', EXIT.remote, 'peer_response_invalid'); };
8
+ if (!object(value))
9
+ return fail();
10
+ const peer = (v, source, bind) => {
11
+ if (!object(v) || !keys(v, ['id', 'project_id', 'reviewer_id', 'review_digest', 'expires_at', 'approved_at', 'declined_at', 'revoked_at', 'verification', ...(source ? ['diffs'] : [])])
12
+ || !uuid(v.id) || v.project_id !== expected.project || !Number.isSafeInteger(v.reviewer_id) || Number(v.reviewer_id) < 1
13
+ || typeof v.review_digest !== 'string' || /^[a-f0-9]{64}$/.exec(v.review_digest)?.[0] !== v.review_digest
14
+ || !date(v.expires_at) || [v.approved_at, v.declined_at, v.revoked_at].some(d => d !== null && !date(d))
15
+ || (v.approved_at && v.declined_at) || v.verification !== 'source_review_only'
16
+ || (bind && ((expected.peer && v.id !== expected.peer) || (expected.reviewer && v.reviewer_id !== expected.reviewer)
17
+ || (expected.digest && v.review_digest !== expected.digest))))
18
+ return fail();
19
+ if (source && (!Array.isArray(v.diffs) || !v.diffs.length || v.diffs.length > 20
20
+ || v.diffs.some(d => !object(d) || !keys(d, ['path', 'diff']) || typeof d.path !== 'string' || !d.path
21
+ || typeof d.diff !== 'string') || new Set(v.diffs.map(d => d.path)).size !== v.diffs.length))
22
+ return fail();
23
+ };
24
+ if (action === 'peer-withdraw') {
25
+ if (!keys(value, ['id', 'revoked_at']) || value.id !== expected.peer || !date(value.revoked_at))
26
+ return fail();
27
+ }
28
+ else if (action === 'peer-options') {
29
+ if (!keys(value, ['project_id', 'task_id', 'truncated', 'required', 'reviewers', 'active']) || value.project_id !== expected.project
30
+ || value.task_id !== expected.task || typeof value.truncated !== 'boolean' || typeof value.required !== 'boolean'
31
+ || !Array.isArray(value.reviewers) || value.reviewers.length > 100
32
+ || value.reviewers.some(r => !object(r) || !keys(r, ['id', 'name', 'role']) || !Number.isSafeInteger(r.id)
33
+ || Number(r.id) < 1 || typeof r.name !== 'string' || !['owner', 'admin'].includes(String(r.role)))
34
+ || new Set(value.reviewers.map(r => r.id)).size !== value.reviewers.length)
35
+ return fail();
36
+ if (value.active !== null)
37
+ peer(value.active, false, false);
38
+ }
39
+ else if (action === 'peer-inbox') {
40
+ if (!keys(value, ['project_id', 'truncated', 'reviews']) || value.project_id !== expected.project
41
+ || typeof value.truncated !== 'boolean' || !Array.isArray(value.reviews) || value.reviews.length > 100)
42
+ return fail();
43
+ for (const item of value.reviews)
44
+ peer(item, false, false);
45
+ if (new Set(value.reviews.map(r => r.id)).size !== value.reviews.length)
46
+ return fail();
47
+ }
48
+ else {
49
+ peer(value, action !== 'peer-invite', true);
50
+ if ((action === 'peer-approve' && (!value.approved_at || value.revoked_at))
51
+ || (action === 'peer-decline' && (!value.declined_at || value.revoked_at)))
52
+ return fail();
53
+ }
54
+ }
55
+ //# sourceMappingURL=peer-review.js.map
@@ -0,0 +1 @@
1
+ export declare function exportProject(input: string[], profile?: string): Promise<Record<string, unknown>>;
@@ -0,0 +1,79 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { link, lstat, open, unlink } from 'node:fs/promises';
3
+ import { basename, dirname, join, parse, relative } from 'node:path';
4
+ import { ApiClient } from './api.js';
5
+ import { CliError, EXIT } from './errors.js';
6
+ import { resolveLocalPath } from './project.js';
7
+ async function checkDestination(destination) {
8
+ let cursor = parse(destination).root;
9
+ for (const segment of relative(cursor, dirname(destination)).split(/[\\/]/).filter(Boolean)) {
10
+ cursor = join(cursor, segment);
11
+ const info = await lstat(cursor);
12
+ if (!info.isDirectory() || info.isSymbolicLink())
13
+ throw new CliError('Export requires an existing directory without symbolic links.', EXIT.filesystem, 'unsafe_export_directory');
14
+ }
15
+ try {
16
+ await lstat(destination);
17
+ }
18
+ catch (error) {
19
+ if (error.code === 'ENOENT')
20
+ return;
21
+ throw error;
22
+ }
23
+ throw new CliError('The export destination already exists. Choose a new filename.', EXIT.filesystem, 'target_exists');
24
+ }
25
+ export async function exportProject(input, profile) {
26
+ const args = [...input];
27
+ const projectId = args.shift();
28
+ if (!projectId || !/^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i.test(projectId)) {
29
+ throw new CliError('Use projects export PROJECT_UUID --output ./project.zip.', EXIT.usage, 'invalid_project_id');
30
+ }
31
+ let output;
32
+ let sourceOnly = false;
33
+ while (args.length) {
34
+ const option = args.shift();
35
+ if (option === '--source-only' && !sourceOnly)
36
+ sourceOnly = true;
37
+ else if (option === '--output' && output === undefined && args[0] && !args[0].startsWith('--'))
38
+ output = args.shift();
39
+ else
40
+ throw new CliError('Use projects export PROJECT_UUID [--source-only] --output ./project.zip. Do not repeat options.', EXIT.usage, 'export_output_required');
41
+ }
42
+ if (!output) {
43
+ throw new CliError('Choose a new ZIP filename with --output. Existing files are never replaced.', EXIT.usage, 'export_output_required');
44
+ }
45
+ const destination = resolveLocalPath(output);
46
+ if (!basename(destination).toLowerCase().endsWith('.zip'))
47
+ throw new CliError('The export filename must end in .zip.', EXIT.usage, 'export_output_invalid');
48
+ await checkDestination(destination);
49
+ const client = await ApiClient.create(profile);
50
+ const mode = sourceOnly ? 'source' : 'portable';
51
+ const body = await client.projectArchive(projectId, mode);
52
+ await checkDestination(destination);
53
+ const temporary = join(dirname(destination), `.blinkhost-export-${randomUUID()}.tmp`);
54
+ const file = await open(temporary, 'wx', 0o600);
55
+ try {
56
+ await file.writeFile(body);
57
+ await file.sync();
58
+ await file.close();
59
+ // A hard link publishes only the complete archive and fails if the destination
60
+ // was created meanwhile. Never rename over an existing customer file.
61
+ await link(temporary, destination);
62
+ }
63
+ catch (error) {
64
+ if (error.code === 'EEXIST')
65
+ throw new CliError('The export destination already exists. Choose a new filename.', EXIT.filesystem, 'target_exists');
66
+ throw error;
67
+ }
68
+ finally {
69
+ await file.close().catch(() => undefined);
70
+ await unlink(temporary);
71
+ }
72
+ return { project_id: projectId, path: destination, size_bytes: body.length,
73
+ sha256: createHash('sha256').update(body).digest('hex'), format: 'zip', extracted: false,
74
+ includes_database_backup: false, includes_runtime_secrets: false,
75
+ export_mode: mode,
76
+ next_steps: [...(sourceOnly ? ['Source only: build configuration was not generated or validated.'] : []),
77
+ 'Review the archive before extracting or sharing it.', 'Configure resources and secrets separately in the destination environment.'] };
78
+ }
79
+ //# sourceMappingURL=project-export.js.map
@@ -0,0 +1 @@
1
+ export declare function validateResearchCatalog(raw: unknown, project: string): void;
@@ -0,0 +1,42 @@
1
+ import { CliError, EXIT } from './errors.js';
2
+ // This is a display/selection boundary, not a URL fetcher. The server verifies
3
+ // the content digest, review, expiry and allowlist again at admission and claim.
4
+ export function validateResearchCatalog(raw, project) {
5
+ const fail = () => { throw new CliError('The public source catalog could not be verified. No research was started.', EXIT.remote, 'research_catalog_invalid'); };
6
+ const text = (value, max, multiline = false) => typeof value === 'string'
7
+ && !!value.trim() && Buffer.byteLength(value) <= max
8
+ && !/[\p{Cc}\p{Cf}\p{Cs}]/u.test(multiline ? value.replace(/[\n\t]/g, '') : value);
9
+ const value = raw;
10
+ if (!value || value.project_id !== project.toLowerCase() || value.live_search !== false
11
+ || value.max_selection !== 4 || typeof value.truncated !== 'boolean'
12
+ || !Array.isArray(value.sources) || value.sources.length > 100)
13
+ fail();
14
+ const seen = new Set();
15
+ for (const source of value.sources) {
16
+ if (!source || typeof source !== 'object' || Array.isArray(source)
17
+ || Object.keys(source).sort().join(',') !== 'attribution,captured_at,excerpt,expires_at,id,publisher,schema,title,url'
18
+ || source.schema !== 'blinkhost.idam.public-source/v1' || typeof source.id !== 'string'
19
+ || !/^[a-f0-9]{64}$/.test(source.id) || seen.has(source.id)
20
+ || !text(source.title, 300) || !text(source.publisher, 200) || !text(source.attribution, 1000)
21
+ || !text(source.excerpt, 6000, true) || !text(source.url, 1500)
22
+ || !/^https:\/\/[a-z0-9.-]+\/[A-Za-z0-9_./~%\-]*$/.test(source.url))
23
+ fail();
24
+ let url;
25
+ try {
26
+ url = new URL(source.url);
27
+ }
28
+ catch {
29
+ return fail();
30
+ }
31
+ if (!/\.[a-z]{2,63}$/.test(url.hostname) || /\.(localhost|local|internal|test|invalid)$/.test(url.hostname)
32
+ || url.hostname.split('.').some(label => !label || label.length > 63 || label.startsWith('-') || label.endsWith('-'))
33
+ || /%(?![0-9a-f]{2})|%(0[0-9a-f]|1[0-9a-f]|7f|25|2f|5c)/i.test(url.pathname))
34
+ fail();
35
+ const captured = typeof source.captured_at === 'string' ? Date.parse(source.captured_at) : NaN;
36
+ const expires = typeof source.expires_at === 'string' ? Date.parse(source.expires_at) : NaN;
37
+ if (!Number.isFinite(captured) || !Number.isFinite(expires) || expires <= captured || expires - captured > 90 * 86400000)
38
+ fail();
39
+ seen.add(source.id);
40
+ }
41
+ }
42
+ //# sourceMappingURL=research.js.map
@@ -0,0 +1,11 @@
1
+ export declare const starterName: (value: unknown) => value is string;
2
+ export declare const starterLanguage: (value: unknown) => value is string;
3
+ export type StarterExpected = {
4
+ project: string;
5
+ review?: string;
6
+ name?: string;
7
+ language?: string;
8
+ revision?: string;
9
+ digest?: string;
10
+ };
11
+ export declare function validateStarter(value: unknown, expected: StarterExpected, action: string): void;
@@ -0,0 +1,45 @@
1
+ import { CliError, EXIT } from './errors.js';
2
+ const matches = (pattern, value) => typeof value === 'string' && pattern.exec(value)?.[0] === value;
3
+ const hash = (value) => matches(/^[a-f0-9]{64}$/, value);
4
+ const uuid = (value) => matches(/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i, value);
5
+ const date = (value) => typeof value === 'string' && Number.isFinite(Date.parse(value));
6
+ export const starterName = (value) => matches(/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/, value);
7
+ export const starterLanguage = (value) => matches(/^[a-z]{1,24}-wasi$/, value);
8
+ export function validateStarter(value, expected, action) {
9
+ const fail = () => { throw new CliError('The starter response could not be verified. Use starter-status with the existing review ID before any further approval. Do not retry a save automatically.', EXIT.remote, 'starter_response_invalid'); };
10
+ if (!value || typeof value !== 'object' || Array.isArray(value))
11
+ return fail();
12
+ const item = value;
13
+ if (item.project_id !== expected.project || !hash(item.revision))
14
+ return fail();
15
+ if (action === 'starters') {
16
+ if (item.verification !== 'starter_only' || !Array.isArray(item.languages) || item.languages.length > 20
17
+ || item.languages.some((entry) => !entry || !starterLanguage(entry.id)
18
+ || typeof entry.label !== 'string' || !entry.label || entry.label.length > 80
19
+ || /[\x00-\x1f\x7f-\x9f]/.test(entry.label) || !['ga', 'beta'].includes(entry.status))
20
+ || new Set(item.languages.map((entry) => entry.id)).size !== item.languages.length)
21
+ return fail();
22
+ return;
23
+ }
24
+ if (!uuid(item.id) || !starterName(item.name) || !starterLanguage(item.language)
25
+ || !hash(item.action_digest) || !date(item.expires_at) || typeof item.template_current !== 'boolean'
26
+ || (expected.review !== undefined && item.id !== expected.review)
27
+ || (expected.name !== undefined && item.name !== expected.name)
28
+ || (expected.language !== undefined && item.language !== expected.language)
29
+ || (expected.revision !== undefined && item.revision !== expected.revision)
30
+ || (expected.digest !== undefined && item.action_digest !== expected.digest)
31
+ || !Array.isArray(item.files) || item.files.length > 20
32
+ || (item.template_current ? item.files.length === 0 : item.files.length !== 0)
33
+ || item.files.some((file) => !file || typeof file.path !== 'string'
34
+ || !file.path.startsWith(`_server_islands/${item.name}/`) || file.path.length > 512
35
+ || file.path.split('/').some((part) => !part || part === '.' || part === '..')
36
+ || /[\\:\x00-\x1f\x7f-\x9f]/.test(file.path) || typeof file.content !== 'string'
37
+ || Buffer.byteLength(file.content, 'utf8') > 65536 || typeof file.managed !== 'boolean')
38
+ || new Set(item.files.map((file) => file.path.toLowerCase())).size !== item.files.length
39
+ || (item.module_id !== null && !uuid(item.module_id))
40
+ || (item.applied_at === null ? item.verification !== 'not_applied' || item.module_id !== null || item.applied_revision !== ''
41
+ : !date(item.applied_at) || item.verification !== 'source_saved_not_built' || !hash(item.applied_revision))
42
+ || (action === 'starter-approve' && !item.applied_at))
43
+ return fail();
44
+ }
45
+ //# sourceMappingURL=starter.js.map
package/dist/templates.js CHANGED
@@ -58,13 +58,14 @@ function moduleFiles(module) {
58
58
  const root = `_server_islands/${module.name}`;
59
59
  const files = new Map();
60
60
  if (module.language === 'python') {
61
- files.set(`${root}/main.py`, 'def handler(request):\n return {"status": 200, "body": {"ok": True}}\n');
62
- files.set(`${root}/requirements.txt`, '# Add pinned runtime dependencies here.\n');
61
+ files.set(`${root}/blinkhost.toml`, 'schema_version = 1\nlanguage = "python-wasi"\nentrypoint = "main.py"\nabi_version = "blinkhost-wasi-1"\nsdk_version = "1.1.0"\n');
62
+ files.set(`${root}/main.py`, 'import blinkhost\n\nblinkhost.respond(blinkhost.Response.json({"ok": True}))\n');
63
63
  return { entrypoint: 'main.py', files };
64
64
  }
65
65
  if (module.language === 'go') {
66
- files.set(`${root}/go.mod`, `module blinkhost/${module.name}\n\ngo 1.23\n`);
67
- files.set(`${root}/main.go`, 'package main\n\nfunc main() {}\n');
66
+ files.set(`${root}/blinkhost.toml`, 'schema_version = 1\nlanguage = "go-wasi"\nentrypoint = "main.go"\nabi_version = "blinkhost-wasi-1"\nsdk_version = "1.1.0"\n');
67
+ files.set(`${root}/go.mod`, `module blinkhost/${module.name}\n\ngo 1.24\n\nrequire blinkhost.dev/sdk/go v1.1.0\n\nreplace blinkhost.dev/sdk/go => /opt/blinkhost-sdk/go\n`);
68
+ files.set(`${root}/main.go`, 'package main\n\nimport "blinkhost.dev/sdk/go/blinkhost"\n\nfunc main() {\n\tresponse, err := blinkhost.JSONResponse(200, map[string]bool{"ok": true})\n\tif err != nil || blinkhost.Respond(response) != nil {\n\t\tpanic("BlinkHost response write failed")\n\t}\n}\n');
68
69
  return { entrypoint: 'main.go', files };
69
70
  }
70
71
  if (module.language === 'javascript' || module.language === 'typescript') {
@@ -80,9 +81,10 @@ function moduleFiles(module) {
80
81
  files.set(`${root}/${entrypoint}`, `${declaration}export default function handler(request${annotation}) {\n return {\n status: 200,\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ ok: true, received: request.json() }),\n };\n}\n`);
81
82
  return { entrypoint, files };
82
83
  }
83
- files.set(`${root}/Cargo.toml`, `[package]\nname = "${module.name}"\nversion = "0.1.0"\nedition = "2021"\n\n[lib]\ncrate-type = ["cdylib"]\n`);
84
- files.set(`${root}/src/lib.rs`, '#[no_mangle]\npub extern "C" fn blinkhost_module_version() -> u32 { 1 }\n');
85
- return { entrypoint: 'src/lib.rs', files };
84
+ files.set(`${root}/blinkhost.toml`, 'schema_version = 1\nlanguage = "rust-wasi"\nentrypoint = "src/main.rs"\nabi_version = "blinkhost-wasi-1"\nsdk_version = "1.1.0"\n');
85
+ files.set(`${root}/Cargo.toml`, `[package]\nname = "${module.name}"\nversion = "0.1.0"\nedition = "2021"\n\n[dependencies]\nblinkhost-sdk = { path = "/opt/blinkhost-sdk/rust", version = "=1.1.0" }\n\n[profile.release]\ncodegen-units = 1\nlto = true\nopt-level = "s"\npanic = "abort"\nstrip = true\n`);
86
+ files.set(`${root}/src/main.rs`, 'use blinkhost_sdk::{respond, Response};\n\nfn main() {\n if respond(Response::json(200, r#"{"ok":true}"#)).is_err() {\n std::process::abort();\n }\n}\n');
87
+ return { entrypoint: 'src/main.rs', files };
86
88
  }
87
89
  export function createScaffold(options) {
88
90
  const packageCommands = commands(options.packageManager);
@@ -92,7 +94,7 @@ export function createScaffold(options) {
92
94
  const generated = moduleFiles(item);
93
95
  for (const [path, contents] of generated.files)
94
96
  files.set(path, contents);
95
- modules.push({ name: item.name, path: `_server_islands/${item.name}`, language: item.language, entrypoint: generated.entrypoint, abi: 'blinkhost-wasi-1', sdk: '1.1' });
97
+ modules.push({ name: item.name, path: `_server_islands/${item.name}`, language: item.language, entrypoint: generated.entrypoint, abi: 'blinkhost-wasi-1', sdk: '1.1.0' });
96
98
  }
97
99
  const databases = options.database ? [{ binding: options.database, schema: `database/${options.database}/schema.sql`, migrations: `database/${options.database}/migrations` }] : [];
98
100
  if (options.database) {
@@ -0,0 +1,2 @@
1
+ export declare function terminalText(value: string): string;
2
+ export declare function terminalJson(serialized: string): string;
@@ -0,0 +1,12 @@
1
+ // Presentation only. Never feed annotated text back into source or approvals.
2
+ export function terminalText(value) {
3
+ return value.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, char => char === '\n' || char === '\t' ? char
4
+ : `[U+${char.codePointAt(0).toString(16).toUpperCase().padStart(4, '0')}]`);
5
+ }
6
+ // Escape already serialized JSON, including object keys. JSON.parse preserves
7
+ // the exact original values; supplementary controls require two UTF-16 escapes.
8
+ // JSON.stringify already escapes C0 controls within strings.
9
+ export function terminalJson(serialized) {
10
+ return serialized.replace(/[\p{Cf}\p{Zl}\p{Zp}\u007f-\u009f]/gu, char => char.split('').map(unit => `\\u${unit.charCodeAt(0).toString(16).padStart(4, '0')}`).join(''));
11
+ }
12
+ //# sourceMappingURL=terminal.js.map
package/dist/version.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const VERSION = "2.3.0";
1
+ export declare const VERSION = "2.5.0";
2
2
  export declare const DOCUMENTATION_URL = "https://app.blinkhost.me/docs/source-control/cli";
3
3
  export declare const RELEASES_URL = "https://github.com/blinkhost-ltd/blinkhost-cli/releases";
4
4
  export declare function supportedNodeVersion(version?: string): boolean;
package/dist/version.js CHANGED
@@ -1,4 +1,4 @@
1
- export const VERSION = '2.3.0';
1
+ export const VERSION = '2.5.0';
2
2
  export const DOCUMENTATION_URL = 'https://app.blinkhost.me/docs/source-control/cli';
3
3
  export const RELEASES_URL = 'https://github.com/blinkhost-ltd/blinkhost-cli/releases';
4
4
  export function supportedNodeVersion(version = process.versions.node) {
@@ -0,0 +1,12 @@
1
+ /** Read-only type loading; cold PowerShell startup may exceed five seconds. */
2
+ export declare function windowsVaultProbe(): {
3
+ command: string;
4
+ args: string[];
5
+ timeoutMs: number;
6
+ };
7
+ /** Fixed PowerShell program; credentials travel only through the input pipe. */
8
+ export declare function windowsVaultCommand(action: 'get' | 'set' | 'delete', profile: string, token?: string): {
9
+ command: string;
10
+ args: string[];
11
+ input?: string;
12
+ };
@@ -0,0 +1,42 @@
1
+ import { CliError, EXIT } from './errors.js';
2
+ /** Read-only type loading; cold PowerShell startup may exceed five seconds. */
3
+ export function windowsVaultProbe() {
4
+ return {
5
+ command: 'powershell.exe',
6
+ args: ['-NoProfile', '-NonInteractive', '-Command',
7
+ "$ErrorActionPreference='Stop';try{[void][Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]}catch{exit 3}"],
8
+ timeoutMs: 15_000,
9
+ };
10
+ }
11
+ /** Fixed PowerShell program; credentials travel only through the input pipe. */
12
+ export function windowsVaultCommand(action, profile, token) {
13
+ if (!profile || profile.length > 128 || !/^[\x20-\x7e]+$/.test(profile)) {
14
+ throw new CliError('The credential profile is invalid.', EXIT.auth, 'invalid_profile');
15
+ }
16
+ if (action === 'set' && (typeof token !== 'string' || !/^bhr_[A-Za-z0-9_-]{32,256}$/.test(token))) {
17
+ throw new CliError('The server returned an invalid refresh credential.', EXIT.auth, 'invalid_refresh_credential');
18
+ }
19
+ const user = profile.replace(/'/g, "''");
20
+ const prefix = `$ErrorActionPreference='Stop';try{$r='blinkhost-cli';$u='${user}';[void][Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime];$p=New-Object Windows.Security.Credentials.PasswordVault}catch{exit 3};`;
21
+ const missing = 'catch{if($_.Exception.GetBaseException().HResult -eq -2147023728){exit 2}else{exit 3}}';
22
+ let operation;
23
+ if (action === 'get') {
24
+ operation = `try{$c=$p.Retrieve($r,$u);$c.RetrievePassword();[Console]::Out.Write($c.Password)}${missing}`;
25
+ }
26
+ else if (action === 'delete') {
27
+ operation = `try{$c=$p.Retrieve($r,$u);$p.Remove($c)}${missing}`;
28
+ }
29
+ else if (action === 'set') {
30
+ // Do not delete the prior credential before Add. A failed write must not
31
+ // become an application-created missing-item window. No fallback/retry.
32
+ // Validate again after pipe transport; PowerShell must fail nonzero even
33
+ // for non-terminating errors. Never print exceptions or credential values.
34
+ operation = "try{$s=[Console]::In.ReadToEnd();if($s -cnotmatch '\\Abhr_[A-Za-z0-9_-]{32,256}\\z'){exit 3};$p.Add((New-Object Windows.Security.Credentials.PasswordCredential($r,$u,$s)))}catch{exit 3}";
35
+ }
36
+ else {
37
+ throw new CliError('Invalid credential-service operation.', EXIT.internal, 'credential_store_configuration_invalid');
38
+ }
39
+ return { command: 'powershell.exe', args: ['-NoProfile', '-NonInteractive', '-Command', prefix + operation],
40
+ ...(action === 'set' ? { input: token } : {}) };
41
+ }
42
+ //# sourceMappingURL=windows-vault-command.js.map