insta 0.0.71 → 0.0.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/agent.js CHANGED
@@ -66,7 +66,7 @@ export async function loadAgentSession(apiUrl, projectId, cwd = process.cwd()) {
66
66
  // scope.projectId. A miss fails HERE, naming the route, instead of on the platform as a
67
67
  // "for a different project" 403 whose setup hint cannot help — keep this list in step with the
68
68
  // account-level paths in src/commands/.
69
- export const ACCOUNT_ROUTES = new Set(['agent', 'auth', 'me', 'orgs', 'regions', 'templates', 'tokens', 'github']);
69
+ export const ACCOUNT_ROUTES = new Set(['agent', 'auth', 'me', 'orgs', 'regions', 'templates', 'tokens']);
70
70
  export async function agentHeaders(api, method, path, rawBody, scope = {}) {
71
71
  if (!mode)
72
72
  return {};
@@ -1,6 +1,6 @@
1
1
  import { ApiClient, ApiError, requireProject } from '../api.js';
2
2
  import { agentMode } from '../agent.js';
3
- import { info, printJson } from '../util.js';
3
+ import { info, printJson, openUrl } from '../util.js';
4
4
  import { resolveSoleService, parsePort, q } from './services.js';
5
5
  export function parseRepoRef(raw) {
6
6
  const s = raw.trim().replace(/^https?:\/\//i, '').replace(/^(www\.)?github\.com\//i, '').replace(/\/+$/, '').replace(/\.git$/i, '');
@@ -81,8 +81,8 @@ const sleepSeconds = (s) => new Promise((r) => setTimeout(r, s * 1000));
81
81
  const pollDelay = (s) => Math.min(Math.max(s, 1), 60);
82
82
  // GitHub shows the person a code to type; the platform holds the device code and finishes the exchange,
83
83
  // so nothing secret passes through the CLI.
84
- export async function authorizeTerminal(api, orgId, wait = sleepSeconds) {
85
- const start = await api.request('POST', `/orgs/${encodeURIComponent(orgId)}/github/device`, {});
84
+ export async function authorizeTerminal(api, wait = sleepSeconds, open = openUrl) {
85
+ const start = await api.request('POST', '/me/github/device', {});
86
86
  const deadline = Date.parse(start.expiresAt);
87
87
  // A NaN deadline makes every comparison false, which reads as an instant expiry — or, inverted, as a
88
88
  // loop with no way out. Fail on it rather than guess which.
@@ -92,6 +92,7 @@ export async function authorizeTerminal(api, orgId, wait = sleepSeconds) {
92
92
  const say = (line) => process.stderr.write(line + '\n');
93
93
  say('this terminal is not authorized with GitHub yet — authorize it once:');
94
94
  say(` open ${start.verificationUri} and enter the code ${start.userCode}`);
95
+ open(start.verificationUri);
95
96
  say('waiting for you to confirm… (ctrl-c to abort)');
96
97
  const stopAt = Math.min(deadline, Date.now() + 3600_000); // no device code sensibly outlives an hour
97
98
  const asked = Number(start.interval);
@@ -100,7 +101,7 @@ export async function authorizeTerminal(api, orgId, wait = sleepSeconds) {
100
101
  await wait(interval);
101
102
  let answer;
102
103
  try {
103
- answer = await api.request('POST', `/orgs/${encodeURIComponent(orgId)}/github/device/poll`, { state: start.state });
104
+ answer = await api.request('POST', '/me/github/device/poll', { state: start.state });
104
105
  }
105
106
  catch (e) {
106
107
  // A dropped link, or the per-IP limiter this cadence already tripped on the login flow, must not
@@ -120,50 +121,70 @@ export async function authorizeTerminal(api, orgId, wait = sleepSeconds) {
120
121
  }
121
122
  throw new Error('the GitHub authorization expired before it was confirmed — run the command again');
122
123
  }
123
- // Only the platform's own "you have no usable authorization" may send the person to GitHub: any other
124
- // failure is real, and a device flow cannot fix it.
125
- const needsAuthorization = (e) => e instanceof ApiError && e.status === 400 && /not linked|no longer accepted/i.test(e.message);
126
- // The repositories THIS caller's GitHub account can reach — the same question the platform asks again
127
- // when the connect lands, so a repo missing here would be refused there anyway.
128
- // Someone has to read the code and type it at GitHub. A terminal qualifies, and so does agent mode —
129
- // an agent relays the URL to the person driving it — but --json and a bare pipe have no reader, and a
130
- // ten-minute wait there is a stall where the old code failed with something to act on.
124
+ // Device authorization needs a person to read the code; JSON and bare pipes must fail promptly.
131
125
  export function canAuthorizeHere(opts = {}) {
132
126
  if (opts.json)
133
127
  return false;
134
128
  return !!agentMode() || !!process.stderr.isTTY;
135
129
  }
136
- export async function findCallerRepo(api, orgId, ref, authorize = authorizeTerminal, canAuthorize = canAuthorizeHere()) {
137
- if (!orgId)
138
- throw new Error('this directory is linked without an org — set INSTA_ORG_ID alongside INSTA_PROJECT_ID, or link it with `insta project link`');
139
- let repos;
140
- try {
141
- repos = (await api.request('POST', `/orgs/${encodeURIComponent(orgId)}/github/repos`, {})).repos ?? [];
130
+ export async function findCallerRepo(api, ref, authorize = authorizeTerminal, canAuthorize = canAuthorizeHere(), wait = sleepSeconds, open = openUrl) {
131
+ let mine = await api.request('GET', '/me/github/repos');
132
+ if (!mine.linked && !canAuthorize) {
133
+ throw new Error('this GitHub account is not authorized for InstaCloud yet, and nothing here can read the code GitHub shows — run `insta compute connect-repo` from a terminal, connect the repository from the console, or pass --public for a public repository');
142
134
  }
143
- catch (e) {
144
- // Two 403s carry an action; a third kind would be guessed at, so it is rethrown as the platform put it.
145
- if (e instanceof ApiError && e.status === 403 && /unclassified_agent_action/.test(e.message)) {
146
- throw new Error('this backend does not let an agent authorize GitHub yet — connect the repository from the console, or pass --public for a public repository');
147
- }
148
- if (e instanceof ApiError && e.status === 403 && /requires admin/i.test(e.message)) {
149
- throw new Error('connecting a repository needs the org admin role — ask an admin to connect it, or pass --public for a public repository');
135
+ const repos = mine.linked ? mine.repos : await authorize(api, wait, open);
136
+ const lookup = (rows) => {
137
+ const hit = rows.find((r) => r.owner.toLowerCase() === ref.owner.toLowerCase() && r.repo.toLowerCase() === ref.repo.toLowerCase());
138
+ if (!hit)
139
+ return;
140
+ const whole = (n) => n !== null && n !== '' && Number.isInteger(Number(n)) && Number(n) > 0;
141
+ if (!whole(hit.installationId) || !whole(hit.id))
142
+ throw new Error(`${ref.owner}/${ref.repo} came back without an installation to build it through — reconnect GitHub in the console, or pass --public for a public repository`);
143
+ return { installationId: Number(hit.installationId), repoId: Number(hit.id) };
144
+ };
145
+ const hit = lookup(repos);
146
+ if (hit)
147
+ return hit;
148
+ if (!canAuthorize)
149
+ throw new Error(`${ref.owner}/${ref.repo} is not one your GitHub account can reach through the App — run \`insta compute connect-repo\` without --json from a terminal to install or configure the App, or pass --public for a public repository`);
150
+ if (!mine.linked)
151
+ mine = await api.request('GET', '/me/github/repos');
152
+ const installation = mine.installations.find((i) => i.accountLogin.toLowerCase() === ref.owner.toLowerCase());
153
+ let url;
154
+ if (installation) {
155
+ const settings = installation.accountType === 'Organization' ? `/organizations/${encodeURIComponent(installation.accountLogin)}/settings` : '/settings';
156
+ url = `https://github.com${settings}/installations/${installation.installationId}`;
157
+ }
158
+ else {
159
+ const setup = await api.request('POST', '/me/github/setup', {});
160
+ const install = new URL(setup.installUrl);
161
+ // The CLI verifies access by polling; this marker only selects the browser's return-to-terminal page.
162
+ install.searchParams.set('state', 'cli');
163
+ url = install.toString();
164
+ }
165
+ process.stderr.write(`${installation ? 'configure' : 'install'} the InstaCloud GitHub App on ${ref.owner} and grant access to ${ref.owner}/${ref.repo}:\n ${url}\nIf you cannot change access, ask the account owner or organization admin.\nWaiting for repository access… (ctrl-c to abort)\n`);
166
+ open(url);
167
+ const stopAt = Date.now() + 900_000;
168
+ let interval = 5;
169
+ while (Date.now() < stopAt) {
170
+ await wait(Math.min(interval, (stopAt - Date.now()) / 1000));
171
+ const remaining = stopAt - Date.now();
172
+ if (remaining <= 0)
173
+ break;
174
+ try {
175
+ mine = await api.request('GET', '/me/github/repos', undefined, { signal: AbortSignal.timeout(remaining) });
150
176
  }
151
- if (!needsAuthorization(e))
152
- throw e;
153
- if (!canAuthorize) {
154
- throw new Error('this GitHub account is not authorized for InstaCloud yet, and nothing here can read the code GitHub shows — run `insta compute connect-repo` from a terminal, connect the repository from the console, or pass --public for a public repository');
177
+ catch (e) {
178
+ if (e instanceof ApiError && e.status !== 429)
179
+ throw e;
180
+ interval = pollDelay(interval + 5);
181
+ continue;
155
182
  }
156
- repos = await authorize(api, orgId);
183
+ const ready = lookup(mine.repos);
184
+ if (ready)
185
+ return ready;
157
186
  }
158
- const whole = (n) => n !== null && n !== '' && Number.isInteger(Number(n)) && Number(n) > 0;
159
- const hit = repos.find((r) => r.owner.toLowerCase() === ref.owner.toLowerCase() && r.repo.toLowerCase() === ref.repo.toLowerCase());
160
- if (hit && whole(hit.installationId) && whole(hit.id))
161
- return { installationId: Number(hit.installationId), repoId: Number(hit.id) };
162
- if (hit)
163
- throw new Error(`${ref.owner}/${ref.repo} came back without an installation to build it through — reconnect GitHub in the console, or pass --public for a public repository`);
164
- if (repos.length === 0)
165
- throw new Error('the InstaCloud GitHub App reaches none of your repositories — install it on the account that owns this one (console → Add Service → GitHub Repo → Connect GitHub), or pass --public for a public repository');
166
- throw new Error(`${ref.owner}/${ref.repo} is not one your GitHub account can reach through the App — grant the App access to it on GitHub, or pass --public for a public repository`);
187
+ throw new Error(`timed out waiting for access to ${ref.owner}/${ref.repo} — save the App's repository access on GitHub, then run the command again`);
167
188
  }
168
189
  async function targetService(api, projectId, branch, serviceName) {
169
190
  const { services } = await api.request('GET', `/projects/${projectId}/services${q(branch)}`);
@@ -187,7 +208,7 @@ export async function computeConnectRepo(rawRef, serviceName, opts) {
187
208
  const svc = await targetService(api, p.projectId, opts.branch ?? p.branch, serviceName);
188
209
  const src = opts.public
189
210
  ? { source: 'public', ...ref }
190
- : { source: 'app', ...(await findCallerRepo(api, p.orgId, ref, authorizeTerminal, canAuthorizeHere(opts))), ...ref };
211
+ : { source: 'app', ...(await findCallerRepo(api, ref, authorizeTerminal, canAuthorizeHere(opts))), ...ref };
191
212
  // Detection must scan the branch that will be built: the build refuses commands that differ from what it detects there.
192
213
  const detected = await api.request('POST', `/projects/${p.projectId}/github/detect`, { ...src, ...(opts.repoBranch ? { ref: opts.repoBranch } : {}) });
193
214
  const candidate = pickCandidate(detected.services, opts.rootDir);
package/dist/index.js CHANGED
@@ -255,7 +255,7 @@ for (const [flags, description] of computeCmd.EXEC_OPTIONS)
255
255
  execCmd.option(flags, description);
256
256
  compute.command('repo [service]').description('Show what a compute service deploys from: the image it runs, or the GitHub repository — owner/repo, the branch it builds, root directory, which paths a push must change to redeploy it, and whether pushes redeploy it at all')
257
257
  .option('--json').option('--branch <branch>', 'branch (default: current)').action(guard((service, o) => githubCmd.computeRepo(service, o)));
258
- compute.command('connect-repo <owner/repo> [service]').description("Connect a GitHub repository to an EXISTING compute service: the repo is built (its Dockerfile, or nixpacks when there is none) and deployed into that service, and every later push to the tracked repository branch redeploys it. The repo must be one your own GitHub account can reach through the InstaCloud App, or be public; the first connect from a terminal prints a GitHub URL and a code to authorize it once. Build and start commands come from detection and cannot be set. Connecting again replaces the service's current source")
258
+ compute.command('connect-repo <owner/repo> [service]').description("Connect a GitHub repository to an EXISTING compute service: the repo is built (its Dockerfile, or nixpacks when there is none) and deployed into that service, and every later push to the tracked repository branch redeploys it. The repo must be one your own GitHub account can reach through the InstaCloud App, or be public; the CLI opens GitHub for device-code authorization and App installation or configuration when needed, then waits for repository access and continues. URLs are also printed for remote terminals; --json requires access to be ready. Build and start commands come from detection and cannot be set. Connecting again replaces the service's current source")
259
259
  .option('--public', 'the repo is public and no GitHub App installation is needed (deploys are manual; pushes cannot redeploy)')
260
260
  .option('--root-dir <dir>', 'the directory of the repo to build (a monorepo with several deployable directories lists them and exits 1 without it)')
261
261
  .option('--repo-branch <name>', "the repository branch to build (default: the repo's default branch)")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "insta",
3
- "version": "0.0.71",
3
+ "version": "0.0.73",
4
4
  "type": "module",
5
5
  "description": "InstaCloud CLI — a thin client of the platform control-plane API.",
6
6
  "keywords": [