@redaktyn/cli 1.5.9 → 1.6.2

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,25 +1,26 @@
1
1
  #!/usr/bin/env node
2
- import{readFileSync as me,realpathSync as ye}from"node:fs";import{basename as K}from"node:path";import*as $e from"node:readline";import{pathToFileURL as we}from"node:url";import{canonicalize as ke,computeHmac as ve,deriveKey as be,deriveProjectKey as Se,enrollPayload as je}from"./redaktyn-fingerprint.mjs";import{freshAdminSession as Re,freshSession as Ae,loadAdminSession as U,loadSession as Ee,resolveServerUrl as Ne}from"./redaktyn-session.mjs";import{askWorkspacePassphrase as xe}from"./redaktyn-passphrase.mjs";import{banner as Te,bar as Oe,box as B,g as C,humanBytes as z,k as g,rich as j,reveal as Ie,rows as J,say as w,step as G}from"./redaktyn-ui.mjs";import{createRequire as Le}from"node:module";const _e=Le(import.meta.url)("./package.json").version,x=process.argv.includes("--no-color")||!!process.env.NO_COLOR,s={reset:x?"":"\x1B[0m",bold:x?"":"\x1B[1m",dim:x?"":"\x1B[2m",red:x?"":"\x1B[31m",green:x?"":"\x1B[32m",yellow:x?"":"\x1B[33m",blue:x?"":"\x1B[34m",cyan:x?"":"\x1B[36m",gray:x?"":"\x1B[90m"};class m extends Error{}const V=15e5,Z=5e4,Pe=1e4,D=5*1024*1024,Ce=256,De=65536,He=/^v1\.[0-9a-f]{12}$/,X=e=>typeof e.scanPrefilter=="string"&&He.test(e.scanPrefilter);function Q(e,t=!1){const o=[new Map,new Map,new Map],r=(n,i,h)=>{if(!(i>0))return;const a=o[n].get(i);o[n].set(i,a?{windowLen:i,prefiltered:a.prefiltered&&h,entries:a.entries+1}:{windowLen:i,prefiltered:h,entries:1})};for(const n of e){const i=t||X(n);n.hmacHex&&r(0,n.length,i),typeof n.hmacHexStripped=="string"&&r(1,n.lengthStripped,i),typeof n.hmacHexLower=="string"&&r(2,n.lengthLower,i)}return o.flatMap(n=>[...n.values()])}function ee(e,t){let o=0;for(const r of t){const n=Math.max(0,e-r.windowLen+1);o+=r.prefiltered?Math.ceil(n/Ce)+Math.ceil(n*r.entries/De):n}return o}function te(e){if(e.length===0)return 1/0;if(ee(D,e)<=V)return D;let t=0,o=D;for(;t<o;){const r=Math.ceil((t+o)/2);ee(r,e)<=V?t=r:o=r-1}return t}function Me(e){const t=Q(e),o=te(t);return{windowLengths:t.length,ceiling:o,legacySecrets:e.filter(r=>r.hmacHex&&!X(r)).length,ceilingIfReenrolled:te(Q(e,!0)),atCharacterCap:o===D}}function We(e){return e.length===0||e.some(t=>t&&Object.prototype.hasOwnProperty.call(t,"scanPrefilter"))}function Ke(e){const t=e.data&&Array.isArray(e.data.unknownFields)?e.data.unknownFields:null;return e.status===400&&e.data?.code==="UNKNOWN_FIELD"&&t!==null&&t.length===1&&t[0]==="scanPrefilter"}function Je(e){const t={help:!1,env:null,jsonFile:null,yaml:null,stdin:!1,source:null,apply:!1,yes:!1,minLength:null,allowWeak:!1,only:[],exclude:[],server:null,orgId:null,project:null,reportJson:!1,showRequest:!1,noColor:!1},o=(r,n)=>{const i=e[r];if(i===void 0||i.startsWith("--"))throw new m(`${n} needs a value`);return i};for(let r=2;r<e.length;r++){const n=e[r];if(n==="--help"||n==="-h")t.help=!0;else if(n==="--env")t.env=o(++r,"--env");else if(n==="--json")t.jsonFile=o(++r,"--json");else if(n==="--yaml")t.yaml=o(++r,"--yaml");else if(n==="--stdin")t.stdin=!0;else if(n==="--source")t.source=o(++r,"--source");else if(n==="--apply")t.apply=!0;else if(n==="--yes"||n==="-y")t.yes=!0;else if(n==="--min-length")t.minLength=Number(o(++r,"--min-length"));else if(n==="--allow-weak")t.allowWeak=!0;else if(n==="--only")t.only.push(o(++r,"--only"));else if(n==="--exclude")t.exclude.push(o(++r,"--exclude"));else if(n==="--server")t.server=o(++r,"--server");else if(n==="--org-id")t.orgId=o(++r,"--org-id");else if(n==="--project")t.project=o(++r,"--project");else if(n==="--report-json")t.reportJson=!0;else if(n==="--show-request")t.showRequest=!0;else if(n==="--no-color")t.noColor=!0;else throw new m(`Unknown flag: ${n}`)}if(t.minLength!==null&&(!Number.isInteger(t.minLength)||t.minLength<1))throw new m("--min-length must be a positive integer");return t}const Ye=/^[A-Za-z_][A-Za-z0-9_.-]*$/;function Fe(e){const t=e.replace(/\r\n/g,`
2
+ import{readFileSync as ke,realpathSync as be}from"node:fs";import{basename as Y}from"node:path";import*as ve from"node:readline";import{pathToFileURL as Se}from"node:url";import{canonicalize as je,computeHmac as Re,deriveProjectKey as Ee,enrollPayload as Ne}from"./redaktyn-fingerprint.mjs";import{freshAdminSession as Ae,freshSession as xe,loadAdminSession as G,loadSession as Te,resolveServerUrl as Oe}from"./redaktyn-session.mjs";import{askWorkspaceKey as Ie}from"./redaktyn-passphrase.mjs";import{banner as Le,bar as _e,box as z,g as D,humanBytes as V,k as g,rich as E,reveal as Pe,rows as J,say as w,step as Z}from"./redaktyn-ui.mjs";import{createRequire as Ce}from"node:module";const X=Ce(import.meta.url),De=X("./package.json").version;function Me(){try{const e=X("./redaktyn-shared.cjs");return typeof e.assessSecretGuessability=="function"?e.assessSecretGuessability:null}catch{return null}}const A=process.argv.includes("--no-color")||!!process.env.NO_COLOR,s={reset:A?"":"\x1B[0m",bold:A?"":"\x1B[1m",dim:A?"":"\x1B[2m",red:A?"":"\x1B[31m",green:A?"":"\x1B[32m",yellow:A?"":"\x1B[33m",blue:A?"":"\x1B[34m",cyan:A?"":"\x1B[36m",gray:A?"":"\x1B[90m"};class y extends Error{}const Q=15e5,ee=5e4,He=1e4,M=5*1024*1024,We=256,Ke=65536,Ye=/^v1\.[0-9a-f]{12}$/,te=e=>typeof e.scanPrefilter=="string"&&Ye.test(e.scanPrefilter);function ne(e,t=!1){const r=[new Map,new Map,new Map],o=(n,i,p)=>{if(!(i>0))return;const l=r[n].get(i);r[n].set(i,l?{windowLen:i,prefiltered:l.prefiltered&&p,entries:l.entries+1}:{windowLen:i,prefiltered:p,entries:1})};for(const n of e){const i=t||te(n);n.hmacHex&&o(0,n.length,i),typeof n.hmacHexStripped=="string"&&o(1,n.lengthStripped,i),typeof n.hmacHexLower=="string"&&o(2,n.lengthLower,i)}return r.flatMap(n=>[...n.values()])}function oe(e,t){let r=0;for(const o of t){const n=Math.max(0,e-o.windowLen+1);r+=o.prefiltered?Math.ceil(n/We)+Math.ceil(n*o.entries/Ke):n}return r}function re(e){if(e.length===0)return 1/0;if(oe(M,e)<=Q)return M;let t=0,r=M;for(;t<r;){const o=Math.ceil((t+r)/2);oe(o,e)<=Q?t=o:r=o-1}return t}function Je(e){const t=ne(e),r=re(t);return{windowLengths:t.length,ceiling:r,legacySecrets:e.filter(o=>o.hmacHex&&!te(o)).length,ceilingIfReenrolled:re(ne(e,!0)),atCharacterCap:r===M}}function qe(e){return e.length===0||e.some(t=>t&&Object.prototype.hasOwnProperty.call(t,"scanPrefilter"))}function Fe(e){const t=e.data&&Array.isArray(e.data.unknownFields)?e.data.unknownFields:null;return e.status===400&&e.data?.code==="UNKNOWN_FIELD"&&t!==null&&t.length===1&&t[0]==="scanPrefilter"}function Be(e){const t={help:!1,env:null,jsonFile:null,yaml:null,stdin:!1,source:null,apply:!1,yes:!1,minLength:null,allowWeak:!1,only:[],exclude:[],server:null,orgId:null,project:null,reportJson:!1,showRequest:!1,noColor:!1},r=(o,n)=>{const i=e[o];if(i===void 0||i.startsWith("--"))throw new y(`${n} needs a value`);return i};for(let o=2;o<e.length;o++){const n=e[o];if(n==="--help"||n==="-h")t.help=!0;else if(n==="--env")t.env=r(++o,"--env");else if(n==="--json")t.jsonFile=r(++o,"--json");else if(n==="--yaml")t.yaml=r(++o,"--yaml");else if(n==="--stdin")t.stdin=!0;else if(n==="--source")t.source=r(++o,"--source");else if(n==="--apply")t.apply=!0;else if(n==="--yes"||n==="-y")t.yes=!0;else if(n==="--min-length")t.minLength=Number(r(++o,"--min-length"));else if(n==="--allow-weak")t.allowWeak=!0;else if(n==="--only")t.only.push(r(++o,"--only"));else if(n==="--exclude")t.exclude.push(r(++o,"--exclude"));else if(n==="--server")t.server=r(++o,"--server");else if(n==="--org-id")t.orgId=r(++o,"--org-id");else if(n==="--project")t.project=r(++o,"--project");else if(n==="--report-json")t.reportJson=!0;else if(n==="--show-request")t.showRequest=!0;else if(n==="--no-color")t.noColor=!0;else throw new y(`Unknown flag: ${n}`)}if(t.minLength!==null&&(!Number.isInteger(t.minLength)||t.minLength<1))throw new y("--min-length must be a positive integer");return t}const Ue=/^[A-Za-z_][A-Za-z0-9_.-]*$/;function Ge(e){const t=e.replace(/\r\n/g,`
3
3
  `).replace(/\r/g,`
4
- `),o=[],r=[];let n=0,i=1;const h=()=>{const c=t.indexOf(`
5
- `,n);n=c===-1?t.length:c+1},a=(c,p)=>{let l=0;for(let d=c;d<p;d++)t[d]===`
6
- `&&l++;return l};for(;n<t.length;){const c=t[n];if(c===`
7
- `){i++,n++;continue}if(c===" "||c===" "){n++;continue}if(c==="#"){h(),i++;continue}const p=i;let l=n;for(;l<t.length&&t[l]!=="="&&t[l]!==`
8
- `;)l++;if(l>=t.length||t[l]===`
9
- `){r.push({line:p,message:"no '=' on this line \u2014 skipped"}),n=l+1,i++;continue}let d=t.slice(n,l).trim();for(/^export\s/.test(d)&&(d=d.replace(/^export\s+/,"").trim()),n=l+1;n<t.length&&(t[n]===" "||t[n]===" ");)n++;let y="",u=!0;const $=t[n];if($==='"'||$==="'"){const S=++n,k=t.indexOf(`
10
- `,n);let b=!1;for(;n<t.length;){const v=t[n];if(v==="\\"&&$==='"'&&n+1<t.length){const E=t[n+1];y+=E==="n"?`
11
- `:E==="t"?" ":E==="r"?"\r":E,n+=2;continue}if(v===$){n++,b=!0;break}y+=v,n++}b?(i+=a(S,n),h(),i++):(r.push({line:p,message:"unterminated quote \u2014 skipped this entry"}),u=!1,n=k===-1?t.length:k+1,i++)}else{const S=t.indexOf(`
12
- `,n),k=S===-1?t.length:S;let b=t.slice(n,k);const v=b.search(/\s#/);v!==-1&&(b=b.slice(0,v)),y=b.trim(),n=k===t.length?k:k+1,i++}if(u){if(!Ye.test(d)){r.push({line:p,message:`unusable key name ${JSON.stringify(d)} \u2014 skipped`});continue}o.push({key:d,value:y,line:p})}}return{entries:o,problems:r}}const qe=new Set(["data","metadata","lease_id","lease_duration","lease_renewable","renewable","request_id","warnings","auth","wrap_info","mount_type"]),L=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ne(e){if(!L(e))throw new m("Expected a JSON object of secrets, got "+re(e));if(typeof e.SecretString=="string"){let r;try{r=JSON.parse(e.SecretString)}catch{throw new m("SecretString is not JSON. For a single-value secret pass it to redaktyn-fingerprint instead.")}return ne(r)}if(Array.isArray(e.fields)){const r={};for(const n of e.fields){if(!L(n))continue;const i=n.label??n.id;typeof i!="string"||typeof n.value!="string"||(r[i]=n.value)}return{shape:"1password-item",doc:r}}const t=Object.keys(e);if(t.length>0&&t.every(r=>qe.has(r))&&L(e.data)){const r=e.data;return L(r.data)&&"metadata"in r?{shape:"vault-kv2",doc:r.data}:{shape:"vault-kv1",doc:r}}return{shape:"flat",doc:e}}function re(e){return e===null?"null":Array.isArray(e)?"an array":typeof e}function Ue(e){const t=[],o=[];for(const[r,n]of Object.entries(e)){if(typeof n=="string"){t.push({key:r,value:n});continue}if(typeof n=="number"||typeof n=="boolean"){t.push({key:r,value:String(n)});continue}if(L(n)){const i=["value","raw","computed","computedValue"].find(h=>typeof n[h]=="string");if(i){t.push({key:r,value:n[i]});continue}o.push({key:r,message:"nested object with no value/raw/computed field \u2014 skipped"});continue}o.push({key:r,message:`${re(n)} is not a secret value \u2014 skipped`})}return{entries:t,problems:o}}function oe(e){let t;try{t=JSON.parse(e)}catch(h){throw new m(`Input is not valid JSON: ${h.message}`)}const{shape:o,doc:r}=ne(t),{entries:n,problems:i}=Ue(r);return{entries:n,problems:i,shape:o}}function Be(e){const t=[],o=[];return e.replace(/\r\n/g,`
4
+ `),r=[],o=[];let n=0,i=1;const p=()=>{const d=t.indexOf(`
5
+ `,n);n=d===-1?t.length:d+1},l=(d,a)=>{let u=0;for(let m=d;m<a;m++)t[m]===`
6
+ `&&u++;return u};for(;n<t.length;){const d=t[n];if(d===`
7
+ `){i++,n++;continue}if(d===" "||d===" "){n++;continue}if(d==="#"){p(),i++;continue}const a=i;let u=n;for(;u<t.length&&t[u]!=="="&&t[u]!==`
8
+ `;)u++;if(u>=t.length||t[u]===`
9
+ `){o.push({line:a,message:"no '=' on this line \u2014 skipped"}),n=u+1,i++;continue}let m=t.slice(n,u).trim();for(/^export\s/.test(m)&&(m=m.replace(/^export\s+/,"").trim()),n=u+1;n<t.length&&(t[n]===" "||t[n]===" ");)n++;let $="",c=!0;const f=t[n];if(f==='"'||f==="'"||f==="`"){const k=++n,v=t.indexOf(`
10
+ `,n);let b=!1;for(;n<t.length;){const S=t[n];if(S==="\\"&&f==='"'&&n+1<t.length){const j=t[n+1];$+=j==="n"?`
11
+ `:j==="t"?" ":j==="r"?"\r":j==='"'||j==="\\"?j:`\\${j}`,n+=2;continue}if(S===f){n++,b=!0;break}$+=S,n++}b?(i+=l(k,n),p(),i++):(o.push({line:a,message:"unterminated quote \u2014 skipped this entry"}),c=!1,n=v===-1?t.length:v+1,i++)}else{const k=t.indexOf(`
12
+ `,n),v=k===-1?t.length:k;let b=t.slice(n,v);const S=b.search(/\s#/);S!==-1&&(b=b.slice(0,S)),$=b.trim(),n=v===t.length?v:v+1,i++}if(c){if(!Ue.test(m)){o.push({line:a,message:`unusable key name ${JSON.stringify(m)} \u2014 skipped`});continue}r.push({key:m,value:$,line:a})}}return{entries:r,problems:o}}const ze=new Set(["data","metadata","lease_id","lease_duration","lease_renewable","renewable","request_id","warnings","auth","wrap_info","mount_type"]),_=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function se(e){if(!_(e))throw new y("Expected a JSON object of secrets, got "+ie(e));if(typeof e.SecretString=="string"){let o;try{o=JSON.parse(e.SecretString)}catch{throw new y("SecretString is not JSON. For a single-value secret pass it to redaktyn-fingerprint instead.")}return se(o)}if(Array.isArray(e.fields)){const o={};for(const n of e.fields){if(!_(n))continue;const i=n.label??n.id;typeof i!="string"||typeof n.value!="string"||(o[i]=n.value)}return{shape:"1password-item",doc:o}}const t=Object.keys(e);if(t.length>0&&t.every(o=>ze.has(o))&&_(e.data)){const o=e.data;return _(o.data)&&"metadata"in o?{shape:"vault-kv2",doc:o.data}:{shape:"vault-kv1",doc:o}}return{shape:"flat",doc:e}}function ie(e){return e===null?"null":Array.isArray(e)?"an array":typeof e}function Ve(e){const t=[],r=[];for(const[o,n]of Object.entries(e)){if(typeof n=="string"){t.push({key:o,value:n});continue}if(typeof n=="number"||typeof n=="boolean"){t.push({key:o,value:String(n)});continue}if(_(n)){const i=["value","raw","computed","computedValue"].find(p=>typeof n[p]=="string");if(i){t.push({key:o,value:n[i]});continue}r.push({key:o,message:"nested object with no value/raw/computed field \u2014 skipped"});continue}r.push({key:o,message:`${ie(n)} is not a secret value \u2014 skipped`})}return{entries:t,problems:r}}function ae(e){let t;try{t=JSON.parse(e)}catch(p){throw new y(`Input is not valid JSON: ${p.message}`)}const{shape:r,doc:o}=se(t),{entries:n,problems:i}=Ve(o);return{entries:n,problems:i,shape:r}}function Ze(e){const t=e[0];for(let r=1;r<e.length;r++){if(t==='"'&&e[r]==="\\"){r++;continue}if(e[r]===t){if(t==="'"&&e[r+1]==="'"){r++;continue}return r}}return-1}function Xe(e){const t=[],r=[];return e.replace(/\r\n/g,`
13
13
  `).replace(/\r/g,`
14
14
  `).split(`
15
- `).forEach((n,i)=>{const h=i+1;if(n.trim()===""||n.trim().startsWith("#")||n.trim()==="---"||n.trim()==="...")return;if(/^\s/.test(n))throw new m(`${h}: this YAML is indented, so it is not flat key/value. Refusing rather than guessing \u2014 convert it to JSON and use --json.`);if(/^-\s/.test(n.trim())||n.trim()==="-")throw new m(`${h}: YAML lists are not supported. Use --json.`);if(/^[|>]/.test(n.trim()))throw new m(`${h}: YAML block scalars are not supported. Use --json.`);const a=/^([A-Za-z_][A-Za-z0-9_.-]*)\s*:\s?(.*)$/.exec(n);if(!a){o.push({line:h,message:"not a `key: value` line \u2014 skipped"});return}const c=a[1];let p=a[2]??"";if(p.trim()===""||p.trim()==="|"||p.trim()===">")throw new m(`${h}: "${c}" has no inline value, which in YAML means a nested block or null. Refusing rather than registering an empty fingerprint.`);const l=p.trim();if(l.startsWith('"')&&l.endsWith('"')&&l.length>1||l.startsWith("'")&&l.endsWith("'")&&l.length>1)p=l.slice(1,-1),l[0]==='"'&&(p=p.replace(/\\n/g,`
16
- `).replace(/\\t/g," ").replace(/\\(.)/g,"$1"));else{const d=l.search(/\s#/);p=(d===-1?l:l.slice(0,d)).trim()}t.push({key:c,value:p,line:h})}),{entries:t,problems:o}}const Y=12,ze=new Set(["changeme","change-me","change_me","replaceme","replace-me","your-secret-here","your_secret_here","yoursecrethere","development","production","staging","localhost","password","passw0rd","secret","topsecret","undefined","none","null","n/a","todo","tbd","example","test","dummy","placeholder"]);function se(e){if(e.length===0)return 0;const t=new Map;for(const r of e)t.set(r,(t.get(r)??0)+1);let o=0;for(const r of t.values()){const n=r/e.length;o-=n*Math.log2(n)}return o}function Ge(e){if(!/:\/\//.test(e))return null;let t;try{t=new URL(e)}catch{return null}return t.password?{ok:!0}:[...t.pathname.split("/"),...t.searchParams.values(),t.hash.replace(/^#/,"")].filter(Boolean).some(r=>r.length>=16&&se(r)>=2.5)?{ok:!0}:{ok:!1,reason:"URL with no embedded credential or token"}}function Ve(e,{minLength:t=Y}={}){if(e.length===0)return{ok:!1,reason:"empty value"};if(e.length<t)return{ok:!1,reason:`only ${e.length} chars (minimum ${t})`};if(/^\d+$/.test(e))return{ok:!1,reason:"all digits \u2014 port, id or timestamp"};if(/^(true|false|yes|no|on|off|null|nil|none|undefined|enabled|disabled)$/i.test(e))return{ok:!1,reason:"boolean or empty-ish flag"};if(/^v?\d+(\.\d+){1,3}([-+][0-9A-Za-z.-]+)?$/.test(e))return{ok:!1,reason:"version number"};if(ze.has(e.toLowerCase()))return{ok:!1,reason:"placeholder or environment name"};if(/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/.test(e))return{ok:!1,reason:"email address"};if(/^(\/[^\s]*|\.{1,2}\/[^\s]*|~\/[^\s]*|[A-Za-z]:[\\/][^\s]*)$/.test(e))return{ok:!1,reason:"filesystem path"};const o=Ge(e);if(o&&!o.ok)return{ok:!1,reason:o.reason};if(!o){const r=new Set(e).size;if(r<5)return{ok:!1,reason:`only ${r} distinct characters`};if(se(e)<2)return{ok:!1,reason:"very low character diversity"}}return{ok:!0}}async function Ze(){if(process.stdin.isTTY)throw new m("--stdin was passed but nothing is piped in.");const e=[];for await(const t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}function F(e,t){try{return me(e,"utf8")}catch(o){throw new m(`${t} ${e}: ${o.code==="ENOENT"?"no such file":o.message}`)}}function O(e){return`import:${e}`}function Xe(e){return String(e).replace(/^[./]+/,"").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"import"}function ie(e,t){return t.some(o=>o.includes("*")?new RegExp("^"+o.split("*").map(Qe).join(".*")+"$","i").test(e):e.toLowerCase()===o.toLowerCase())}const Qe=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function et({candidates:e,existing:t,source:o}){const r=O(o),n=new Map;for(const d of t)d.hmacHex&&n.set(d.hmacHex,d);const i=t.filter(d=>Array.isArray(d.tags)&&d.tags.includes(r)),h=new Map(i.map(d=>[d.label,d])),a=new Map;for(const d of t)i.includes(d)||a.has(d.label)||a.set(d.label,d);const c=[],p=new Set;for(const d of e){const{key:y,digests:u}=d;p.add(y);const $=h.get(y);if($){if($.hmacHex===u.digest&&tt($,u))c.push({key:y,action:"skip",reason:"already registered and unchanged",id:$.id,length:u.length});else{const b=n.get(u.digest);if(b&&b.id!==$.id)c.push({key:y,action:"conflict",reason:`new value is already registered as "${b.label}"`,id:$.id,length:u.length});else{const v=$.hmacHex===u.digest?"value unchanged; adding missing variants":"value changed";c.push({key:y,action:"rotate",reason:v,id:$.id,length:u.length})}}continue}const S=n.get(u.digest);if(S){c.push({key:y,action:"skip",reason:`already registered as "${S.label}"`,id:S.id,length:u.length});continue}const k=a.get(y);if(k){c.push({key:y,action:"conflict",reason:"a secret with this label exists outside this import source",id:k.id,length:u.length});continue}c.push({key:y,action:"create",reason:"new",length:u.length})}const l=i.filter(d=>!p.has(d.label)).map(d=>({label:d.label,id:d.id,status:d.status}));return{plan:c,missing:l}}function tt(e,t){return e.hmacHexStripped===t.hmacHexStripped&&e.hmacHexLower===t.hmacHexLower&&e.scanPrefilter===t.scanPrefilter}const ae=e=>e.replace(/\/+$/,"");async function H(e,t,o,r,n){let i;try{i=await fetch(`${ae(e)}${r}`,{method:o,headers:{Authorization:`Bearer ${t}`,...n?{"Content-Type":"application/json"}:{}},...n?{body:JSON.stringify(n)}:{}})}catch(c){throw new m(`Cannot reach ${ae(e)}: ${c.message}`)}const h=await i.text();let a=null;if(h)try{a=JSON.parse(h)}catch{a=null}return{status:i.status,ok:i.ok,data:a,text:h}}async function nt(e,t,o){const r=await H(e,t,"GET","/api/projects");if(!r.ok||!Array.isArray(r.data))throw new m(`GET /api/projects failed: ${r.status} ${String(r.text).slice(0,200)}`);const n=o.trim().toLowerCase(),i=r.data.filter(a=>a.id===o.trim()),h=i.length?i:r.data.filter(a=>String(a.name).toLowerCase()===n);if(h.length===0)throw new m(`No project named or numbered "${o}". Known: ${r.data.map(a=>a.name).join(", ")||"none"}.`);if(h.length>1)throw new m(`"${o}" matches ${h.length} projects. Pass the project id instead.`);if(h[0].status==="CLOSED")throw new m(`Project "${h[0].name}" is closed. Reopen it before enrolling into it.`);return h[0]}async function rt({plan:e,existing:t,serverUrl:o,token:r}){const n=e.filter(a=>a.action==="rotate"),i=a=>t.find(c=>c.id===a.id)?.projectId??null;if(!n.some(i))return;const h=await H(o,r,"GET","/api/projects");if(!(!h.ok||!Array.isArray(h.data)))for(const a of n){const c=i(a);if(!c)continue;const p=h.data.find(l=>l.id===c);p&&(p.usesOrgKey?a.sendProjectId=c:(a.action="conflict",a.reason=`lives in project "${p.name}", which has its own key; re-run with --project "${p.name}"`))}}async function ot(e,t,o=!1){const r=await H(e,t,"GET","/api/secrets");if(o&&(r.status===401||r.status===403))throw new m("This machine's Redaktyn session is no longer valid: the device was removed or its session ended. Ask your admin for a new invite link and run `redaktyn-connect` again.");if(r.status===401)throw new m("Server rejected the token (401). REDAKTYN_TOKEN must be a current OWNER or ADMIN login token.");if(r.status===403)throw new m("This token is not allowed to manage secrets (403). Importing needs an OWNER or ADMIN token.");if(!r.ok)throw new m(`GET /api/secrets failed: ${r.status} ${r.text.slice(0,200)}`);if(!Array.isArray(r.data))throw new m("GET /api/secrets did not return a list.");return r.data}function st(e){try{const t=e.split(".")[1];if(!t)return null;const o=t+"=".repeat((4-t.length%4)%4),r=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8");return JSON.parse(r)}catch{return null}}function it(e){if(!e)return null;if(e.type==="extension")return`REDAKTYN_TOKEN is an extension device token. Those can sync fingerprints but not register them.
15
+ `).forEach((n,i)=>{const p=i+1;if(n.trim()===""||n.trim().startsWith("#")||n.trim()==="---"||n.trim()==="...")return;if(/^\s/.test(n))throw new y(`${p}: this YAML is indented, so it is not flat key/value. Refusing rather than guessing \u2014 convert it to JSON and use --json.`);if(/^-\s/.test(n.trim())||n.trim()==="-")throw new y(`${p}: YAML lists are not supported. Use --json.`);if(/^[|>]/.test(n.trim()))throw new y(`${p}: YAML block scalars are not supported. Use --json.`);const l=/^([A-Za-z_][A-Za-z0-9_.-]*)\s*:\s?(.*)$/.exec(n);if(!l){r.push({line:p,message:"not a `key: value` line \u2014 skipped"});return}const d=l[1];let a=l[2]??"";if(a.trim()===""||a.trim()==="|"||a.trim()===">")throw new y(`${p}: "${d}" has no inline value, which in YAML means a nested block or null. Refusing rather than registering an empty fingerprint.`);const u=a.trim(),m=u[0]==='"'||u[0]==="'"?Ze(u):-1;if(m!==-1&&/^(\s+#.*)?$/.test(u.slice(m+1))){const $=u.slice(1,m);a=u[0]==='"'?$.replace(/\\(.)/g,(c,f)=>f==="n"?`
16
+ `:f==="t"?" ":f==="r"?"\r":f):$.replace(/''/g,"'")}else if(u.startsWith('"')&&u.endsWith('"')&&u.length>1||u.startsWith("'")&&u.endsWith("'")&&u.length>1)a=u.slice(1,-1),u[0]==='"'&&(a=a.replace(/\\n/g,`
17
+ `).replace(/\\t/g," ").replace(/\\(.)/g,"$1"));else{const $=u.search(/\s#/);a=($===-1?u:u.slice(0,$)).trim()}t.push({key:d,value:a,line:p})}),{entries:t,problems:r}}const q=12,Qe=new Set(["DOPPLER_PROJECT","DOPPLER_ENVIRONMENT","DOPPLER_CONFIG"]),et=new Set(["changeme","change-me","change_me","replaceme","replace-me","your-secret-here","your_secret_here","yoursecrethere","development","production","staging","localhost","password","passw0rd","secret","topsecret","undefined","none","null","n/a","todo","tbd","example","test","dummy","placeholder"]);function le(e){if(e.length===0)return 0;const t=new Map;for(const o of e)t.set(o,(t.get(o)??0)+1);let r=0;for(const o of t.values()){const n=o/e.length;r-=n*Math.log2(n)}return r}function tt(e){if(!/:\/\//.test(e))return null;let t;try{t=new URL(e)}catch{return null}return t.password?{ok:!0}:[...t.pathname.split("/"),...t.searchParams.values(),t.hash.replace(/^#/,"")].filter(Boolean).some(o=>o.length>=16&&le(o)>=2.5)?{ok:!0}:{ok:!1,reason:"URL with no embedded credential or token"}}function nt(e,{minLength:t=q}={}){if(e.length===0)return{ok:!1,reason:"empty value"};if(e.length<t)return{ok:!1,reason:`only ${e.length} chars (minimum ${t})`};if(/^\d+$/.test(e))return{ok:!1,reason:"all digits \u2014 port, id or timestamp"};if(/^(true|false|yes|no|on|off|null|nil|none|undefined|enabled|disabled)$/i.test(e))return{ok:!1,reason:"boolean or empty-ish flag"};if(/^v?\d+(\.\d+){1,3}([-+][0-9A-Za-z.-]+)?$/.test(e))return{ok:!1,reason:"version number"};if(et.has(e.toLowerCase()))return{ok:!1,reason:"placeholder or environment name"};if(/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/.test(e))return{ok:!1,reason:"email address"};if(/^(\/[^\s]*|\.{1,2}\/[^\s]*|~\/[^\s]*|[A-Za-z]:[\\/][^\s]*)$/.test(e))return{ok:!1,reason:"filesystem path"};const r=tt(e);if(r&&!r.ok)return{ok:!1,reason:r.reason};if(!r){const o=new Set(e).size;if(o<5)return{ok:!1,reason:`only ${o} distinct characters`};if(le(e)<2)return{ok:!1,reason:"very low character diversity"}}return{ok:!0}}async function ot(){if(process.stdin.isTTY)throw new y("--stdin was passed but nothing is piped in.");const e=[];for await(const t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}function F(e,t){try{return ke(e,"utf8")}catch(r){throw new y(`${t} ${e}: ${r.code==="ENOENT"?"no such file":r.message}`)}}function O(e){return`import:${e}`}function rt(e){return String(e).replace(/^[./]+/,"").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"import"}function ce(e,t){return t.some(r=>r.includes("*")?new RegExp("^"+r.split("*").map(st).join(".*")+"$","i").test(e):e.toLowerCase()===r.toLowerCase())}const st=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function it({candidates:e,existing:t,source:r}){const o=O(r),n=new Map;for(const c of t)c.hmacHex&&n.set(c.hmacHex,c);const i=t.filter(c=>Array.isArray(c.tags)&&c.tags.includes(o)),p=new Map(i.map(c=>[c.label,c])),l=new Map;for(const c of t)i.includes(c)||l.has(c.label)||l.set(c.label,c);const d=[],a=new Set,u=new Map;for(const c of e){const{key:f,digests:k}=c;a.add(f);const v=u.get(k.digest);if(v){d.push({key:f,action:p.has(f)?"conflict":"skip",reason:`same value as "${v}" in this import`,...p.has(f)?{id:p.get(f).id}:{},length:k.length});continue}const b=d.length;m(c);const S=d[b];S&&(S.action==="create"||S.action==="rotate")&&u.set(k.digest,f)}function m({key:c,digests:f}){const k=p.get(c);if(k){if(k.hmacHex===f.digest&&at(k,f))d.push({key:c,action:"skip",reason:"already registered and unchanged",id:k.id,length:f.length});else{const S=n.get(f.digest);if(S&&S.id!==k.id)d.push({key:c,action:"conflict",reason:`new value is already registered as "${S.label}"`,id:k.id,length:f.length});else{const j=k.hmacHex===f.digest?"value unchanged; adding missing variants":"value changed";d.push({key:c,action:"rotate",reason:j,id:k.id,length:f.length})}}return}const v=n.get(f.digest);if(v){d.push({key:c,action:"skip",reason:`already registered as "${v.label}"`,id:v.id,length:f.length});return}const b=l.get(c);if(b){d.push({key:c,action:"conflict",reason:"a secret with this label exists outside this import source",id:b.id,length:f.length});return}d.push({key:c,action:"create",reason:"new",length:f.length})}const $=i.filter(c=>!a.has(c.label)).map(c=>({label:c.label,id:c.id,status:c.status}));return{plan:d,missing:$}}function at(e,t){return e.hmacHexStripped===t.hmacHexStripped&&e.hmacHexLower===t.hmacHexLower&&e.scanPrefilter===t.scanPrefilter}const de=e=>e.replace(/\/+$/,"");async function H(e,t,r,o,n){let i;try{i=await fetch(`${de(e)}${o}`,{method:r,headers:{Authorization:`Bearer ${t}`,...n?{"Content-Type":"application/json"}:{}},...n?{body:JSON.stringify(n)}:{}})}catch(d){throw new y(`Cannot reach ${de(e)}: ${d.message}`)}const p=await i.text();let l=null;if(p)try{l=JSON.parse(p)}catch{l=null}return{status:i.status,ok:i.ok,data:l,text:p}}async function lt(e,t,r){const o=await H(e,t,"GET","/api/projects");if(!o.ok||!Array.isArray(o.data))throw new y(`GET /api/projects failed: ${o.status} ${String(o.text).slice(0,200)}`);const n=r.trim().toLowerCase(),i=o.data.filter(l=>l.id===r.trim()),p=i.length?i:o.data.filter(l=>String(l.name).toLowerCase()===n);if(p.length===0)throw new y(`No project named or numbered "${r}". Known: ${o.data.map(l=>l.name).join(", ")||"none"}.`);if(p.length>1)throw new y(`"${r}" matches ${p.length} projects. Pass the project id instead.`);if(p[0].status==="CLOSED")throw new y(`Project "${p[0].name}" is closed. Reopen it before enrolling into it.`);return p[0]}async function ct({plan:e,existing:t,serverUrl:r,token:o}){const n=e.filter(l=>l.action==="rotate"),i=l=>t.find(d=>d.id===l.id)?.projectId??null;if(!n.some(i))return;const p=await H(r,o,"GET","/api/projects");if(!(!p.ok||!Array.isArray(p.data)))for(const l of n){const d=i(l);if(!d)continue;const a=p.data.find(u=>u.id===d);a&&(a.usesOrgKey?l.sendProjectId=d:(l.action="conflict",l.reason=`lives in project "${a.name}", which has its own key; re-run with --project "${a.name}"`))}}async function dt(e,t,r=!1){const o=await H(e,t,"GET","/api/secrets");if(r&&(o.status===401||o.status===403))throw new y("This machine's Redaktyn session is no longer valid: the device was removed or its session ended. Ask your admin for a new invite link and run `redaktyn-connect` again.");if(o.status===401)throw new y("Server rejected the token (401). REDAKTYN_TOKEN must be a current OWNER or ADMIN login token.");if(o.status===403)throw new y("This token is not allowed to manage secrets (403). Importing needs an OWNER or ADMIN token.");if(!o.ok)throw new y(`GET /api/secrets failed: ${o.status} ${o.text.slice(0,200)}`);if(!Array.isArray(o.data))throw new y("GET /api/secrets did not return a list.");return o.data}function ut(e){try{const t=e.split(".")[1];if(!t)return null;const r=t+"=".repeat((4-t.length%4)%4),o=Buffer.from(r.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8");return JSON.parse(o)}catch{return null}}function pt(e){if(!e)return null;if(e.type==="extension")return`REDAKTYN_TOKEN is an extension device token. Those can sync fingerprints but not register them.
17
18
  Get an OWNER or ADMIN login token instead:
18
19
  curl -s -X POST "$REDAKTYN_SERVER_URL/api/auth/login" \\
19
20
  -H 'Content-Type: application/json' \\
20
- -d '{"email":"you@example.com","password":"\u2026"}' | jq -r .token`;const t=e.role;return typeof t=="string"&&!["OWNER","ADMIN"].includes(t.toUpperCase())?`This token has role ${t}. Importing needs OWNER or ADMIN.`:null}const at={create:{label:"CREATE",color:s.green},rotate:{label:"ROTATE",color:s.yellow},skip:{label:"skip",color:s.gray},conflict:{label:"CONFLICT",color:s.red},rejected:{label:"rejected",color:s.gray}};function le(e,t){return e.length<=t?e.padEnd(t):e.slice(0,t-1)+"\u2026"}function lt({rows:e,missing:t,source:o,dryRun:r,budget:n,projectName:i=null}){const h=Math.min(process.stdout.columns||80,100),a=34;console.log(""),console.log(`${s.bold}Redaktyn import${s.reset} ${s.dim}\xB7 source tag ${O(o)}${i?` \xB7 project ${i}`:""}${s.reset}`),console.log(s.dim+"\u2500".repeat(h)+s.reset),console.log(`${s.dim}${"KEY".padEnd(a)} ${"LEN".padStart(5)} ${"ACTION".padEnd(9)} WHY${s.reset}`);for(const l of e){const d=at[l.action]??{label:l.action,color:""};console.log(`${le(l.key,a)} ${String(l.length??"-").padStart(5)} ${d.color}${d.label.padEnd(9)}${s.reset} ${s.dim}${l.reason??""}${s.reset}`)}console.log(s.dim+"\u2500".repeat(h)+s.reset);const c=M(e),p=[c.create?`${s.green}${c.create} to create${s.reset}`:null,c.rotate?`${s.yellow}${c.rotate} to rotate${s.reset}`:null,c.skip?`${c.skip} unchanged`:null,c.rejected?`${c.rejected} filtered out`:null,c.conflict?`${s.red}${c.conflict} conflicting${s.reset}`:null].filter(Boolean);if(console.log(" "+(p.length?p.join(s.dim+" \xB7 "+s.reset):"nothing to do")),t.length>0){console.log(""),console.log(`${s.yellow}${t.length} secret(s) tagged ${O(o)} are not in this input.${s.reset}`),console.log(`${s.dim} Reported only \u2014 import never removes anything. Retire them in the dashboard if they are gone.${s.reset}`);for(const l of t.slice(0,20))console.log(`${s.dim} \xB7 ${l.label}${s.reset}`);t.length>20&&console.log(`${s.dim} \xB7 \u2026 ${t.length-20} more${s.reset}`)}q(n),r&&(console.log(""),console.log(`${s.bold}Dry run \u2014 nothing was sent.${s.reset} ${s.dim}Re-run with --apply to register.${s.reset}`)),console.log("")}const ct={create:{label:"CREATE",paint:g.green},rotate:{label:"ROTATE",paint:g.amber},skip:{label:"skip",paint:g.gray},conflict:{label:"CONFLICT",paint:g.red},rejected:{label:"rejected",paint:g.gray}};function dt({rows:e,missing:t,source:o,dryRun:r,budget:n,projectName:i=null,byKey:h}){const a=Math.min(process.stderr.columns||90,100),c=30;w(""),w(` ${g.bold("Plan")} ${g.dim(`source tag ${O(o)}${i?` \xB7 project ${i}`:""}`)}`),w(` ${g.gray("\u2500".repeat(a-4))}`),w(` ${g.gray(`${"KEY".padEnd(c)} ${"LEN".padStart(4)} ${"ACTION".padEnd(8)} ${"FINGERPRINT".padEnd(11)} WHY`)}`);for(const d of e){const y=ct[d.action]??{label:d.action,paint:S=>S},u=h.get(d.key),$=u&&(d.action==="create"||d.action==="rotate")?de(u.digests.digest):"";w(` ${le(d.key,c)} ${String(d.length??"-").padStart(4)} ${y.paint(y.label.padEnd(8))} ${g.amber($.padEnd(11))} ${g.dim(d.reason??"")}`)}w(` ${g.gray("\u2500".repeat(a-4))}`);const p=M(e),l=[p.create?g.green(`${p.create} to create`):null,p.rotate?g.amber(`${p.rotate} to rotate`):null,p.skip?`${p.skip} unchanged`:null,p.rejected?`${p.rejected} filtered out`:null,p.conflict?g.red(`${p.conflict} conflicting`):null].filter(Boolean);if(w(` ${l.length?l.join(g.dim(" \xB7 ")):"nothing to do"}`),t.length>0){w(""),w(` ${g.amber("\u25B2")} ${t.length} secret(s) tagged ${O(o)} are not in this input. ${g.dim("Reported only: import never removes anything.")}`);for(const d of t.slice(0,10))w(` ${g.dim(`\xB7 ${d.label}`)}`);t.length>10&&w(` ${g.dim(`\xB7 \u2026 ${t.length-10} more`)}`)}q(n)}function q(e){if(!e||e.ceiling===1/0)return;const t=e.ceiling.toLocaleString("en-US"),o=r=>{if(!(e.legacySecrets>0)||!(e.ceilingIfReenrolled>e.ceiling))return;const n=e.legacySecrets;console.log(`${r} ${n} enrolled secret${n===1?" has":"s have"} no scan prefilter (enrolled before 2026-10-07 or by an older client),${s.reset}`),console.log(`${r} so every paste is checked against ${n===1?"it":"them"} the slow way. They are outside this import; re-enrolling ${n===1?"it":"them"}${s.reset}`),console.log(`${r} from the dashboard, or importing ${n===1?"it":"them"}, raises this to ~${e.ceilingIfReenrolled.toLocaleString("en-US")} chars.${s.reset}`)};if(e.ceiling<Pe){console.log(""),console.log(`${s.red}${s.bold}Scan budget: pastes over ~${t} characters will be refused${s.reset}`),console.log(` ${e.windowLengths} distinct window lengths after this import. Detection slides one pass per`),console.log(` length, so past that size the extension ${s.bold}refuses to scan${s.reset} rather than hang \u2014`),console.log(" which is a hard block in sensitive contexts. A paste at the ceiling takes up to ~8s."),o(""),console.log(`${s.dim} Register the high-value secrets only, or split them across workspaces.${s.reset}`);return}if(e.ceiling<Z){console.log(""),console.log(`${s.yellow}Scan budget:${s.reset} ${e.windowLengths} window lengths after this import; pastes above ~${t} chars are refused.`),o("");return}console.log(e.atCharacterCap?`${s.dim} Scan budget: every paste up to the extension's ${t}-char hard limit is scanned.${s.reset}`:`${s.dim} Scan budget: ${e.windowLengths} window lengths, pastes up to ~${t} chars.${s.reset}`),o(s.dim)}function M(e){const t={create:0,rotate:0,skip:0,conflict:0,rejected:0};for(const o of e)t[o.action]=(t[o.action]??0)+1;return t}async function pt(e){if(!process.stdin.isTTY)throw new m("--apply needs a terminal to confirm on, or --yes to skip the prompt.");const t=$e.createInterface({input:process.stdin,output:process.stdout});try{const o=await new Promise(r=>t.question(`${e} `,r));return/^y(es)?$/i.test(o.trim())}finally{t.close()}}function ht(e,t){return je({label:e,hmacHex:t.digest,length:t.length,hmacHexStripped:t.hmacHexStripped,lengthStripped:t.lengthStripped,hmacHexLower:t.hmacHexLower,lengthLower:t.lengthLower,scanPrefilter:t.scanPrefilter})}function ce(e,t,{withPrefilter:o,projectId:r,tag:n}){const{scanPrefilter:i,...h}=t.digests,a=ht(e.key,o?{...h,scanPrefilter:i}:h),{label:c,...p}=a,l=e.sendProjectId??r,d=l?{projectId:l}:{};return e.action==="create"?{method:"POST",path:"/api/secrets",body:{...a,...d,tags:[n]}}:{method:"PUT",path:`/api/secrets/${e.id}/digest`,body:{...p,...d}}}const de=e=>`${e.slice(0,8)}\u2026`;function ut(e,t){const o=[];let r="";for(const n of e.split(" "))r&&(r+" "+n).length>t?(o.push(r),r=n):r=r?`${r} ${n}`:n;return r&&o.push(r),o}async function ft({rows:e,byKey:t,serverUrl:o,token:r,source:n,projectId:i=null}){const h=[],a=O(n);let c=!0,p=0,l=0;const d=e.filter(u=>u.action==="create"||u.action==="rotate").length;let y=0;for(const u of e){if(u.action!=="create"&&u.action!=="rotate")continue;const $=t.get(u.key),S=E=>{const N=ce(u,$,{withPrefilter:E,projectId:i,tag:a});return p+=Buffer.byteLength(JSON.stringify(N.body)),l+=1,H(o,r,N.method,N.path,N.body)};let k=await S(c);c&&$.digests.scanPrefilter&&Ke(k)&&(c=!1,pe(),k=await S(!1)),y+=1;const b=j?` ${g.dim(de($.digests.digest))}`:"";if(k.ok){h.push({key:u.key,action:u.action,ok:!0}),console.log(` ${s.green}\u2713${s.reset} ${u.action==="create"?"created":"rotated"} ${u.key}${b}`),j&&w(` ${Oe(y,d)}`);continue}const v=$t(k);h.push({key:u.key,action:u.action,ok:!1,status:k.status,reason:v}),console.log(` ${s.red}\u2717${s.reset} ${u.key}: ${v}`)}return h.sentBytes=p,h.requests=l,h}const gt=e=>e.replace(/[0-9a-f]{40,}/g,t=>`${t.slice(0,12)}\u2026(${t.length} hex)`);function mt({writes:e,byKey:t,serverUrl:o,projectId:r,source:n,dryRun:i,showRequest:h,viaSession:a=!1}){if(e.length===0)return;const c=O(n),p=e.map(u=>{const $=t.get(u.key);return ce(u,$,{withPrefilter:!!$.digests.scanPrefilter,projectId:r,tag:c})}),l=p.reduce((u,$)=>u+Buffer.byteLength(JSON.stringify($.body)),0),d=[...new Set(p.flatMap(u=>Object.keys(u.body)))];let y=o;try{y=new URL(o).host}catch{}if(j&&(w(""),B(i?"What WOULD leave this machine":"What leaves this machine",["",...J([["Sent to",`${y}: ${p.length} request${p.length===1?"":"s"}, ${z(l)} in total`],["Each request","label, 3 fingerprints, 3 lengths"],...ut(d.join(", "),44).map(u=>["",g.dim(u)]),["Secret values",g.green("0 B")]],{indent:0,labelWidth:18}),"",g.dim("Never leaves this machine:"),...J([["The values",`${e.length} read into memory, fingerprinted, then dropped`],...a?[["Your passphrase","not used here. This machine holds the project's key from its invite"],["The project key","in the session file only you can read; never sent to the server"]]:[["Your passphrase","asked for, used to derive the key, then forgotten"],["The workspace key","derived here, held in memory, never written or sent"]]],{indent:0,labelWidth:18}),""],{tone:"green",width:100})),h){const u=p[0];w(""),w(` ${g.dim(`The first request, exactly as it is built (${u.method} ${u.path}), digests shortened:`)}`),w(gt(JSON.stringify(u.body,null,2)).split(`
21
- `).map($=>` ${$}`).join(`
22
- `))}else j&&w(` ${g.dim("See the exact request body: --show-request")}`)}async function yt({label:e,cand:t,viaSession:o=!1}){const r=t.digests.length;w(""),w(` ${g.bold(e)} ${g.gray("\u2022".repeat(Math.min(r,22)))} ${g.dim(`${r} characters, read here and never sent`)}`),w(` ${g.gray(C.bar)} ${g.dim("normalise ")} trim, unicode NFC, strip invisible characters`),w(o?` ${g.gray(C.bar)} ${g.dim("project key ")} the key from your invite, already on this machine (no passphrase needed)`:` ${g.gray(C.bar)} ${g.dim("derive key ")} PBKDF2-SHA256, 600,000 rounds, from your passphrase, on this machine`),await Ie(` ${g.gray(C.down)} ${g.dim("fingerprint ")} `,t.digests.digest,{show:16}),w(` ${g.dim("HMAC-SHA256, plus whitespace-stripped and lower-case variants, so a disguised paste still matches")}`),w("")}function pe(){console.log(`${s.yellow}!${s.reset} This server does not store scan prefilters yet, so secrets are registered without one.`),console.log(`${s.dim} They are protected exactly the same, but every paste checks them the slow way. Re-run this${s.reset}`),console.log(`${s.dim} import once the server is updated; it adds the prefilter to each of them.${s.reset}`)}function $t(e){if(e.status===409&&e.data?.code==="PROJECT_MISMATCH"&&typeof e.data.error=="string")return e.data.error;if(e.status===409)return"another secret in this workspace already has this fingerprint";if(e.status===403)return"token is not OWNER or ADMIN";if(e.status===401)return"token expired or invalid";if(e.status===404)return"secret no longer exists \u2014 re-run to re-plan";const t=e.data&&typeof e.data.error=="string"?e.data.error:e.text.slice(0,160);return`${e.status} ${t}`}function wt(){console.log(`
21
+ -d '{"email":"you@example.com","password":"\u2026"}' | jq -r .token`;const t=e.role;return typeof t=="string"&&!["OWNER","ADMIN"].includes(t.toUpperCase())?`This token has role ${t}. Importing needs OWNER or ADMIN.`:null}const ht={create:{label:"CREATE",color:s.green},rotate:{label:"ROTATE",color:s.yellow},skip:{label:"skip",color:s.gray},conflict:{label:"CONFLICT",color:s.red},rejected:{label:"rejected",color:s.gray}};function ue(e,t){return e.length<=t?e.padEnd(t):e.slice(0,t-1)+"\u2026"}function ft({rows:e,missing:t,source:r,dryRun:o,budget:n,projectName:i=null}){const p=Math.min(process.stdout.columns||80,100),l=34;console.log(""),console.log(`${s.bold}Redaktyn import${s.reset} ${s.dim}\xB7 source tag ${O(r)}${i?` \xB7 project ${i}`:""}${s.reset}`),console.log(s.dim+"\u2500".repeat(p)+s.reset),console.log(`${s.dim}${"KEY".padEnd(l)} ${"LEN".padStart(5)} ${"ACTION".padEnd(9)} WHY${s.reset}`);for(const u of e){const m=ht[u.action]??{label:u.action,color:""};console.log(`${ue(u.key,l)} ${String(u.length??"-").padStart(5)} ${m.color}${m.label.padEnd(9)}${s.reset} ${s.dim}${u.reason??""}${s.reset}`)}console.log(s.dim+"\u2500".repeat(p)+s.reset);const d=W(e),a=[d.create?`${s.green}${d.create} to create${s.reset}`:null,d.rotate?`${s.yellow}${d.rotate} to rotate${s.reset}`:null,d.skip?`${d.skip} unchanged`:null,d.rejected?`${d.rejected} filtered out`:null,d.conflict?`${s.red}${d.conflict} conflicting${s.reset}`:null].filter(Boolean);if(console.log(" "+(a.length?a.join(s.dim+" \xB7 "+s.reset):"nothing to do")),t.length>0){console.log(""),console.log(`${s.yellow}${t.length} secret(s) tagged ${O(r)} are not in this input.${s.reset}`),console.log(`${s.dim} Reported only \u2014 import never removes anything. Retire them in the dashboard if they are gone.${s.reset}`);for(const u of t.slice(0,20))console.log(`${s.dim} \xB7 ${u.label}${s.reset}`);t.length>20&&console.log(`${s.dim} \xB7 \u2026 ${t.length-20} more${s.reset}`)}B(n),o&&(console.log(""),console.log(`${s.bold}Dry run \u2014 nothing was sent.${s.reset} ${s.dim}Re-run with --apply to register.${s.reset}`)),console.log("")}const gt={create:{label:"CREATE",paint:g.green},rotate:{label:"ROTATE",paint:g.amber},skip:{label:"skip",paint:g.gray},conflict:{label:"CONFLICT",paint:g.red},rejected:{label:"rejected",paint:g.gray}};function mt({rows:e,missing:t,source:r,dryRun:o,budget:n,projectName:i=null,byKey:p}){const l=Math.min(process.stderr.columns||90,100),d=30;w(""),w(` ${g.bold("Plan")} ${g.dim(`source tag ${O(r)}${i?` \xB7 project ${i}`:""}`)}`),w(` ${g.gray("\u2500".repeat(l-4))}`),w(` ${g.gray(`${"KEY".padEnd(d)} ${"LEN".padStart(4)} ${"ACTION".padEnd(8)} ${"FINGERPRINT".padEnd(11)} WHY`)}`);for(const m of e){const $=gt[m.action]??{label:m.action,paint:k=>k},c=p.get(m.key),f=c&&(m.action==="create"||m.action==="rotate")?he(c.digests.digest):"";w(` ${ue(m.key,d)} ${String(m.length??"-").padStart(4)} ${$.paint($.label.padEnd(8))} ${g.amber(f.padEnd(11))} ${g.dim(m.reason??"")}`)}w(` ${g.gray("\u2500".repeat(l-4))}`);const a=W(e),u=[a.create?g.green(`${a.create} to create`):null,a.rotate?g.amber(`${a.rotate} to rotate`):null,a.skip?`${a.skip} unchanged`:null,a.rejected?`${a.rejected} filtered out`:null,a.conflict?g.red(`${a.conflict} conflicting`):null].filter(Boolean);if(w(` ${u.length?u.join(g.dim(" \xB7 ")):"nothing to do"}`),t.length>0){w(""),w(` ${g.amber("\u25B2")} ${t.length} secret(s) tagged ${O(r)} are not in this input. ${g.dim("Reported only: import never removes anything.")}`);for(const m of t.slice(0,10))w(` ${g.dim(`\xB7 ${m.label}`)}`);t.length>10&&w(` ${g.dim(`\xB7 \u2026 ${t.length-10} more`)}`)}B(n)}function B(e){if(!e||e.ceiling===1/0)return;const t=e.ceiling.toLocaleString("en-US"),r=o=>{if(!(e.legacySecrets>0)||!(e.ceilingIfReenrolled>e.ceiling))return;const n=e.legacySecrets;console.log(`${o} ${n} enrolled secret${n===1?" has":"s have"} no scan prefilter (enrolled before 2026-10-07 or by an older client),${s.reset}`),console.log(`${o} so every paste is checked against ${n===1?"it":"them"} the slow way. They are outside this import; re-enrolling ${n===1?"it":"them"}${s.reset}`),console.log(`${o} from the dashboard, or importing ${n===1?"it":"them"}, raises this to ~${e.ceilingIfReenrolled.toLocaleString("en-US")} chars.${s.reset}`)};if(e.ceiling<He){console.log(""),console.log(`${s.red}${s.bold}Scan budget: pastes over ~${t} characters will be refused${s.reset}`),console.log(` ${e.windowLengths} distinct window lengths after this import. Detection slides one pass per`),console.log(` length, so past that size the extension ${s.bold}refuses to scan${s.reset} rather than hang \u2014`),console.log(" which is a hard block in sensitive contexts. A paste at the ceiling takes up to ~8s."),r(""),console.log(`${s.dim} Register the high-value secrets only, or split them across workspaces.${s.reset}`);return}if(e.ceiling<ee){console.log(""),console.log(`${s.yellow}Scan budget:${s.reset} ${e.windowLengths} window lengths after this import; pastes above ~${t} chars are refused.`),r("");return}console.log(e.atCharacterCap?`${s.dim} Scan budget: every paste up to the extension's ${t}-char hard limit is scanned.${s.reset}`:`${s.dim} Scan budget: ${e.windowLengths} window lengths, pastes up to ~${t} chars.${s.reset}`),r(s.dim)}function W(e){const t={create:0,rotate:0,skip:0,conflict:0,rejected:0};for(const r of e)t[r.action]=(t[r.action]??0)+1;return t}async function yt(e){if(!process.stdin.isTTY)throw new y("--apply needs a terminal to confirm on, or --yes to skip the prompt.");const t=ve.createInterface({input:process.stdin,output:process.stdout});try{const r=await new Promise(o=>t.question(`${e} `,o));return/^y(es)?$/i.test(r.trim())}finally{t.close()}}function $t(e,t){return Ne({label:e,hmacHex:t.digest,length:t.length,hmacHexStripped:t.hmacHexStripped,lengthStripped:t.lengthStripped,hmacHexLower:t.hmacHexLower,lengthLower:t.lengthLower,scanPrefilter:t.scanPrefilter})}function pe(e,t,{withPrefilter:r,projectId:o,tag:n}){const{scanPrefilter:i,...p}=t.digests,l=$t(e.key,r?{...p,scanPrefilter:i}:p),{label:d,...a}=l,u=e.sendProjectId??o,m=u?{projectId:u}:{};return e.action==="create"?{method:"POST",path:"/api/secrets",body:{...l,...m,tags:[n]}}:{method:"PUT",path:`/api/secrets/${e.id}/digest`,body:{...a,...m}}}const he=e=>`${e.slice(0,8)}\u2026`;function wt(e,t){const r=[];let o="";for(const n of e.split(" "))o&&(o+" "+n).length>t?(r.push(o),o=n):o=o?`${o} ${n}`:n;return o&&r.push(o),r}async function kt({rows:e,byKey:t,serverUrl:r,token:o,source:n,projectId:i=null}){const p=[],l=O(n);let d=!0,a=0,u=0;const m=e.filter(c=>c.action==="create"||c.action==="rotate").length;let $=0;for(const c of e){if(c.action!=="create"&&c.action!=="rotate")continue;const f=t.get(c.key),k=j=>{const x=pe(c,f,{withPrefilter:j,projectId:i,tag:l});return a+=Buffer.byteLength(JSON.stringify(x.body)),u+=1,H(r,o,x.method,x.path,x.body)};let v=await k(d);d&&f.digests.scanPrefilter&&Fe(v)&&(d=!1,fe(),v=await k(!1)),$+=1;const b=E?` ${g.dim(he(f.digests.digest))}`:"";if(v.ok){p.push({key:c.key,action:c.action,ok:!0}),console.log(` ${s.green}\u2713${s.reset} ${c.action==="create"?"created":"rotated"} ${c.key}${b}`),E&&w(` ${_e($,m)}`);continue}const S=jt(v);p.push({key:c.key,action:c.action,ok:!1,status:v.status,reason:S}),console.log(` ${s.red}\u2717${s.reset} ${c.key}: ${S}`)}return p.sentBytes=a,p.requests=u,p}const bt=e=>e.replace(/[0-9a-f]{40,}/g,t=>`${t.slice(0,12)}\u2026(${t.length} hex)`);function vt({writes:e,byKey:t,serverUrl:r,projectId:o,source:n,dryRun:i,showRequest:p,viaSession:l=!1}){if(e.length===0)return;const d=O(n),a=e.map(c=>{const f=t.get(c.key);return pe(c,f,{withPrefilter:!!f.digests.scanPrefilter,projectId:o,tag:d})}),u=a.reduce((c,f)=>c+Buffer.byteLength(JSON.stringify(f.body)),0),m=[...new Set(a.flatMap(c=>Object.keys(c.body)))];let $=r;try{$=new URL(r).host}catch{}if(E&&(w(""),z(i?"What WOULD leave this machine":"What leaves this machine",["",...J([["Sent to",`${$}: ${a.length} request${a.length===1?"":"s"}, ${V(u)} in total`],["Each request","label, 3 fingerprints, 3 lengths"],...wt(m.join(", "),44).map(c=>["",g.dim(c)]),["Secret values",g.green("0 B")]],{indent:0,labelWidth:18}),"",g.dim("Never leaves this machine:"),...J([["The values",`${e.length} read into memory, fingerprinted, then dropped`],...l?[["Your passphrase","not used here. This machine holds the project's key from its invite"],["The project key","in the session file only you can read; never sent to the server"]]:[["Your passphrase","asked for, used to derive the key, then forgotten"],["The workspace key","derived here, held in memory, never written or sent"]]],{indent:0,labelWidth:18}),""],{tone:"green",width:100})),p){const c=a[0];w(""),w(` ${g.dim(`The first request, exactly as it is built (${c.method} ${c.path}), digests shortened:`)}`),w(bt(JSON.stringify(c.body,null,2)).split(`
22
+ `).map(f=>` ${f}`).join(`
23
+ `))}else E&&w(` ${g.dim("See the exact request body: --show-request")}`)}async function St({label:e,cand:t,viaSession:r=!1}){const o=t.digests.length;w(""),w(` ${g.bold(e)} ${g.gray("\u2022".repeat(Math.min(o,22)))} ${g.dim(`${o} characters, read here and never sent`)}`),w(` ${g.gray(D.bar)} ${g.dim("normalise ")} trim, unicode NFC, strip invisible characters`),w(r?` ${g.gray(D.bar)} ${g.dim("project key ")} the key from your invite, already on this machine (no passphrase needed)`:` ${g.gray(D.bar)} ${g.dim("derive key ")} PBKDF2-SHA256, 600,000 rounds, from your passphrase, on this machine`),await Pe(` ${g.gray(D.down)} ${g.dim("fingerprint ")} `,t.digests.digest,{show:16}),w(` ${g.dim("HMAC-SHA256, plus whitespace-stripped and lower-case variants, so a disguised paste still matches")}`),w("")}function fe(){console.log(`${s.yellow}!${s.reset} This server does not store scan prefilters yet, so secrets are registered without one.`),console.log(`${s.dim} They are protected exactly the same, but every paste checks them the slow way. Re-run this${s.reset}`),console.log(`${s.dim} import once the server is updated; it adds the prefilter to each of them.${s.reset}`)}function jt(e){if(e.status===409&&e.data?.code==="PROJECT_MISMATCH"&&typeof e.data.error=="string")return e.data.error;if(e.status===409)return"another secret in this workspace already has this fingerprint";if(e.status===403)return"token is not OWNER or ADMIN";if(e.status===401)return"token expired or invalid";if(e.status===404)return"secret no longer exists \u2014 re-run to re-plan";const t=e.data&&typeof e.data.error=="string"?e.data.error:e.text.slice(0,160);return`${e.status} ${t}`}function Rt(){console.log(`
23
24
  ${s.bold}redaktyn-import${s.reset} \u2014 register fingerprints in bulk from files or any vault CLI
24
25
 
25
26
  ${s.bold}Digests are computed on this machine.${s.reset} Values are never sent, never
@@ -43,7 +44,7 @@ ${s.bold}Options${s.reset}
43
44
  (default: input file name, or "stdin")
44
45
  --apply Actually register. Without it this is a dry run.
45
46
  --yes Skip the confirmation prompt (for CI)
46
- --min-length <n> Minimum value length to accept (default ${Y})
47
+ --min-length <n> Minimum value length to accept (default ${q})
47
48
  --allow-weak Register values the junk filter rejected
48
49
  --only <key|glob> Only these keys (repeatable)
49
50
  --exclude <key|glob> Skip these keys (repeatable)
@@ -66,4 +67,4 @@ ${s.bold}Exit codes${s.reset}
66
67
  0 plan printed, or every write succeeded
67
68
  1 one or more writes failed
68
69
  2 usage, auth or parse error
69
- `)}async function kt(e){const t=[e.env&&"env",e.jsonFile&&"json",e.yaml&&"yaml",e.stdin&&"stdin"].filter(Boolean);if(t.length===0)throw new m("Nothing to import. Pass one of --env, --json, --yaml or --stdin (see --help).");if(t.length>1)throw new m(`Pick one input mode, got: ${t.map(i=>"--"+i).join(", ")}`);const o=t[0];if(o==="env")return{...Fe(F(e.env,"--env")),mode:o,defaultSource:K(e.env)};if(o==="json")return{...oe(F(e.jsonFile,"--json")),mode:o,defaultSource:K(e.jsonFile)};if(o==="yaml")return{...Be(F(e.yaml,"--yaml")),mode:o,defaultSource:K(e.yaml)};const r=await Ze();if(r.trim()==="")throw new m("Nothing arrived on stdin.");return{...oe(r),mode:o,defaultSource:"stdin"}}async function vt(e){const t=process.env.REDAKTYN_TOKEN||process.env.REDAKTYN_JWT;let o=null;if(!t){const l=U();if(l)try{o=await Re(l)}catch(d){throw new m(d.message)}}const r=e.server||!t&&o?.serverUrl||Ne(),n=t||o?.token;if(!n)throw new m("Run `redaktyn-login` to sign in as an OWNER or ADMIN (or set REDAKTYN_TOKEN for a script).");const i=st(n),h=it(i);if(h)throw new m(h);const a=e.orgId||i?.orgId||i?.org_id||process.env.REDAKTYN_ORG_ID;if(!a)throw new m("Could not determine the org id from the token. Pass --org-id.");const c=e.orgId||process.env.REDAKTYN_ORG_ID;if(c&&i?.orgId&&c!==i.orgId)throw new m("The org id given does not match the token's org id.");let p;try{p=await xe({server:r,token:n,orgId:a,who:o?`Signed in as ${o.email}${o.orgName?` (${o.orgName})`:""}.`:null,label:"Org passphrase",record:!!e.apply})}catch(l){throw new m(l.message)}return{serverUrl:r,token:n,orgId:a,passphrase:p}}async function bt(e){const o=process.env.REDAKTYN_TOKEN||process.env.REDAKTYN_JWT||U()?null:Ee();if(o){let l;try{l=await Ae(o)}catch(d){throw new m(d.message)}if(e.project){const d=e.project.trim().toLowerCase();if(d!==String(l.projectId).toLowerCase()&&d!==String(l.projectName||"").toLowerCase())throw new m(`This machine is connected to project "${l.projectName??l.projectId}" only, not "${e.project}". Drop --project, or ask for an invite to the other project.`)}if(!l.projectId)throw new m("This session is not tied to a project. Ask for a new invite link.");if(e.apply&&!l.canEnrol)throw new m("This invite lets you scan but not enrol secrets. Ask your admin for a link made with: redaktyn-invite --can-enrol");return{serverUrl:e.server||l.serverUrl,token:l.token,key:Buffer.from(l.key,"hex"),project:{id:l.projectId,name:l.projectName??l.projectId,usesOrgKey:l.projectUsesOrgKey===!0},viaSession:!0}}const{serverUrl:r,token:n,orgId:i,passphrase:h}=await vt(e),a=await be(h,i),c=e.project?await nt(r,n,e.project):null,p=c&&!c.usesOrgKey?Se(a,c.id):a;return{serverUrl:r,token:n,key:p,project:c,viaSession:!1}}async function St(){const e=Je(process.argv);if(e.help)return wt(),0;e.reportJson||Te("import secrets",_e);const t=await kt(e),o=Xe(e.source??t.defaultSource);j&&!e.reportJson&&w(` ${g.green("\u2714")} Read ${t.entries.length} key${t.entries.length===1?"":"s"} ${g.dim(`(${t.mode}); the values stay in memory`)}`);const r=new Map;for(const f of t.entries)r.set(f.key,f);const n=t.entries.length-r.size;let i=[...r.values()];if(e.only.length>0&&(i=i.filter(f=>ie(f.key,e.only))),e.exclude.length>0&&(i=i.filter(f=>!ie(f.key,e.exclude))),i.length===0)throw new m(`No usable keys found in the input (${t.mode}). `+(t.problems?.length?`${t.problems.length} line(s) were skipped \u2014 see above.`:""));const{serverUrl:h,token:a,key:c,project:p,viaSession:l}=await bt(e),d=e.minLength??Y,y=[],u=[],$=j&&!e.reportJson?G("Fingerprinting on this machine"):null;for(const f of i){if(f.key.length>200){u.push({key:f.key,action:"rejected",reason:"key longer than 200 characters"});continue}const A=ke(f.value),P=Ve(A,{minLength:d});if(!P.ok&&!e.allowWeak){u.push({key:f.key,action:"rejected",reason:P.reason,length:A.length});continue}const ge=ve(f.value,c);y.push({key:f.key,digests:ge,weak:!P.ok,weakReason:P.reason})}$?.succeed(`${y.length} fingerprint${y.length===1?"":"s"} computed here ${g.dim("(three variants each)")}`),j&&!e.reportJson&&y.length>0&&await yt({label:y[0].key,cand:y[0],viaSession:l});const S=j&&!e.reportJson?G("Comparing with what your workspace already holds"):null;let k=await ot(h,a,l);p&&(k=k.filter(f=>f&&f.projectId===p.id)),S?.succeed(`${k.length} existing secret${k.length===1?"":"s"} compared`);const b=We(k);if(!b)for(const f of y)delete f.digests.scanPrefilter;const{plan:v,missing:E}=et({candidates:y,existing:k,source:o});p||await rt({plan:v,existing:k,serverUrl:h,token:a});const N=new Map(y.map(f=>[f.key,f]));for(const f of v){const A=N.get(f.key);A?.weak&&(f.action==="create"||f.action==="rotate")&&(f.reason=`${f.reason} (weak: ${A.weakReason}, allowed by --allow-weak)`)}const _=[...v,...u].sort((f,A)=>ue(f.action)-ue(A.action)||f.key.localeCompare(A.key)),fe=jt({existing:k,plan:v,byKey:N}),R=Me(fe),W=v.filter(f=>f.action==="create"||f.action==="rotate");if(e.reportJson){if(console.log(JSON.stringify({source:o,sourceTag:O(o),mode:t.mode,shape:t.shape??null,dryRun:!e.apply,minLength:d,allowWeak:e.allowWeak,duplicateKeys:n,inputProblems:t.problems??[],counts:M(_),plan:_.map(f=>({key:f.key,action:f.action,reason:f.reason??null,length:f.length??null})),missing:E,scanBudget:{windowLengths:R.windowLengths,maxPasteChars:R.ceiling===1/0?null:R.ceiling,warn:R.ceiling<Z,atCharacterCap:R.atCharacterCap,legacySecrets:R.legacySecrets,maxPasteCharsIfReenrolled:R.ceilingIfReenrolled===1/0?null:R.ceilingIfReenrolled,serverStoresScanPrefilter:b}},null,2)),!e.apply)return 0}else{for(const f of t.problems??[]){const A=f.line!==void 0?`line ${f.line}`:f.key;console.log(`${s.yellow}!${s.reset} ${A}: ${f.message}`)}n>0&&console.log(`${s.dim}${n} duplicate key(s) in the input; the last value of each was used.${s.reset}`),b||pe(),j?dt({rows:_,missing:E,source:o,dryRun:!e.apply,budget:R,projectName:p?p.name:null,byKey:N}):lt({rows:_,missing:E,source:o,dryRun:!e.apply,budget:R,projectName:p?p.name:null}),mt({writes:W,byKey:N,serverUrl:h,projectId:p?p.id:null,source:o,dryRun:!e.apply,showRequest:e.showRequest,viaSession:l}),j&&!e.apply&&(w(""),w(` ${g.bold("Dry run. Nothing was sent.")} ${g.dim("Re-run with --apply to register.")}`)),j&&w("")}if(!e.apply)return 0;if(W.length===0)return console.log(`${s.dim}Nothing to write.${s.reset}`),0;if(!e.yes){const f=M(v);if(!await pt(`Register ${f.create} new and rotate ${f.rotate} existing fingerprint(s) for this org? [y/N]`))return console.log("Aborted."),0}console.log("");const T=await ft({rows:W,byKey:N,serverUrl:h,token:a,source:o,projectId:p?p.id:null}),I=T.filter(f=>!f.ok);return console.log(""),console.log(I.length===0?`${s.green}${T.length} fingerprint(s) registered.${s.reset}`:`${s.red}${I.length} of ${T.length} failed.${s.reset}`),q(R),j&&(w(""),B(I.length===0?"Done":"Finished with errors",["",...J([["Registered",`${T.length-I.length} of ${T.length}`],["Sent",`${z(T.sentBytes??0)} in ${T.requests??0} request${T.requests===1?"":"s"}`],["Secret values sent",g.green("0 B")],["Takes effect","in every connected browser within about a minute"]],{indent:0}),""],{tone:I.length===0?"green":"red",width:78})),console.log(""),I.length===0?0:1}const he=["create","rotate","conflict","skip","rejected"],ue=e=>{const t=he.indexOf(e);return t===-1?he.length:t};function jt({existing:e,plan:t,byKey:o}){const r=e.map(i=>({...i})),n=new Map(r.map(i=>[i.id,i]));for(const i of t){const h=o.get(i.key);if(!h)continue;const a=h.digests;if(i.action==="create"){r.push({id:`pending:${i.key}`,label:i.key,hmacHex:a.digest,length:a.length,hmacHexStripped:a.hmacHexStripped,lengthStripped:a.lengthStripped,hmacHexLower:a.hmacHexLower,lengthLower:a.lengthLower,scanPrefilter:a.scanPrefilter,tags:[]});continue}if(i.action==="rotate"){const c=n.get(i.id);if(!c)continue;c.hmacHex=a.digest,c.length=a.length,c.hmacHexStripped=a.hmacHexStripped,c.lengthStripped=a.lengthStripped,c.hmacHexLower=a.hmacHexLower,c.lengthLower=a.lengthLower,c.scanPrefilter=a.scanPrefilter}}return r}function Rt(){try{return ye(process.argv[1])}catch{return process.argv[1]}}const At=!!process.argv[1]&&import.meta.url===we(Rt()).href;At&&St().then(e=>process.exit(e)).catch(e=>{e instanceof m&&(console.error(`${s.red}${e.message}${s.reset}`),process.exit(2)),console.error(`${s.red}Fatal: ${e instanceof Error?e.message:e}${s.reset}`),process.exit(1)});export{Y as DEFAULT_MIN_LENGTH,st as decodeJwtPayload,et as diffAgainstServer,Ue as entriesFromJsonDocument,Ve as junkVerdict,Xe as normalizeSource,Fe as parseDotenv,Be as parseFlatYaml,oe as parseJsonSecrets,Me as scanBudgetForSecrets,O as sourceTag,it as tokenRoleProblem,ne as unwrapSecretsDocument};
70
+ `)}async function Et(e){const t=[e.env&&"env",e.jsonFile&&"json",e.yaml&&"yaml",e.stdin&&"stdin"].filter(Boolean);if(t.length===0)throw new y("Nothing to import. Pass one of --env, --json, --yaml or --stdin (see --help).");if(t.length>1)throw new y(`Pick one input mode, got: ${t.map(i=>"--"+i).join(", ")}`);const r=t[0];if(r==="env")return{...Ge(F(e.env,"--env")),mode:r,defaultSource:Y(e.env)};if(r==="json")return{...ae(F(e.jsonFile,"--json")),mode:r,defaultSource:Y(e.jsonFile)};if(r==="yaml")return{...Xe(F(e.yaml,"--yaml")),mode:r,defaultSource:Y(e.yaml)};const o=await ot();if(o.trim()==="")throw new y("Nothing arrived on stdin.");return{...ae(o),mode:r,defaultSource:"stdin"}}async function Nt(e){const t=process.env.REDAKTYN_TOKEN||process.env.REDAKTYN_JWT;let r=null;if(!t){const u=G();if(u)try{r=await Ae(u)}catch(m){throw new y(m.message)}}const o=e.server||!t&&r?.serverUrl||Oe(),n=t||r?.token;if(!n)throw new y("Run `redaktyn-login` to sign in as an OWNER or ADMIN (or set REDAKTYN_TOKEN for a script).");const i=ut(n),p=pt(i);if(p)throw new y(p);const l=e.orgId||i?.orgId||i?.org_id||process.env.REDAKTYN_ORG_ID;if(!l)throw new y("Could not determine the org id from the token. Pass --org-id.");const d=e.orgId||process.env.REDAKTYN_ORG_ID;if(d&&i?.orgId&&d!==i.orgId)throw new y("The org id given does not match the token's org id.");let a;try{({orgKey:a}=await Ie({server:o,token:n,orgId:l,who:r?`Signed in as ${r.email}${r.orgName?` (${r.orgName})`:""}.`:null,label:"Org passphrase",record:!!e.apply}))}catch(u){throw new y(u.message)}return{serverUrl:o,token:n,orgId:l,orgKey:a}}async function At(e){const r=process.env.REDAKTYN_TOKEN||process.env.REDAKTYN_JWT||G()?null:Te();if(r){let a;try{a=await xe(r)}catch(u){throw new y(u.message)}if(e.project){const u=e.project.trim().toLowerCase();if(u!==String(a.projectId).toLowerCase()&&u!==String(a.projectName||"").toLowerCase())throw new y(`This machine is connected to project "${a.projectName??a.projectId}" only, not "${e.project}". Drop --project, or ask for an invite to the other project.`)}if(!a.projectId)throw new y("This session is not tied to a project. Ask for a new invite link.");if(e.apply&&!a.canEnrol)throw new y("This invite lets you scan but not enrol secrets. Ask your admin for a link made with: redaktyn-invite --can-enrol");return{serverUrl:e.server||a.serverUrl,token:a.token,key:Buffer.from(a.key,"hex"),project:{id:a.projectId,name:a.projectName??a.projectId,usesOrgKey:a.projectUsesOrgKey===!0},viaSession:!0}}const{serverUrl:o,token:n,orgId:i,orgKey:p}=await Nt(e),l=e.project?await lt(o,n,e.project):null,d=l&&!l.usesOrgKey?Ee(p,l.id):p;return{serverUrl:o,token:n,key:d,project:l,viaSession:!1}}async function xt(){const e=Be(process.argv);if(e.help)return Rt(),0;e.reportJson||Le("import secrets",De);const t=await Et(e),r=rt(e.source??t.defaultSource);E&&!e.reportJson&&w(` ${g.green("\u2714")} Read ${t.entries.length} key${t.entries.length===1?"":"s"} ${g.dim(`(${t.mode}); the values stay in memory`)}`);const o=new Map;for(const h of t.entries)o.set(h.key,h);const n=t.entries.length-o.size;let i=[...o.values()];if(e.only.length>0&&(i=i.filter(h=>ce(h.key,e.only))),e.exclude.length>0&&(i=i.filter(h=>!ce(h.key,e.exclude))),i.length===0)throw new y(`No usable keys found in the input (${t.mode}). `+(t.problems?.length?`${t.problems.length} line(s) were skipped \u2014 see above.`:""));const{serverUrl:p,token:l,key:d,project:a,viaSession:u}=await At(e),m=e.minLength??q,$=[],c=[],f=Me(),k=E&&!e.reportJson?Z("Fingerprinting on this machine"):null;for(const h of i){if(h.key.length>200){c.push({key:h.key,action:"rejected",reason:"key longer than 200 characters"});continue}if(Qe.has(h.key)){c.push({key:h.key,action:"rejected",reason:"Doppler's own project, environment or config name, not a secret"});continue}const R=je(h.value),C=nt(R,{minLength:m});if(!C.ok&&!e.allowWeak){c.push({key:h.key,action:"rejected",reason:C.reason,length:R.length});continue}const we=Re(h.value,d),U=f?f(h.value):null;$.push({key:h.key,digests:we,weak:!C.ok,weakReason:C.reason,guessable:U?.guessable?U:null})}k?.succeed(`${$.length} fingerprint${$.length===1?"":"s"} computed here ${g.dim("(three variants each)")}`),E&&!e.reportJson&&$.length>0&&await St({label:$[0].key,cand:$[0],viaSession:u});const v=E&&!e.reportJson?Z("Comparing with what your workspace already holds"):null;let b=await dt(p,l,u);a&&(b=b.filter(h=>h&&h.projectId===a.id)),v?.succeed(`${b.length} existing secret${b.length===1?"":"s"} compared`);const S=qe(b);if(!S)for(const h of $)delete h.digests.scanPrefilter;const{plan:j,missing:x}=it({candidates:$,existing:b,source:r});a||await ct({plan:j,existing:b,serverUrl:p,token:l});const I=new Map($.map(h=>[h.key,h]));for(const h of j){const R=I.get(h.key);R?.weak&&(h.action==="create"||h.action==="rotate")&&(h.reason=`${h.reason} (weak: ${R.weakReason}, allowed by --allow-weak)`),R?.guessable&&(h.action==="create"||h.action==="rotate")&&(h.reason=`${h.reason} (could be guessed: ${Tt(R.guessable)})`)}const ye=j.filter(h=>(h.action==="create"||h.action==="rotate")&&I.get(h.key)?.guessable).map(h=>h.key),P=[...j,...c].sort((h,R)=>me(h.action)-me(R.action)||h.key.localeCompare(R.key)),$e=It({existing:b,plan:j,byKey:I}),N=Je($e),K=j.filter(h=>h.action==="create"||h.action==="rotate");if(e.reportJson){if(console.log(JSON.stringify({source:r,sourceTag:O(r),mode:t.mode,shape:t.shape??null,dryRun:!e.apply,minLength:m,allowWeak:e.allowWeak,duplicateKeys:n,inputProblems:t.problems??[],counts:W(P),plan:P.map(h=>({key:h.key,action:h.action,reason:h.reason??null,length:h.length??null,guessable:f?!!I.get(h.key)?.guessable:null})),missing:x,scanBudget:{windowLengths:N.windowLengths,maxPasteChars:N.ceiling===1/0?null:N.ceiling,warn:N.ceiling<ee,atCharacterCap:N.atCharacterCap,legacySecrets:N.legacySecrets,maxPasteCharsIfReenrolled:N.ceilingIfReenrolled===1/0?null:N.ceilingIfReenrolled,serverStoresScanPrefilter:S}},null,2)),!e.apply)return 0}else{for(const h of t.problems??[]){const R=h.line!==void 0?`line ${h.line}`:h.key;console.log(`${s.yellow}!${s.reset} ${R}: ${h.message}`)}n>0&&console.log(`${s.dim}${n} duplicate key(s) in the input; the last value of each was used.${s.reset}`),S||fe(),E?mt({rows:P,missing:x,source:r,dryRun:!e.apply,budget:N,projectName:a?a.name:null,byKey:I}):ft({rows:P,missing:x,source:r,dryRun:!e.apply,budget:N,projectName:a?a.name:null}),vt({writes:K,byKey:I,serverUrl:p,projectId:a?a.id:null,source:r,dryRun:!e.apply,showRequest:e.showRequest,viaSession:u}),Ot(ye,f!==null),E&&!e.apply&&(w(""),w(` ${g.bold("Dry run. Nothing was sent.")} ${g.dim("Re-run with --apply to register.")}`)),E&&w("")}if(!e.apply)return 0;if(K.length===0)return console.log(`${s.dim}Nothing to write.${s.reset}`),0;if(!e.yes){const h=W(j);if(!await yt(`Register ${h.create} new and rotate ${h.rotate} existing fingerprint(s) for this org? [y/N]`))return console.log("Aborted."),0}console.log("");const T=await kt({rows:K,byKey:I,serverUrl:p,token:l,source:r,projectId:a?a.id:null}),L=T.filter(h=>!h.ok);return console.log(""),console.log(L.length===0?`${s.green}${T.length} fingerprint(s) registered.${s.reset}`:`${s.red}${L.length} of ${T.length} failed.${s.reset}`),B(N),E&&(w(""),z(L.length===0?"Done":"Finished with errors",["",...J([["Registered",`${T.length-L.length} of ${T.length}`],["Sent",`${V(T.sentBytes??0)} in ${T.requests??0} request${T.requests===1?"":"s"}`],["Secret values sent",g.green("0 B")],["Takes effect","in every connected browser within about a minute"]],{indent:0}),""],{tone:L.length===0?"green":"red",width:78})),console.log(""),L.length===0?0:1}function Tt(e){return e.patterns.length>0?`built from ${e.patterns.slice(0,3).join(", ")}`:"short"}function Ot(e,t){if(!t){console.log(`${s.dim}Could not load the check for values that could be guessed; nothing else changed.${s.reset}`);return}if(e.length===0)return;const r=e.length===1;console.log(""),console.log(`${s.yellow}!${s.reset} ${e.length} value${r?"":"s"} could be found by guessing: ${e.join(", ")}.`),console.log(` Anyone who copies the workspace key off one of your team's devices can test guesses against ${r?"its":"their"} fingerprint very fast.`),console.log(` Registering still stops ${r?"it":"them"} being pasted. Change ${r?"it":"them"} to a long random value when you can, then import again.`)}const ge=["create","rotate","conflict","skip","rejected"],me=e=>{const t=ge.indexOf(e);return t===-1?ge.length:t};function It({existing:e,plan:t,byKey:r}){const o=e.map(i=>({...i})),n=new Map(o.map(i=>[i.id,i]));for(const i of t){const p=r.get(i.key);if(!p)continue;const l=p.digests;if(i.action==="create"){o.push({id:`pending:${i.key}`,label:i.key,hmacHex:l.digest,length:l.length,hmacHexStripped:l.hmacHexStripped,lengthStripped:l.lengthStripped,hmacHexLower:l.hmacHexLower,lengthLower:l.lengthLower,scanPrefilter:l.scanPrefilter,tags:[]});continue}if(i.action==="rotate"){const d=n.get(i.id);if(!d)continue;d.hmacHex=l.digest,d.length=l.length,d.hmacHexStripped=l.hmacHexStripped,d.lengthStripped=l.lengthStripped,d.hmacHexLower=l.hmacHexLower,d.lengthLower=l.lengthLower,d.scanPrefilter=l.scanPrefilter}}return o}function Lt(){try{return be(process.argv[1])}catch{return process.argv[1]}}const _t=!!process.argv[1]&&import.meta.url===Se(Lt()).href;_t&&xt().then(e=>process.exit(e)).catch(e=>{e instanceof y&&(console.error(`${s.red}${e.message}${s.reset}`),process.exit(2)),console.error(`${s.red}Fatal: ${e instanceof Error?e.message:e}${s.reset}`),process.exit(1)});export{q as DEFAULT_MIN_LENGTH,ut as decodeJwtPayload,it as diffAgainstServer,Ve as entriesFromJsonDocument,nt as junkVerdict,rt as normalizeSource,Ge as parseDotenv,Xe as parseFlatYaml,ae as parseJsonSecrets,Je as scanBudgetForSecrets,O as sourceTag,pt as tokenRoleProblem,se as unwrapSecretsDocument};
@@ -1,16 +1,25 @@
1
1
  #!/usr/bin/env node
