@north-light/cli 0.3.762 → 0.3.763

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.
@@ -1 +1 @@
1
- var C=Object.defineProperty;var o=(e,n)=>C(e,"name",{value:n,configurable:!0});import{createHash as J,randomBytes as N}from"node:crypto";import{renameSync as R,rmSync as _}from"node:fs";import{hostname as z}from"node:os";import{join as x}from"node:path";import{CrtrError as M,general as f}from"../errors.js";import{atomicWriteJson as E,readJsonOrNull as A}from"../fs-utils.js";import{secretsDir as b}from"../layout.js";import{ExitCode as F}from"../../types.js";import{northlightUnreachable as D}from"./reach.js";const k=o(()=>x(b(),"person-credential"),"personCredentialPath"),y=o(()=>x(b(),"person-bearer.json"),"personBearerPath"),H=o(()=>x(b(),"person-credential.pending"),"pendingPath"),G=3e4,K=o(e=>J("sha256").update(e).digest("hex"),"sha256Hex"),l=o(e=>e.replace(/\/+$/,""),"trimUrl"),v=o(e=>new M("not_signed_in",e,F.USAGE,{next:"Run `crtr sys signin`, then retry."}),"notSignedIn");function h(){const e=A(k());if(!(e===null||typeof e.secret!="string"||typeof e.directoryUrl!="string"))return{directoryUrl:e.directoryUrl,secret:e.secret}}o(h,"readPersonCredential");function p(e,n){const r=e!==null&&typeof e=="object"?e:{},t=r.error;if(t!==null&&typeof t=="object"){const s=t;return{code:String(s.code??"error"),message:String(s.message??`HTTP ${n}`)}}return typeof t=="string"?{code:t,message:String(r.error_description??r.message??t)}:{code:"error",message:`the directory answered HTTP ${n}`}}o(p,"errorOf");async function w(e,n,r,t){let s;try{s=await fetch(`${l(e)}${n}`,{method:"POST",headers:{"content-type":"application/json",...t===void 0?{}:{authorization:`Bearer ${t}`}},body:JSON.stringify(r),signal:AbortSignal.timeout(3e4)})}catch(d){throw D(d,e)}const i=await s.text();let c={};try{c=i===""?{}:JSON.parse(i)}catch{}return{status:s.status,body:c}}o(w,"call");const g=o((e,n)=>{const r=p(n,e);throw f(`the directory refused: ${r.message}`,{code:r.code})},"refuse");async function V(e,n,r={}){const t=l(e),s=r.sleep??(a=>new Promise(u=>setTimeout(u,a))),i=`nld_${N(32).toString("base64url")}`,c=await w(t,"/v1/developer/logins",{credential_hash:K(i),name:z().slice(0,64),platform:process.platform==="darwin"||process.platform==="win32"?process.platform:"linux",sdk_version:"crtr",kind:"crtr"});c.status!==200&&c.status!==201&&g(c.status,c.body);const d=c.body;n({verificationUri:d.verification_uri,userCode:d.user_code,complete:d.verification_uri_complete});let $=Math.max(1,d.interval)*1e3;const j=Date.now()+d.expires_in*1e3;for(;;){if(Date.now()>j)throw f("the sign-in code expired before it was allowed: run `crtr sys signin` again",{code:"expired_token"});await s($);const a=await w(t,"/v1/developer/logins/poll",{device_code:d.device_code});if(a.status===200){const m=a.body,P=await S(t,i),B=await r.accept?.({account:m.account,bearer:P.access_token});if(B!==void 0)throw await T(t,i),B;return E(H(),{directoryUrl:t,secret:i},{mode:384}),R(H(),k()),U(t,P),{account:m.account.display,credentialId:m.credential_id}}const u=p(a.body,a.status).code;if(!(a.status===400&&u==="authorization_pending")){if(a.status===400&&u==="slow_down"){$+=5e3;continue}if(a.status===400&&u==="access_denied")throw f("the sign-in was declined in the browser",{code:u});if(a.status===400&&u==="expired_token")throw f("the sign-in code expired before it was allowed: run `crtr sys signin` again",{code:u});g(a.status,a.body)}}}o(V,"signIn");const I=new Set(["credential_revoked","credential_expired","credential_unknown"]);async function S(e,n,r=!1){const t=await w(e,"/v1/developer/token",{},n);if(t.status===401&&I.has(p(t.body,401).code))throw r&&_(y(),{force:!0}),v(`the sign-in on this computer is no longer valid (${p(t.body,401).code})`);t.status!==200&&g(t.status,t.body);const s=t.body;if(typeof s.access_token!="string"||typeof s.expires_in!="number")throw f("the directory answered without a bearer token");const i=s.account;return{access_token:s.access_token,expires_in:s.expires_in,...typeof i?.id=="string"&&typeof i.display=="string"?{account:{id:i.id,display:i.display}}:{}}}o(S,"exchange");function U(e,n){E(y(),{directoryUrl:e,access_token:n.access_token,expires_at_ms:Date.now()+n.expires_in*1e3},{mode:384})}o(U,"writeBearer");async function O(e){const n=h();if(n===void 0)throw v("this computer is not signed in");const r=l(e??n.directoryUrl),t=A(y());if(t!==null&&t.directoryUrl===r&&typeof t.access_token=="string"&&t.expires_at_ms-Date.now()>G)return t.access_token;const s=await S(r,n.secret,!0);return U(r,s),s.access_token}o(O,"personBearer");function oe(e,n){return async(r,t)=>{const s=new Headers(t?.headers);s.set("authorization",`Bearer ${await O(e)}`);try{return await fetch(r,{...t,headers:s})}catch(i){throw t?.signal?.aborted===!0?i:D(i,n)}}}o(oe,"northlightFetch");async function se(e){const n=h();if(n===void 0)throw v("this computer is not signed in");const r=l(e??n.directoryUrl),t=await S(r,n.secret,!0);if(U(r,t),t.account===void 0)throw f("the directory's token answer names no account");return t.account}o(se,"personAccount");async function ie(e){const n=await O(e);let r;try{r=JSON.parse(Buffer.from(n.split(".")[1]??"","base64url").toString("utf8")).aud}catch{r=void 0}const t=Array.isArray(r)?r[0]:r;if(typeof t!="string"||!/^https?:\/\//.test(t))throw f("the directory's sign-in token names no control plane (no http(s) `aud`)");return l(t)}o(ie,"controlPlaneUrl");async function T(e,n){const r=await w(e,"/v1/developer/token/revoke",{},n);return r.status===200?!0:r.status===401&&I.has(p(r.body,401).code)?!1:g(r.status,r.body)}o(T,"revoke");function W(){_(k(),{force:!0}),_(y(),{force:!0})}o(W,"forgetSignIn");async function ae(){const e=h();if(e===void 0)return{signedOut:!1,revoked:!1};const n=await T(e.directoryUrl,e.secret);return W(),{signedOut:!0,revoked:n}}o(ae,"signOut");async function ce(e,n){return h()===void 0&&await V(e,n),O(e)}o(ce,"ensureSignedIn");export{ie as controlPlaneUrl,ce as ensureSignedIn,W as forgetSignIn,oe as northlightFetch,v as notSignedIn,se as personAccount,O as personBearer,y as personBearerPath,k as personCredentialPath,h as readPersonCredential,V as signIn,ae as signOut};
1
+ var M=Object.defineProperty;var s=(e,n)=>M(e,"name",{value:n,configurable:!0});import{createHash as N,randomBytes as R}from"node:crypto";import{renameSync as z,rmSync as b}from"node:fs";import{hostname as F}from"node:os";import{join as y}from"node:path";import{CrtrError as G,general as f}from"../errors.js";import{atomicWriteJson as A,readJsonOrNull as B}from"../fs-utils.js";import{withExclusiveDirectoryLockAsync as D}from"../exclusive-lock.js";import{secretsDir as h}from"../layout.js";import{ExitCode as L}from"../../types.js";import{northlightUnreachable as H}from"./reach.js";const k=s(()=>y(h(),"person-credential"),"personCredentialPath"),w=s(()=>y(h(),"person-bearer.json"),"personBearerPath"),I=s(()=>y(h(),"person-credential.pending"),"pendingPath"),T=s(()=>y(h(),"person-bearer.lock"),"refreshLockPath"),K=3e4,V=s(e=>N("sha256").update(e).digest("hex"),"sha256Hex"),l=s(e=>e.replace(/\/+$/,""),"trimUrl"),v=s(e=>new G("not_signed_in",e,L.USAGE,{next:"Run `crtr sys signin`, then retry."}),"notSignedIn");function m(){const e=B(k());if(!(e===null||typeof e.secret!="string"||typeof e.directoryUrl!="string"))return{directoryUrl:e.directoryUrl,secret:e.secret}}s(m,"readPersonCredential");function p(e,n){const r=e!==null&&typeof e=="object"?e:{},t=r.error;if(t!==null&&typeof t=="object"){const i=t;return{code:String(i.code??"error"),message:String(i.message??`HTTP ${n}`)}}return typeof t=="string"?{code:t,message:String(r.error_description??r.message??t)}:{code:"error",message:`the directory answered HTTP ${n}`}}s(p,"errorOf");async function g(e,n,r,t){let i;try{i=await fetch(`${l(e)}${n}`,{method:"POST",headers:{"content-type":"application/json",...t===void 0?{}:{authorization:`Bearer ${t}`}},body:JSON.stringify(r),signal:AbortSignal.timeout(3e4)})}catch(d){throw H(d,e)}const o=await i.text();let a={};try{a=o===""?{}:JSON.parse(o)}catch{}return{status:i.status,body:a}}s(g,"call");const _=s((e,n)=>{const r=p(n,e);throw f(`the directory refused: ${r.message}`,{code:r.code})},"refuse");async function W(e,n,r={}){const t=l(e),i=r.sleep??(c=>new Promise(u=>setTimeout(u,c))),o=`nld_${R(32).toString("base64url")}`,a=await g(t,"/v1/developer/logins",{credential_hash:V(o),name:F().slice(0,64),platform:process.platform==="darwin"||process.platform==="win32"?process.platform:"linux",sdk_version:"crtr",kind:"crtr"});a.status!==200&&a.status!==201&&_(a.status,a.body);const d=a.body;n({verificationUri:d.verification_uri,userCode:d.user_code,complete:d.verification_uri_complete});let P=Math.max(1,d.interval)*1e3;const J=Date.now()+d.expires_in*1e3;for(;;){if(Date.now()>J)throw f("the sign-in code expired before it was allowed: run `crtr sys signin` again",{code:"expired_token"});await i(P);const c=await g(t,"/v1/developer/logins/poll",{device_code:d.device_code});if(c.status===200){const x=c.body,$=await S(t,o),E=await r.accept?.({account:x.account,bearer:$.access_token});if(E!==void 0)throw await C(t,o),E;return A(I(),{directoryUrl:t,secret:o},{mode:384}),z(I(),k()),U(t,$),{account:x.account.display,credentialId:x.credential_id}}const u=p(c.body,c.status).code;if(!(c.status===400&&u==="authorization_pending")){if(c.status===400&&u==="slow_down"){P+=5e3;continue}if(c.status===400&&u==="access_denied")throw f("the sign-in was declined in the browser",{code:u});if(c.status===400&&u==="expired_token")throw f("the sign-in code expired before it was allowed: run `crtr sys signin` again",{code:u});_(c.status,c.body)}}}s(W,"signIn");const j=new Set(["credential_revoked","credential_expired","credential_unknown"]);async function S(e,n,r=!1){const t=await g(e,"/v1/developer/token",{},n);if(t.status===401&&j.has(p(t.body,401).code))throw r&&b(w(),{force:!0}),v(`the sign-in on this computer is no longer valid (${p(t.body,401).code})`);t.status!==200&&_(t.status,t.body);const i=t.body;if(typeof i.access_token!="string"||typeof i.expires_in!="number")throw f("the directory answered without a bearer token");const o=i.account;return{access_token:i.access_token,expires_in:i.expires_in,...typeof o?.id=="string"&&typeof o.display=="string"?{account:{id:o.id,display:o.display}}:{}}}s(S,"exchange");function U(e,n){A(w(),{directoryUrl:e,access_token:n.access_token,expires_at_ms:Date.now()+n.expires_in*1e3},{mode:384})}s(U,"writeBearer");async function O(e){const n=m();if(n===void 0)throw v("this computer is not signed in");const r=l(e??n.directoryUrl),t=s(()=>{const o=B(w());return o!==null&&o.directoryUrl===r&&typeof o.access_token=="string"&&o.expires_at_ms-Date.now()>K?o.access_token:void 0},"fresh"),i=t();return i!==void 0?i:D(T(),async()=>{const o=t();if(o!==void 0)return o;const a=await S(r,n.secret,!0);return U(r,a),a.access_token},{timeoutMs:4e4})}s(O,"personBearer");function ce(e,n){return async(r,t)=>{const i=new Headers(t?.headers);i.set("authorization",`Bearer ${await O(e)}`);try{return await fetch(r,{...t,headers:i})}catch(o){throw t?.signal?.aborted===!0?o:H(o,n)}}}s(ce,"northlightFetch");async function ae(e){const n=m();if(n===void 0)throw v("this computer is not signed in");const r=l(e??n.directoryUrl),t=await D(T(),async()=>{const i=await S(r,n.secret,!0);return U(r,i),i},{timeoutMs:4e4});if(t.account===void 0)throw f("the directory's token answer names no account");return t.account}s(ae,"personAccount");async function de(e){const n=await O(e);let r;try{r=JSON.parse(Buffer.from(n.split(".")[1]??"","base64url").toString("utf8")).aud}catch{r=void 0}const t=Array.isArray(r)?r[0]:r;if(typeof t!="string"||!/^https?:\/\//.test(t))throw f("the directory's sign-in token names no control plane (no http(s) `aud`)");return l(t)}s(de,"controlPlaneUrl");async function C(e,n){const r=await g(e,"/v1/developer/token/revoke",{},n);return r.status===200?!0:r.status===401&&j.has(p(r.body,401).code)?!1:_(r.status,r.body)}s(C,"revoke");function q(){b(k(),{force:!0}),b(w(),{force:!0})}s(q,"forgetSignIn");async function ue(){const e=m();if(e===void 0)return{signedOut:!1,revoked:!1};const n=await C(e.directoryUrl,e.secret);return q(),{signedOut:!0,revoked:n}}s(ue,"signOut");async function fe(e,n){return m()===void 0&&await W(e,n),O(e)}s(fe,"ensureSignedIn");export{de as controlPlaneUrl,fe as ensureSignedIn,q as forgetSignIn,ce as northlightFetch,v as notSignedIn,ae as personAccount,O as personBearer,w as personBearerPath,k as personCredentialPath,m as readPersonCredential,W as signIn,ue as signOut};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.762",
3
+ "version": "0.3.763",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -157,8 +157,8 @@
157
157
  },
158
158
  "license": "UNLICENSED",
159
159
  "dependencies": {
160
- "@north-light/identity": "0.3.762",
161
- "@north-light/plugin": "0.3.762",
160
+ "@north-light/identity": "0.3.763",
161
+ "@north-light/plugin": "0.3.763",
162
162
  "@earendil-works/chord": "1.5.2",
163
163
  "@earendil-works/pi-agent-core": "1.5.2",
164
164
  "@earendil-works/pi-ai": "1.5.2",
@@ -8,12 +8,15 @@ import { hostname } from 'node:os';
8
8
  import { join } from 'node:path';
9
9
  import { CrtrError, general } from '../errors.js';
10
10
  import { atomicWriteJson, readJsonOrNull } from '../fs-utils.js';
11
+ import { withExclusiveDirectoryLockAsync } from '../exclusive-lock.js';
11
12
  import { secretsDir } from '../layout.js';
12
13
  import { ExitCode } from '../../types.js';
13
14
  import { northlightUnreachable } from './reach.js';
14
15
  export const personCredentialPath = () => join(secretsDir(), 'person-credential');
15
16
  export const personBearerPath = () => join(secretsDir(), 'person-bearer.json');
16
17
  const pendingPath = () => join(secretsDir(), 'person-credential.pending');
18
+ /** Serializes bearer refreshes across every crtr process on this computer, so a stale cache costs one exchange, not one per process. */
19
+ const refreshLockPath = () => join(secretsDir(), 'person-bearer.lock');
17
20
  const REFRESH_MARGIN_MS = 30_000;
18
21
  const sha256Hex = (text) => createHash('sha256').update(text).digest('hex');
19
22
  const trimUrl = (url) => url.replace(/\/+$/, '');
@@ -137,12 +140,23 @@ export async function personBearer(directoryUrl) {
137
140
  if (credential === undefined)
138
141
  throw notSignedIn('this computer is not signed in');
139
142
  const directory = trimUrl(directoryUrl ?? credential.directoryUrl);
140
- const cached = readJsonOrNull(personBearerPath());
141
- if (cached !== null && cached.directoryUrl === directory && typeof cached.access_token === 'string' && cached.expires_at_ms - Date.now() > REFRESH_MARGIN_MS)
142
- return cached.access_token;
143
- const bearer = await exchange(directory, credential.secret, true);
144
- writeBearer(directory, bearer);
145
- return bearer.access_token;
143
+ const fresh = () => {
144
+ const cached = readJsonOrNull(personBearerPath());
145
+ return cached !== null && cached.directoryUrl === directory && typeof cached.access_token === 'string' && cached.expires_at_ms - Date.now() > REFRESH_MARGIN_MS ? cached.access_token : undefined;
146
+ };
147
+ const hit = fresh();
148
+ if (hit !== undefined)
149
+ return hit;
150
+ // Many crtr processes see the cache go stale at the same moment; without this lock each one exchanged, and the directory's
151
+ // 600-an-hour limit per sign-in answered "Too many requests from this login". The first holder exchanges; the rest read its result.
152
+ return withExclusiveDirectoryLockAsync(refreshLockPath(), async () => {
153
+ const raced = fresh();
154
+ if (raced !== undefined)
155
+ return raced;
156
+ const bearer = await exchange(directory, credential.secret, true);
157
+ writeBearer(directory, bearer);
158
+ return bearer.access_token;
159
+ }, { timeoutMs: 40_000 });
146
160
  }
147
161
  /** A `fetch` for the control plane at `apiUrl`: each request carries the person's bearer for `directoryUrl` (fetched per request, so a long command never sends
148
162
  * an ended one), a sign-in refusal crosses as its own `CrtrError`, and a request that never got an HTTP answer is `northlight_unreachable` (a caller's own abort
@@ -167,8 +181,11 @@ export async function personAccount(directoryUrl) {
167
181
  if (credential === undefined)
168
182
  throw notSignedIn('this computer is not signed in');
169
183
  const directory = trimUrl(directoryUrl ?? credential.directoryUrl);
170
- const bearer = await exchange(directory, credential.secret, true);
171
- writeBearer(directory, bearer);
184
+ const bearer = await withExclusiveDirectoryLockAsync(refreshLockPath(), async () => {
185
+ const answer = await exchange(directory, credential.secret, true);
186
+ writeBearer(directory, answer);
187
+ return answer;
188
+ }, { timeoutMs: 40_000 });
172
189
  if (bearer.account === undefined)
173
190
  throw general('the directory\'s token answer names no account');
174
191
  return bearer.account;
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.762",
3
+ "version": "0.3.763",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.762",
3
+ "version": "0.3.763",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.762",
3
+ "version": "0.3.763",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -27,8 +27,8 @@
27
27
  "postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
28
28
  },
29
29
  "dependencies": {
30
- "@north-light/api": "0.3.762",
31
- "@north-light/identity": "0.3.762"
30
+ "@north-light/api": "0.3.763",
31
+ "@north-light/identity": "0.3.763"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.762",
3
+ "version": "0.3.763",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.762",
9
+ "version": "0.3.763",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,8 +28,8 @@
28
28
  "@milkdown/preset-gfm": "^7.22.3",
29
29
  "@milkdown/prose": "^7.22.3",
30
30
  "@milkdown/utils": "^7.22.3",
31
- "@north-light/identity": "0.3.762",
32
- "@north-light/plugin": "0.3.762",
31
+ "@north-light/identity": "0.3.763",
32
+ "@north-light/plugin": "0.3.763",
33
33
  "cron-parser": "^5.6.0",
34
34
  "esbuild": "0.28.2",
35
35
  "jose": "^6.2.12",
@@ -11902,17 +11902,17 @@
11902
11902
  },
11903
11903
  "packages/crouter-api": {
11904
11904
  "name": "@north-light/api",
11905
- "version": "0.3.762",
11905
+ "version": "0.3.763",
11906
11906
  "license": "UNLICENSED"
11907
11907
  },
11908
11908
  "packages/crouter-env-docker": {
11909
11909
  "name": "@north-light/env-docker",
11910
- "version": "0.3.762",
11910
+ "version": "0.3.763",
11911
11911
  "license": "UNLICENSED"
11912
11912
  },
11913
11913
  "packages/crouter-identity": {
11914
11914
  "name": "@north-light/identity",
11915
- "version": "0.3.762",
11915
+ "version": "0.3.763",
11916
11916
  "license": "UNLICENSED",
11917
11917
  "dependencies": {
11918
11918
  "jose": "^6.2.1"
@@ -11920,21 +11920,21 @@
11920
11920
  },
11921
11921
  "packages/crouter-plugin": {
11922
11922
  "name": "@north-light/plugin",
11923
- "version": "0.3.762",
11923
+ "version": "0.3.763",
11924
11924
  "license": "UNLICENSED",
11925
11925
  "dependencies": {
11926
- "@north-light/api": "0.3.762",
11927
- "@north-light/identity": "0.3.762"
11926
+ "@north-light/api": "0.3.763",
11927
+ "@north-light/identity": "0.3.763"
11928
11928
  }
11929
11929
  },
11930
11930
  "packages/crouter-sdk": {
11931
11931
  "name": "@north-light/sdk",
11932
- "version": "0.3.762",
11932
+ "version": "0.3.763",
11933
11933
  "license": "UNLICENSED",
11934
11934
  "dependencies": {
11935
- "@north-light/api": "0.3.762",
11936
- "@north-light/identity": "0.3.762",
11937
- "@north-light/plugin": "0.3.762",
11935
+ "@north-light/api": "0.3.763",
11936
+ "@north-light/identity": "0.3.763",
11937
+ "@north-light/plugin": "0.3.763",
11938
11938
  "jose": "^6.2.1"
11939
11939
  },
11940
11940
  "bin": {