2
- import{pathToFileURL as K}from"node:url";import{realpathSync as P}from"node:fs";import{createInterface as R}from"node:readline";import{deriveKey as C,deriveProjectKey as D}from"./redaktyn-fingerprint.mjs";import{SessionError as i,apiJson as j,freshAdminSession as L,loadAdminSession as O,resolveServerUrl as U,sealInviteKey as Y}from"./redaktyn-session.mjs";import{askWorkspacePassphrase as W}from"./redaktyn-passphrase.mjs";import{copyToClipboard as q}from"./redaktyn-clipboard.mjs";import{banner as B,box as F,k as s,rich as v,rows as G,say as u,step as k}from"./redaktyn-ui.mjs";import{createRequire as _}from"node:module";const H=_(import.meta.url)("./package.json").version;function J(){console.log(`redaktyn-invite: mint a single-use invite link for one project
2
+ import{pathToFileURL as H}from"node:url";import{existsSync as D,realpathSync as G,readFileSync as q,statSync as z,writeFileSync as M,chmodSync as J}from"node:fs";import{createInterface as V}from"node:readline";import{deriveProjectKey as O}from"./redaktyn-fingerprint.mjs";import{SessionError as a,apiJson as A,freshAdminSession as X,loadAdminSession as Q,resolveServerUrl as Z,sealInviteKey as P}from"./redaktyn-session.mjs";import{askWorkspaceKey as U}from"./redaktyn-passphrase.mjs";import{copyToClipboard as ee}from"./redaktyn-clipboard.mjs";import{banner as te,box as ne,k as c,rich as K,rows as oe,say as v,step as x}from"./redaktyn-ui.mjs";import{createRequire as se}from"node:module";const _=se(import.meta.url),re=_("./package.json").version;function ie(){console.log(`redaktyn-invite: mint a single-use invite link for one project
3
3
 
4
4
  --project <name|id> The project the link is for (required)
5
5
  --can-enrol Let the redeeming CLI register secrets on that project
6
6
  --expires-days <n> Link lifetime (default 7)
7
7
  --name <text> Name to show for the person
8
8
  --email <address> Restrict the link to this email
9
+ --csv <file> Invite a whole list: a .csv/.tsv/.txt of "Name, email" rows, or just email addresses.
10
+ Shows the plan and creates nothing unless --apply is given.
11
+ --apply With --csv: actually create the links
12
+ --out <file> With --csv --apply: where the links go (default redaktyn-invites-<project>.csv, private to you)
13
+ --force With --csv: overwrite the --out file if it exists
9
14
  --copy Copy the link to your clipboard (asked, by default, when run in a terminal)
10
15
  --no-copy Do not copy it, and do not ask
11
- --app-url <url> Address to put in the link (default https://redaktyn.com)
16
+ --app-url <url> Address to put in the link (default: the server you are signed in to)
12
17
  --server <url> API address (default https://redaktyn.com; self-hosted only)
13
18
 
14
- Needs: redaktyn-login first (or REDAKTYN_TOKEN), and the workspace passphrase (REDAKTYN_PASSPHRASE or a prompt)`)}function M(r){const e={project:null,canEnrol:!1,days:7,name:null,email:null,appUrl:"https://redaktyn.com",server:null,help:!1,copy:null};for(let o=2;o<r.length;o++){const t=r[o],n=()=>{const l=r[++o];if(l===void 0||l.startsWith("--"))throw new i(`${t} needs a value`);return l};if(t==="--help"||t==="-h")e.help=!0;else if(t==="--project")e.project=n();else if(t==="--can-enrol"||t==="--can-enroll")e.canEnrol=!0;else if(t==="--expires-days")e.days=Number(n());else if(t==="--name")e.name=n();else if(t==="--email")e.email=n();else if(t==="--copy")e.copy=!0;else if(t==="--no-copy")e.copy=!1;else if(t==="--app-url")e.appUrl=n();else if(t==="--server")e.server=n();else throw new i(`Unknown flag: ${t}`)}if(!Number.isInteger(e.days)||e.days<1||e.days>365)throw new i("--expires-days must be 1 to 365");return e}function V(r){return new Promise(e=>{const o=R({input:process.stdin,output:process.stderr});o.question(r,t=>{o.close(),e(!/^\s*n/i.test(t))})})}async function E(r,e){let o=e;if(o===null&&(o=process.stdin.isTTY&&v?await V(` Copy the link to your clipboard? ${s.dim("[Y/n]")} `):!1),!o)return;const t=q(r),n=t.ok?"Copied. Paste it where you are sending it; it works once.":"Could not copy (no clipboard tool found). The link is printed above.";v?u(` ${t.ok?s.green("\u2714"):s.amber("\u25B2")} ${n}`):console.log(n)}function z(r){try{return JSON.parse(Buffer.from(r.split(".")[1],"base64url").toString()).orgId}catch{return null}}async function Q(r){const e=M(r);if(e.help)return J(),0;if(!e.project)throw new i("Say which project the link is for: --project <name|id>");const o=process.env.REDAKTYN_TOKEN,t=o?null:await L(O()),n=e.server||(t&&!o?t.serverUrl:null)||U(),l=o||t.token,g=z(l);if(!g)throw new i("That token carries no org id.");const T=t?`Signed in as ${t.email}${t.orgName?` (${t.orgName})`:""}.`:null;B("invite link",H);const m=k("Looking up the project"),c=await j(n,"GET","/api/projects",{token:l});if(!c.ok||!Array.isArray(c.data))throw m.fail("Could not read your projects"),new i(`GET /api/projects failed (${c.status}). Is the token an OWNER/ADMIN token?`);const p=e.project.trim(),f=c.data.filter(h=>h.id===p).length?c.data.filter(h=>h.id===p):c.data.filter(h=>String(h.name).toLowerCase()===p.toLowerCase());if(f.length!==1)throw m.fail(f.length?`"${p}" matches several projects`:`No project "${p}"`),new i(f.length?`"${p}" matches several projects; pass the id.`:`No project "${p}". Known: ${c.data.map(h=>h.name).join(", ")}.`);const a=f[0];if(a.status==="CLOSED")throw m.fail("That project is closed"),new i(`Project ${a.name} is closed.`);m.succeed(`Project ${a.name}`);const b=await W({server:n,token:l,orgId:g,who:T}),S=k("Deriving the project key on this machine"),w=await C(b,g),N=a.usesOrgKey?w:D(w,a.id);S.succeed(`Project key derived here ${s.dim("(PBKDF2-SHA256, 600,000 rounds)")}`);const A=k("Sealing the key into the link"),{w:I,blob:x}=await Y(N,a.usesOrgKey?1:2);A.succeed(`Key sealed ${s.dim("(AES-GCM; the opener lives only in the link's #fragment)")}`);const $=k("Registering the link with the server"),d=await j(n,"POST","/api/invites",{token:l,body:{projectId:a.id,keyBlob:x,maxUses:1,expiresInDays:e.days,...e.canEnrol?{canEnrol:!0}:{},...e.name?{assignedName:e.name}:{},...e.email?{assignedEmail:e.email}:{}}});if(!d.ok)throw $.fail("The server refused the invite"),new i(`The server refused the invite (${d.status}): ${d.data?.error||d.text.slice(0,200)}`);$.succeed(`Registered ${s.dim("(the server stored ciphertext it cannot open)")}`);const y=`${e.appUrl.replace(/\/+$/,"")}/connect?code=${d.data.code}#w=${I}`;return v?(u(""),F("Invite ready",["",...G([["Project",a.name],["Access",e.canEnrol?s.amber("may enrol secrets on this project only"):"scan only"],["Lifetime",`single use ${s.dim("\xB7")} expires in ${e.days} day${e.days===1?"":"s"}`],["Opens with","the part after # in the link. It never reaches the server"],["Revoke",`DELETE /api/invites/${d.data.id}`]],{indent:0}),""],{tone:"green",width:78}),u(""),u(` ${s.bold("Send this link over a channel you trust.")} ${s.dim("Whoever opens it first gets this project's key.")}`),u(` ${s.dim("They run")} ${s.bold("redaktyn-connect")} ${s.dim("and paste it.")}`),u(""),console.log(y),u(""),await E(y,e.copy),0):(console.log(`Invite for project ${a.name}${e.canEnrol?" (may enrol secrets)":" (scan only)"}, single use, expires in ${e.days} day(s):
15
- `),console.log(y),console.log(`
16
- Send it over a channel you trust: whoever opens it first gets this project's key.`),console.log(`They run: redaktyn-connect and paste it. Revoke before use: DELETE /api/invites/${d.data.id}`),await E(y,e.copy),0)}function X(){try{return P(process.argv[1])}catch{return process.argv[1]}}process.argv[1]&&import.meta.url===K(X()).href&&Q(process.argv).then(r=>process.exit(r),r=>{console.error(r.message),process.exit(r instanceof i?1:2)});export{Q as main};
19
+ Needs: redaktyn-login first (or REDAKTYN_TOKEN), and the workspace passphrase (REDAKTYN_PASSPHRASE or a prompt)`)}function ae(o){const e={project:null,canEnrol:!1,days:7,name:null,email:null,appUrl:null,server:null,help:!1,copy:null,csv:null,apply:!1,out:null,force:!1};for(let r=2;r<o.length;r++){const n=o[r],i=()=>{const l=o[++r];if(l===void 0||l.startsWith("--"))throw new a(`${n} needs a value`);return l};if(n==="--help"||n==="-h")e.help=!0;else if(n==="--project")e.project=i();else if(n==="--can-enrol"||n==="--can-enroll")e.canEnrol=!0;else if(n==="--expires-days")e.days=Number(i());else if(n==="--name")e.name=i();else if(n==="--email")e.email=i();else if(n==="--copy")e.copy=!0;else if(n==="--no-copy")e.copy=!1;else if(n==="--csv")e.csv=i();else if(n==="--apply")e.apply=!0;else if(n==="--out")e.out=i();else if(n==="--force")e.force=!0;else if(n==="--app-url")e.appUrl=i();else if(n==="--server")e.server=i();else throw new a(`Unknown flag: ${n}`)}if(!Number.isInteger(e.days)||e.days<1||e.days>365)throw new a("--expires-days must be 1 to 365");if(e.csv&&(e.name||e.email||e.copy!==null))throw new a("--csv takes the names and emails from the file: drop --name, --email and --copy");if(!e.csv&&(e.apply||e.out||e.force))throw new a("--apply, --out and --force go with --csv");return e}function le(o){return new Promise(e=>{const r=V({input:process.stdin,output:process.stderr});r.question(o,n=>{r.close(),e(!/^\s*n/i.test(n))})})}async function F(o,e){let r=e;if(r===null&&(r=process.stdin.isTTY&&K?await le(` Copy the link to your clipboard? ${c.dim("[Y/n]")} `):!1),!r)return;const n=ee(o),i=n.ok?"Copied. Paste it where you are sending it; it works once.":"Could not copy (no clipboard tool found). The link is printed above.";K?v(` ${n.ok?c.green("\u2714"):c.amber("\u25B2")} ${i}`):console.log(i)}function ce(o){try{return JSON.parse(Buffer.from(o.split(".")[1],"base64url").toString()).orgId}catch{return null}}function W(){try{return _("./redaktyn-shared.cjs")}catch{throw new a("Cannot load the shared code. From a checkout, run `npm install` then `npm run build -w @redaktyn/shared`; otherwise reinstall the CLI.")}}const de=o=>String(o).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"project";async function pe({o,server:e,token:r,orgId:n,who:i,project:l}){const f=W(),I=f.checkRosterFile({name:o.csv,size:D(o.csv)?z(o.csv).size:0});if(!D(o.csv))throw new a(`No such file: ${o.csv}`);if(!I.ok)throw new a(I.reason);const E=q(o.csv,"utf8"),h=await A(e,"GET","/api/invites",{token:r}),m=Date.now(),S=new Set((Array.isArray(h.data)?h.data:[]).filter(t=>t.projectId===l.id&&t.assignedEmail&&t.currentUses<t.maxUses&&(!t.expiresAt||new Date(t.expiresAt).getTime()>m)).map(t=>String(t.assignedEmail).toLowerCase())),s=f.parseRoster(E,{existingEmails:S}),w=s.rows.filter(t=>t.issues.length>0);console.log(`
20
+ Read ${s.rows.length} row${s.rows.length===1?"":"s"} from ${o.csv}${s.hadHeader?" (column titles found)":""}: ${s.people.length} to invite, ${w.length} set aside.`);for(const t of w.slice(0,20))console.log(` row ${t.line}: ${t.email||"(no address)"} ${t.issues.map(g=>f.ISSUE_LABEL[g]).join(", ")}`);w.length>20&&console.log(` and ${w.length-20} more`),s.skipped>0&&console.log(` ${s.skipped} rows past the first ${f.ROSTER_MAX_ROWS} were not read: invite in smaller batches.`);const j=s.rows.filter(t=>t.issues.length===0&&t.nameDerived).length;if(j>0&&console.log(` ${j} name${j===1?" was":"s were"} made from the email address because the list had none. It is locked into that person's link.`),s.people.length===0)throw new a("Nothing to invite in that file.");const u=await A(e,"GET","/api/plans/current",{token:r});if(u.ok&&u.data?.invites&&Number.isFinite(u.data.invites.max)&&u.data.invites.used+s.people.length>u.data.invites.max)throw new a(`That would make ${u.data.invites.used+s.people.length} unused invite links, but your plan allows ${u.data.invites.max}. Revoke unused links, move up a size, or invite fewer people.`);const y=o.out||`redaktyn-invites-${de(l.name)}.csv`;if(D(y)&&!o.force)throw new a(`${y} already exists. Choose another --out, or add --force to overwrite it.`);if(!o.apply)return console.log(`
21
+ Dry run: nothing was created. Re-run with --apply to make ${s.people.length} link${s.people.length===1?"":"s"} and write them to ${y}.`),0;const{orgKey:C}=await U({server:e,token:r,orgId:n,who:i}),N=x("Deriving the project key on this machine"),R=l.usesOrgKey?C:O(C,l.id);N.succeed(`Project key derived here ${c.dim("(PBKDF2-SHA256, 600,000 rounds)")}`);const k=x(`Creating ${s.people.length} link${s.people.length===1?"":"s"}`),p=[];let T=null;for(const t of s.people){if(T){p.push({...t,link:null,error:T});continue}try{const{w:g,code:Y,blob:B}=await P(R,l.usesOrgKey?1:2),b=await A(e,"POST","/api/invites",{token:r,body:{projectId:l.id,keyBlob:B,maxUses:1,expiresInDays:o.days,assignedName:t.name,assignedEmail:t.email,...o.canEnrol?{canEnrol:!0}:{}}});if(!b.ok){const L=b.data?.error||`HTTP ${b.status}`;p.push({...t,link:null,error:L}),(b.status===401||b.status===403)&&(T=`not attempted: ${L}`);continue}p.push({...t,link:`${o.appUrl.replace(/\/+$/,"")}/connect?code=${b.data.code}#w2=${g}`,inviteCode:Y,error:null})}catch(g){p.push({...t,link:null,error:g instanceof Error?g.message:"failed"})}}const d=p.filter(t=>t.link).length,$=p.length-d;$===0?k.succeed(`${d} link${d===1?"":"s"} created ${c.dim("(the server stored ciphertext it cannot open)")}`):k.fail(`${d} of ${p.length} links created`),M(y,f.inviteLinksCsv(p)+`
22
+ `,{mode:384});try{J(y,384)}catch{}console.log(`
23
+ Links written to ${y} (readable only by you). They are not printed here: each is a credential that works once.`),console.log("Send each person their own link over a channel you trust, then delete the file.");for(const t of p.filter(g=>!g.link).slice(0,20))console.log(` not created for ${t.email}: ${t.error}`);return $===0?0:1}async function he(o){const e=ae(o);if(e.help)return ie(),0;if(!e.project)throw new a("Say which project the link is for: --project <name|id>");const r=process.env.REDAKTYN_TOKEN,n=r?null:await X(Q()),i=e.server||(n&&!r?n.serverUrl:null)||Z(),l=r||n.token;e.appUrl||(e.appUrl=i);const f=ce(l);if(!f)throw new a("That token carries no org id.");const I=n?`Signed in as ${n.email}${n.orgName?` (${n.orgName})`:""}.`:null;te("invite link",re);const E=x("Looking up the project"),h=await A(i,"GET","/api/projects",{token:l});if(!h.ok||!Array.isArray(h.data))throw E.fail("Could not read your projects"),new a(`GET /api/projects failed (${h.status}). Is the token an OWNER/ADMIN token?`);const m=e.project.trim(),S=h.data.filter(t=>t.id===m).length?h.data.filter(t=>t.id===m):h.data.filter(t=>String(t.name).toLowerCase()===m.toLowerCase());if(S.length!==1)throw E.fail(S.length?`"${m}" matches several projects`:`No project "${m}"`),new a(S.length?`"${m}" matches several projects; pass the id.`:`No project "${m}". Known: ${h.data.map(t=>t.name).join(", ")}.`);const s=S[0];if(s.status==="CLOSED")throw E.fail("That project is closed"),new a(`Project ${s.name} is closed.`);if(E.succeed(`Project ${s.name}`),e.csv)return pe({o:e,server:i,token:l,orgId:f,who:I,project:s});const{SECURITY_CODE_WHERE_TO_TYPE:w,inviteShareText:j}=W(),{orgKey:u}=await U({server:i,token:l,orgId:f,who:I}),y=x("Deriving the project key on this machine"),C=s.usesOrgKey?u:O(u,s.id);y.succeed(`Project key derived here ${c.dim("(PBKDF2-SHA256, 600,000 rounds)")}`);const N=x("Sealing the key into the link"),{w:R,code:k,blob:p}=await P(C,s.usesOrgKey?1:2);N.succeed(`Key sealed ${c.dim("(AES-GCM; the opener lives only in the link's #fragment)")}`);const T=x("Registering the link with the server"),d=await A(i,"POST","/api/invites",{token:l,body:{projectId:s.id,keyBlob:p,maxUses:1,expiresInDays:e.days,...e.canEnrol?{canEnrol:!0}:{},...e.name?{assignedName:e.name}:{},...e.email?{assignedEmail:e.email}:{}}});if(!d.ok)throw T.fail("The server refused the invite"),new a(`The server refused the invite (${d.status}): ${d.data?.error||d.text.slice(0,200)}`);T.succeed(`Registered ${c.dim("(the server stored ciphertext it cannot open)")}`);const $=`${e.appUrl.replace(/\/+$/,"")}/connect?code=${d.data.code}#w2=${R}`;return K?(v(""),ne("Invite ready",["",...oe([["Project",s.name],["Access",e.canEnrol?c.amber("may enrol secrets on this project only"):"scan only"],["Lifetime",`single use ${c.dim("\xB7")} expires in ${e.days} day${e.days===1?"":"s"}`],["Opens with","the part after # in the link. It never reaches the server"],["Revoke",`DELETE /api/invites/${d.data.id}`]],{indent:0}),""],{tone:"green",width:78}),v(""),v(` ${c.bold("Send this link over a channel you trust.")} ${c.dim("Whoever opens it first gets this project's key.")}`),v(` ${c.dim("They run")} ${c.bold("redaktyn-connect")} ${c.dim("and paste it.")}`),v(""),console.log($),console.log(`Security code: ${k}`),v(` ${c.dim(w)}`),v(""),await F(j($,k),e.copy),0):(console.log(`Invite for project ${s.name}${e.canEnrol?" (may enrol secrets)":" (scan only)"}, single use, expires in ${e.days} day(s):
24
+ `),console.log($),console.log(`Security code: ${k}`),console.log(w),console.log(`
25
+ Send it over a channel you trust: whoever opens it first gets this project's key.`),console.log(`They run: redaktyn-connect and paste it. Revoke before use: DELETE /api/invites/${d.data.id}`),await F(j($,k),e.copy),0)}function ue(){try{return G(process.argv[1])}catch{return process.argv[1]}}process.argv[1]&&import.meta.url===H(ue()).href&&he(process.argv).then(o=>process.exit(o),o=>{console.error(o.message),process.exit(o instanceof a?1:2)});export{he as main};
@@ -0,0 +1 @@
1
+ import{SessionError as o,apiJson as i,oprfPinStore as u}from"./redaktyn-session.mjs";const c={"X-Redaktyn-Lock-Versions":"1,2,3"},l=15e3;async function p({share:e,blinded:s}){const n=process.env.REDAKTYN_SHARE_TOKEN,a=new URL(e.url).host;let t;try{t=await fetch(`${e.url.replace(/\/+$/,"")}/evaluate`,{method:"POST",headers:{"Content-Type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}},body:JSON.stringify({blinded:s}),signal:AbortSignal.timeout(l)})}catch{throw new o(`Could not reach your key-share server at ${a}. This workspace's key cannot be opened without it.`)}const r=await t.json().catch(()=>null);if(!t.ok)throw new o(t.status===401?`Your key-share server at ${a} wants a token. Set REDAKTYN_SHARE_TOKEN and run this again.`:`Your key-share server at ${a} refused the request (HTTP ${t.status}).`);if(typeof r?.evaluated!="string"||typeof r?.proof!="string")throw new o("Your key-share server's answer was not understood.");return{evaluated:r.evaluated,proof:r.proof}}function d({server:e,token:s},n){return{evaluate:async a=>{const t=await i(e,"POST","/api/org/key-lock/evaluate",{token:s,body:a,headers:c});if(!t.ok){const r=new o(t.data?.error??`The server could not help open the workspace key (HTTP ${t.status}).`);throw r.code=t.data?.code,r}return t.data},trust:{scope:n.scopeOf(e),pins:u(),firstUse:"allow"},evaluateShare:p,secretKey:process.env.REDAKTYN_SECRET_KEY||null}}function f(e){return e?.name==="SecretKeyNeededError"?new o(`${e.message} Run this in a terminal and it will ask, or set REDAKTYN_SECRET_KEY for a script.`):e?.name==="OprfProofError"||e?.name==="KeyShareUnavailableError"?new o(e.message):e}export{c as LOCK_HEADERS,f as explainLockError,d as lockNetwork};
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{pathToFileURL as x}from"node:url";import{realpathSync as A}from"node:fs";import{spawn as R}from"node:child_process";import{createRequire as I}from"node:module";import{banner as P,box as y,k as o,rich as c,rows as T,say as d,step as O}from"./redaktyn-ui.mjs";const W=I(import.meta.url)("./package.json").version;import*as E from"node:readline";import{SessionError as v,deleteAdminSession as j,loadAdminSession as k,loginWithBrowser as Y,loginWithPassword as C,readHidden as $,resolveServerUrl as D,sessionDir as b}from"./redaktyn-session.mjs";function U(e){if(process.env.REDAKTYN_NO_BROWSER)return!1;try{const[n,t]=process.platform==="darwin"?["open",[e]]:process.platform==="win32"?["cmd",["/c","start","",e]]:["xdg-open",[e]],a=R(n,t,{stdio:"ignore",detached:!0});return a.on("error",()=>{}),a.unref(),!0}catch{return!1}}function B(){console.log(`redaktyn-login: sign in as a workspace admin
2
+ import{pathToFileURL as N}from"node:url";import{realpathSync as x}from"node:fs";import{spawn as A}from"node:child_process";import{createRequire as R}from"node:module";import{banner as T,box as y,k as o,rich as g,rows as P,say as d,step as I}from"./redaktyn-ui.mjs";const O=R(import.meta.url)("./package.json").version;import*as W from"node:readline";import{SessionError as v,apiJson as E,deleteAdminSession as j,loadAdminSession as k,loginWithBrowser as D,loginWithPassword as U,readHidden as Y,resolveServerUrl as C,sessionDir as $}from"./redaktyn-session.mjs";function B(r){if(process.env.REDAKTYN_NO_BROWSER)return!1;try{const[n,i]=process.platform==="darwin"?["open",[r]]:process.platform==="win32"?["cmd",["/c","start","",r]]:["xdg-open",[r]],a=A(n,i,{stdio:"ignore",detached:!0});return a.on("error",()=>{}),a.unref(),!0}catch{return!1}}function L(){console.log(`redaktyn-login: sign in as a workspace admin
3
3
 
4
4
  redaktyn-login open the browser and approve the code there (nothing typed here)
5
5
  redaktyn-login --no-browser print the link instead of opening it (SSH, containers)
@@ -9,10 +9,10 @@ import{pathToFileURL as x}from"node:url";import{realpathSync as A}from"node:fs";
9
9
  redaktyn-login --status show who this machine is logged in as
10
10
  redaktyn-login --logout forget the login on this machine
11
11
 
12
- --server <url> API address (default ${D()}; only a self-hosted install changes it)
12
+ --server <url> API address (default ${C()}; only a self-hosted install changes it)
13
13
 
14
- The login is stored in ${b()} (readable only by you). Your password is never saved.`)}function M(e){return new Promise(n=>{const t=E.createInterface({input:process.stdin,output:process.stderr});t.question(e,a=>{t.close(),n(a.trim())})})}function m(e){if(c){d(""),y("Signed in",[...T([["Account",`${e.email} ${o.dim(`(${e.role})`)}`],["Workspace",e.orgName??e.orgId??"your workspace"],["Server",e.serverUrl],["Session",`${o.dim("kept in")} ${b()}${o.dim("/admin.json, readable only by you")}`],["Password",o.green("never typed here, never stored")]],{indent:0})],{tone:"green"});return}console.log(`Logged in as ${e.email} (${e.role}) of ${e.orgName??e.orgId??"your workspace"}.`),console.log(` server ${e.serverUrl}`)}async function q(e){const n=e.slice(2);if(n.includes("--help")||n.includes("-h"))return B(),0;if(n.includes("--logout")){const r=!!k();return j(),console.log(r?"Forgot this machine's Redaktyn admin login.":"There was no admin login to forget."),0}if(n.includes("--status")){const r=k();return r?(m(r),0):(console.log("Not logged in. Run: redaktyn-login"),1)}const t=r=>{const i=n.indexOf(r);return i>=0?n[i+1]:void 0},a=t("--server"),p=n.includes("--password-stdin");if(!(p||n.includes("--password")||t("--email")!==void 0)){let r=null,i=null;try{P("sign in",W);const s=await Y({serverUrl:a,onCode:({userCode:h,verificationUrl:g,expiresIn:S})=>{const f=!n.includes("--no-browser")&&U(g);if(c){y("Approve in your browser",["",` ${o.gray("Your code")} ${o.bold(o.clay(h))}`,"",` ${f?"A browser tab is opening on this link.":"Open this link in a browser where you are signed in:"}`,` ${o.blue(g)}`,"",` ${o.dim("Check the page shows the same code, then press Approve.")}`,` ${o.dim("Nothing is typed in this terminal, and no password is sent from it.")}`,""],{tone:"clay",width:70}),d("");const N=Date.now()+(S||600)*1e3;r=O("Waiting for you to approve in the browser"),i=setInterval(()=>{const w=Math.max(0,Math.round((N-Date.now())/1e3));r.update(`Waiting for you to approve in the browser ${o.dim(`${Math.floor(w/60)}:${String(w%60).padStart(2,"0")} left`)}`)},1e3);return}console.error(f?"Opening your browser to sign in.":"Open this page in a browser where you are signed in:"),console.error(`
15
- ${g}
16
- `),console.error(`Check that it shows the code ${h} and approve it. Waiting\u2026 (Ctrl+C to cancel)`)}});return i&&clearInterval(i),r&&r.succeed(`Approved by ${s.email}`),c||console.log(""),m(s),c?(d(""),d(` ${o.dim("Next")} ${o.bold("redaktyn-import --env .env --project <name>")} ${o.dim("(add --apply to register)")}`),d("")):console.log(`
17
- Next: redaktyn-import --env .env --project <name> (add --apply to register)`),0}catch(s){if(i&&clearInterval(i),r&&r.fail(s instanceof Error?s.message:String(s)),s instanceof v)return r||console.error(s.message),1;throw s}}let l=t("--email");if(!l){if(!process.stdin.isTTY)return console.error("Pass --email, or run this in a terminal."),2;l=await M("Email: ")}if(!l)return console.error("No email given."),2;if(!p&&!process.stdin.isTTY)return console.error("Run this in a terminal, or use --password-stdin."),2;const u=p?(await $("")).trim():await $("Password: ");if(!u)return console.error("No password given."),2;try{const r=await C(l,u,{serverUrl:a});return m(r),console.log(`
18
- Next: redaktyn-import --env .env --project <name> (add --apply to register)`),0}catch(r){if(r instanceof v)return console.error(r.message),1;throw r}}function F(){try{return A(process.argv[1])}catch{return process.argv[1]}}process.argv[1]&&import.meta.url===x(F()).href&&q(process.argv).then(e=>process.exit(e),e=>{console.error(e.message),process.exit(1)});export{q as main};
14
+ The login is stored in ${$()} (readable only by you). Your password is never saved.`)}function M(r){return new Promise(n=>{const i=W.createInterface({input:process.stdin,output:process.stderr});i.question(r,a=>{i.close(),n(a.trim())})})}function m(r){if(g){d(""),y("Signed in",[...P([["Account",`${r.email} ${o.dim(`(${r.role})`)}`],["Workspace",r.orgName??r.orgId??"your workspace"],["Server",r.serverUrl],["Session",`${o.dim("kept in")} ${$()}${o.dim("/admin.json, readable only by you")}`],["Password",o.green("never typed here, never stored")]],{indent:0})],{tone:"green"});return}console.log(`Logged in as ${r.email} (${r.role}) of ${r.orgName??r.orgId??"your workspace"}.`),console.log(` server ${r.serverUrl}`)}async function q(r){const n=r.slice(2);if(n.includes("--help")||n.includes("-h"))return L(),0;if(n.includes("--logout")){const e=k();let s=!1;if(e)try{const t=await E(e.serverUrl,"POST","/api/auth/logout",{token:e.token});s=t.ok&&t.data?.ended===!0}catch{}return j(),console.log(e?s?"Logged out: this machine's Redaktyn admin login is forgotten and ended on the server.":"Forgot this machine's Redaktyn admin login. The server could not be told, so its token runs until it expires (within 24 hours).":"There was no admin login to forget."),0}if(n.includes("--status")){const e=k();return e?(m(e),0):(console.log("Not logged in. Run: redaktyn-login"),1)}const i=e=>{const s=n.indexOf(e);return s>=0?n[s+1]:void 0},a=i("--server"),l=n.includes("--password-stdin");if(!(l||n.includes("--password")||i("--email")!==void 0)){let e=null,s=null;try{T("sign in",O);const t=await D({serverUrl:a,onCode:({userCode:h,verificationUrl:u,expiresIn:b})=>{const f=!n.includes("--no-browser")&&B(u);if(g){y("Approve in your browser",["",` ${o.gray("Your code")} ${o.bold(o.clay(h))}`,"",` ${f?"A browser tab is opening on this link.":"Open this link in a browser where you are signed in:"}`,` ${o.blue(u)}`,"",` ${o.dim("Check the page shows the same code, then press Approve.")}`,` ${o.dim("Nothing is typed in this terminal, and no password is sent from it.")}`,""],{tone:"clay",width:70}),d("");const S=Date.now()+(b||600)*1e3;e=I("Waiting for you to approve in the browser"),s=setInterval(()=>{const w=Math.max(0,Math.round((S-Date.now())/1e3));e.update(`Waiting for you to approve in the browser ${o.dim(`${Math.floor(w/60)}:${String(w%60).padStart(2,"0")} left`)}`)},1e3);return}console.error(f?"Opening your browser to sign in.":"Open this page in a browser where you are signed in:"),console.error(`
15
+ ${u}
16
+ `),console.error(`Check that it shows the code ${h} and approve it. Waiting\u2026 (Ctrl+C to cancel)`)}});return s&&clearInterval(s),e&&e.succeed(`Approved by ${t.email}`),g||console.log(""),m(t),g?(d(""),d(` ${o.dim("Next")} ${o.bold("redaktyn-import --env .env --project <name>")} ${o.dim("(add --apply to register)")}`),d("")):console.log(`
17
+ Next: redaktyn-import --env .env --project <name> (add --apply to register)`),0}catch(t){if(s&&clearInterval(s),e&&e.fail(t instanceof Error?t.message:String(t)),t instanceof v)return e||console.error(t.message),1;throw t}}let c=i("--email");if(!c){if(!process.stdin.isTTY)return console.error("Pass --email, or run this in a terminal."),2;c=await M("Email: ")}if(!c)return console.error("No email given."),2;if(!l&&!process.stdin.isTTY)return console.error("Run this in a terminal, or use --password-stdin."),2;const p=await Y(l?"":"Password: ");if(!p.trim())return console.error("No password given."),2;try{const e=await U(c,p,{serverUrl:a});return m(e),console.log(`
18
+ Next: redaktyn-import --env .env --project <name> (add --apply to register)`),0}catch(e){if(e instanceof v)return console.error(e.message),l&&p!==p.trim()&&console.error(`The password read from standard input starts or ends with a space. If that is not part of it, send it with: printf '%s' "$PASSWORD"`),1;throw e}}function F(){try{return x(process.argv[1])}catch{return process.argv[1]}}process.argv[1]&&import.meta.url===N(F()).href&&q(process.argv).then(r=>process.exit(r),r=>{console.error(r.message),process.exit(1)});export{q as main};
@@ -1,2 +1,2 @@
1
- import{createHmac as E}from"node:crypto";import{createRequire as N}from"node:module";import{createInterface as b}from"node:readline";import{deriveKey as $}from"./redaktyn-fingerprint.mjs";import{SessionError as d,apiJson as S,readHidden as D}from"./redaktyn-session.mjs";import{box as m,k as c,rich as i,say as f,step as k}from"./redaktyn-ui.mjs";const H="vaultx-passphrase-verify-v1",P=3,r=e=>process.stderr.write(e+`
2
- `),Y=N(import.meta.url);function _(e){return new Promise(a=>{const s=b({input:process.stdin,output:process.stderr});s.question(e,o=>{s.close(),a(o)})})}function A(){let e=null;try{e=Y("./redaktyn-shared.cjs")}catch{}if(!e||typeof e.generateOrgPassphrase!="function"||typeof e.validateGeneratedPassphrase!="function")throw new d("This workspace has no passphrase yet, and this copy of the CLI cannot generate one. Reinstall it (npm install -g @redaktyn/cli@latest), or from a checkout rebuild shared, and run this again.");return e}async function K({server:e,token:a}){const s=await S(e,"GET","/api/org/passphrase-verifier",{token:a});if(!s.ok)return{state:"unknown"};const o=s.data?.verifier;return typeof o=="string"&&o.length>0?{state:"anchored",verifier:o}:{state:"none"}}async function T(e,a){const s=await $(e,a);return E("sha256",s).update(H,"utf8").digest("hex")}async function R(e,a,s){return a.state!=="anchored"?"unchecked":await T(e,s)===a.verifier?"ok":"wrong"}async function I(e,{server:a,token:s,orgId:o}){const w=await T(e,o),y=await S(a,"PUT","/api/org/passphrase-verifier",{token:s,body:{verifier:w}});if(y.status===409)throw new d("This workspace already has a different passphrase, set a moment ago by someone else. Run this again and use that one.");return y.ok}async function O({server:e,token:a,orgId:s,who:o=null,label:w="Workspace passphrase",record:y=!0}){o&&(i?f(` ${c.green("\u2714")} ${o.replace(/^Signed in as /,"Signed in as ").replace(/\.$/,"")}`):r(o));const l=await K({server:e,token:a}),v=l.state==="none",u=process.env.REDAKTYN_PASSPHRASE,g=async n=>{if(!y){r(i?` ${c.dim("Dry run: this passphrase is accepted for the preview but not recorded. Run with --apply to set it.")}`:"Dry run: this passphrase is accepted for the preview but not recorded. Run with --apply to set it.");return}const t=k("Setting this as the workspace passphrase");await I(n,{server:e,token:a,orgId:s})?t.succeed("Workspace passphrase set. Every device and the dashboard are now checked against it"):t.succeed("Passphrase accepted, but the server did not record it yet. It will be checked once it is"),r(i?` ${c.dim("Nobody can reset it for you. Set recovery codes in the dashboard if you have not.")}`:"Nobody can reset it for you. Set recovery codes in the dashboard if you have not.")};if(u){if(v){if(!A().validateGeneratedPassphrase(u).ok)throw new d("This workspace has no passphrase yet, so REDAKTYN_PASSPHRASE would become it, and a new workspace's passphrase has to be generated. Run this once in a terminal to get one, then set REDAKTYN_PASSPHRASE to it.");return await g(u),u}const n=k("Checking the passphrase from REDAKTYN_PASSPHRASE"),t=await R(u,l,s);if(t==="wrong")throw n.fail("REDAKTYN_PASSPHRASE is not this workspace's passphrase"),new d("REDAKTYN_PASSPHRASE is not this workspace's passphrase.");return n.succeed(t==="ok"?"Passphrase from REDAKTYN_PASSPHRASE verified":"Passphrase from REDAKTYN_PASSPHRASE accepted. The server has nothing to check it against"),u}if(!process.stdin.isTTY)throw new d("Set REDAKTYN_PASSPHRASE. It is used locally to derive the key and is never sent.");if(v){const t=A().generateOrgPassphrase();if(!y)return r(i?` ${c.dim("Dry run: this workspace has no passphrase yet. The preview uses a throwaway one. Run with --apply to generate the real one.")}`:"Dry run: this workspace has no passphrase yet. The preview uses a throwaway one. Run with --apply to generate the real one."),t;const h=["This workspace has no passphrase yet, so one was generated for you.","It derives your keys on this machine and is never sent.","Nobody can reset it for you.","",t,"","Save it in your password manager now.","It stays in this terminal's scrollback until you clear it."];i?(f(""),m("Your workspace passphrase",h,{tone:"clay"}),f("")):(r(""),h.forEach(p=>r(p)),r(""));for(let p=P;p>0;p--){if((await _(i?` ${c.clay("\u203A")} Type ${c.dim("saved")} once you have kept it `:"Type 'saved' once you have kept it > ")).trim().toLowerCase()==="saved")return await g(t),t;r("Not set yet. Save the passphrase above, then type: saved")}throw new d("No passphrase was set after 3 tries. Nothing was changed.")}i?(f(""),m(w,["This derives your keys on this machine and is never sent,","never stored, and not shown while you type."],{tone:"clay"}),f("")):(r(""),r(`${w}: this derives the key on your machine and is never sent. Nothing shows while you type.`));for(let n=P;n>0;n--){const t=await D(i?` ${c.clay("\u203A")} Passphrase ${c.dim("(hidden)")} `:"Type it, then press Enter > ");if(!t){r("Nothing was typed.");continue}const h=k(i?"Checking it against your workspace":"Checking"),p=await R(t,l,s);if(p!=="wrong")return h.succeed(p==="ok"?"Passphrase verified. It matches your workspace":"Passphrase accepted. This workspace has nothing to check it against"),t;h.fail("That is not this workspace's passphrase"),r(i?n>1?` ${c.dim(`Try again (${n-1} left).`)}`:"":n>1?`That is not this workspace's passphrase. Try again (${n-1} left).`:"That is not this workspace's passphrase.")}throw new d("No correct passphrase after 3 tries. Nothing was changed.")}export{O as askWorkspacePassphrase};
1
+ import{createHmac as H}from"node:crypto";import{createRequire as Y}from"node:module";import{createInterface as C}from"node:readline";import{deriveKey as T}from"./redaktyn-fingerprint.mjs";import{SessionError as d,apiJson as g,readHidden as K}from"./redaktyn-session.mjs";import{LOCK_HEADERS as O,explainLockError as N,lockNetwork as A}from"./redaktyn-lock-net.mjs";import{box as b,k as u,rich as y,say as v,step as P}from"./redaktyn-ui.mjs";const W="vaultx-passphrase-verify-v1",$=3,p=s=>process.stderr.write(s+`
2
+ `),G=Y(import.meta.url);function U(s){return new Promise(r=>{const e=C({input:process.stdin,output:process.stderr});e.question(s,t=>{e.close(),r(t)})})}function S(){try{return G("./redaktyn-shared.cjs")}catch{return null}}function L(){const s=S();if(!s||typeof s.generateOrgPassphrase!="function"||typeof s.validateGeneratedPassphrase!="function")throw new d("This workspace has no passphrase yet, and this copy of the CLI cannot generate one. Reinstall it (npm install -g @redaktyn/cli@latest), or from a checkout rebuild shared, and run this again.");return s}async function B({server:s,token:r}){const e=await g(s,"GET","/api/org/passphrase-verifier",{token:r});if(!e.ok)return{state:"unknown"};const t=e.data?.verifier;return typeof t=="string"&&t.length>0?{state:"anchored",verifier:t}:{state:"none"}}const _=s=>H("sha256",s).update(W,"utf8").digest("hex");async function q({server:s,token:r}){const e=await g(s,"GET","/api/org/key-lock",{token:r,headers:O});if(e.status===404)return{supported:!1,lock:null};if(!e.ok)throw new d(e.data?.error??`Could not read this workspace's key lock (HTTP ${e.status}).`);const t=S(),a=e.data?.lock??null;if(a&&(!t||typeof t.unlockOrgKey!="function"))throw new d("This workspace's key is locked with the server, and this copy of the CLI cannot open it. Update it (npm install -g @redaktyn/cli@latest) and run this again.");return{supported:!0,lock:a&&t.isOrgKeyLock(a)?a:null}}async function I(s,r,e,t){if(e.lock){const c=S();let o;try{try{o=await c.unlockOrgKey(e.lock,s,t.orgId,A(t,c))}catch(n){if(n?.name!=="SecretKeyNeededError"||!process.stdin.isTTY)throw n;p(y?` ${u.dim(n.message)}`:n.message);const k=await K(y?` ${u.clay("\u203A")} Secret Key ${u.dim("(hidden)")} `:"Secret Key: ");o=await c.unlockOrgKey(e.lock,c.joinLockCredential(s,k.trim()),t.orgId,A(t,c))}}catch(n){throw N(n)}return o?{verdict:"ok",key:Buffer.from(o)}:{verdict:"wrong"}}const a=await T(s,t.orgId);return r.state!=="anchored"?{verdict:"unchecked",key:a}:_(a)===r.verifier?{verdict:"ok",key:a}:{verdict:"wrong"}}const D="This workspace already has a different passphrase, set a moment ago by someone else. Run this again and use that one.";async function F({server:s,token:r}){const e=await g(s,"GET","/api/secrets",{token:r});if(!e.ok||!Array.isArray(e.data))throw new d(`This workspace has no passphrase recorded, and the server could not say whether it already has secrets (HTTP ${e.status}), so none was set. Run this again.`);const t=e.data.filter(a=>a?.status!=="NEEDS_REENROLLMENT").length;if(t!==0)throw new d(`This workspace already has ${t} registered secret${t===1?"":"s"}, but its passphrase was never recorded. A passphrase set here would be a new one, which gives the workspace a different key, and none of them would be caught any more. Nothing was changed. To start over, reset the passphrase with passphrase recovery in the dashboard (it marks them for re-registration), then run this again.`)}async function V(s,r,e){const t=S();if(r.supported&&t&&typeof t.createLockedOrgKey=="function")try{const o=await t.createLockedOrgKey(s,e.orgId,A(e,t)),n=await g(e.server,"PUT","/api/org/key-lock",{token:e.token,body:{lock:o.lock,verifier:o.verifier}});if(n.status===409)throw new d(D);if(n.ok)return{recorded:!0,locked:!0,key:Buffer.from(o.orgKey)};if(n.status!==503)throw new d(n.data?.error??`Could not save the workspace key (HTTP ${n.status}).`)}catch(o){if(o?.code!=="KEY_LOCK_UNAVAILABLE")throw N(o)}const a=await T(s,e.orgId),c=await g(e.server,"PUT","/api/org/passphrase-verifier",{token:e.token,body:{verifier:_(a)}});if(c.status===409&&c.data?.code==="KEY_LOCK_REQUIRED")throw new d(c.data.error);if(c.status===409)throw new d(D);return{recorded:c.ok,locked:!1,key:a}}async function ee(s){return(await j(s)).passphrase}async function j({server:s,token:r,orgId:e,who:t=null,label:a="Workspace passphrase",record:c=!0}){t&&(y?v(` ${u.green("\u2714")} ${t.replace(/^Signed in as /,"Signed in as ").replace(/\.$/,"")}`):p(t));const o={server:s,token:r,orgId:e},n=await B({server:s,token:r}),k=await q({server:s,token:r}),E=n.state==="none"&&!k.lock;E&&await F(o);const l=process.env.REDAKTYN_PASSPHRASE,R=async i=>{if(!c)return p(y?` ${u.dim("Dry run: this passphrase is accepted for the preview but not recorded. Run with --apply to set it.")}`:"Dry run: this passphrase is accepted for the preview but not recorded. Run with --apply to set it."),{passphrase:i,orgKey:await T(i,e)};const h=P("Setting this as the workspace passphrase"),{recorded:f,locked:w,key:m}=await V(i,k,o);return f?h.succeed(w?"Workspace passphrase set. The workspace key is locked with the server, so a copy of its database cannot be used to guess it":"Workspace passphrase set. Every device and the dashboard are now checked against it"):h.succeed("Passphrase accepted, but the server did not record it yet. It will be checked once it is"),p(y?` ${u.dim("Nobody can reset it for you. Set recovery codes in the dashboard if you have not.")}`:"Nobody can reset it for you. Set recovery codes in the dashboard if you have not."),{passphrase:i,orgKey:m}};if(l){if(E){if(!L().validateGeneratedPassphrase(l).ok)throw new d("This workspace has no passphrase yet, so REDAKTYN_PASSPHRASE would become it, and a new workspace's passphrase has to be generated. Run this once in a terminal to get one, then set REDAKTYN_PASSPHRASE to it.");return R(l)}const i=P("Checking the passphrase from REDAKTYN_PASSPHRASE"),{verdict:h,key:f}=await I(l,n,k,o);if(h==="wrong")throw i.fail("REDAKTYN_PASSPHRASE is not this workspace's passphrase"),new d("REDAKTYN_PASSPHRASE is not this workspace's passphrase.");return i.succeed(h==="ok"?"Passphrase from REDAKTYN_PASSPHRASE verified":"Passphrase from REDAKTYN_PASSPHRASE accepted. The server has nothing to check it against"),{passphrase:l,orgKey:f}}if(!process.stdin.isTTY)throw new d("Set REDAKTYN_PASSPHRASE. It is used locally to derive the key and is never sent.");if(E){const h=L().generateOrgPassphrase();if(!c)return p(y?` ${u.dim("Dry run: this workspace has no passphrase yet. The preview uses a throwaway one. Run with --apply to generate the real one.")}`:"Dry run: this workspace has no passphrase yet. The preview uses a throwaway one. Run with --apply to generate the real one."),{passphrase:h,orgKey:await T(h,e)};const f=["This workspace has no passphrase yet, so one was generated for you.","It derives your keys on this machine and is never sent.","Nobody can reset it for you.","",h,"","Save it in your password manager now.","It stays in this terminal's scrollback until you clear it."];y?(v(""),b("Your workspace passphrase",f,{tone:"clay"}),v("")):(p(""),f.forEach(w=>p(w)),p(""));for(let w=$;w>0;w--){if((await U(y?` ${u.clay("\u203A")} Type ${u.dim("saved")} once you have kept it `:"Type 'saved' once you have kept it > ")).trim().toLowerCase()==="saved")return R(h);p("Not set yet. Save the passphrase above, then type: saved")}throw new d("No passphrase was set after 3 tries. Nothing was changed.")}y?(v(""),b(a,["This derives your keys on this machine and is never sent,","never stored, and not shown while you type."],{tone:"clay"}),v("")):(p(""),p(`${a}: this derives the key on your machine and is never sent. Nothing shows while you type.`));for(let i=$;i>0;i--){const h=await K(y?` ${u.clay("\u203A")} Passphrase ${u.dim("(hidden)")} `:"Type it, then press Enter > ");if(!h){p("Nothing was typed.");continue}const f=P(y?"Checking it against your workspace":"Checking"),{verdict:w,key:m}=await I(h,n,k,o);if(w!=="wrong")return f.succeed(w==="ok"?"Passphrase verified. It matches your workspace":"Passphrase accepted. This workspace has nothing to check it against"),{passphrase:h,orgKey:m};f.fail("That is not this workspace's passphrase"),p(y?i>1?` ${u.dim(`Try again (${i-1} left).`)}`:"":i>1?`That is not this workspace's passphrase. Try again (${i-1} left).`:"That is not this workspace's passphrase.")}throw new d("No correct passphrase after 3 tries. Nothing was changed.")}export{j as askWorkspaceKey,ee as askWorkspacePassphrase};