11import { Secret } from "@scaleway/sdk" ;
22
3+ export type Secret = {
4+ name : string ;
5+ path : string ;
6+ }
7+
38export function transformToValidEnvName ( secretName : string ) : string {
49 // Leading digits are invalid
510 if ( secretName . match ( / ^ [ 0 - 9 ] / ) ) {
@@ -10,34 +15,67 @@ export function transformToValidEnvName(secretName: string): string {
1015 return secretName . replace ( / [ ^ a - z A - Z 0 - 9 _ ] / g, "_" ) . toUpperCase ( ) ;
1116}
1217
13- export function extractAlias ( input : string ) : [ string , string ] {
18+ export function extractAlias ( input : string ) : [ string , Secret ] {
1419 const parsedInput = input . split ( "," ) ;
20+ let secretRef = input . trim ( )
21+ let secretPath = "/"
22+ let alias = transformToValidEnvName ( secretRef )
23+ let secretName = secretRef
1524
1625 if ( parsedInput . length > 1 ) {
17- const alias = parsedInput [ 0 ] . trim ( ) ;
18- const secretName = parsedInput [ 1 ] . trim ( ) ;
26+ alias = parsedInput [ 0 ] . trim ( ) ;
27+ secretRef = parsedInput [ 1 ] . trim ( ) ;
28+ secretName = secretRef ;
1929
2030 const validateEnvName = transformToValidEnvName ( alias ) ;
2131 if ( alias !== validateEnvName ) {
2232 throw new Error (
2333 `The alias '${ alias } ' is not a valid environment name. Please verify that it has uppercase letters, numbers, and underscore only.`
2434 ) ;
2535 }
36+ }
37+
38+ if ( secretRef . startsWith ( "/" ) ) {
39+ [ secretName , secretPath ] = splitNameAndPath ( secretRef )
40+ if ( parsedInput . length == 1 ) {
41+ alias = transformToValidEnvName ( secretName )
42+ }
43+ }
2644
27- return [ alias , secretName ] ;
45+ return [ alias , { name : secretName , path : secretPath } ] ;
46+ }
47+
48+ export function splitNameAndPath ( ref : string ) : [ string , string ] {
49+ const s = ref . split ( "/" )
50+ const name = s [ s . length - 1 ]
51+ let path = "/"
52+ if ( s . length > 2 ) {
53+ path = s . slice ( 0 , s . length - 1 ) . join ( "/" )
2854 }
2955
30- return [ transformToValidEnvName ( input . trim ( ) ) , input . trim ( ) ] ;
56+ return [ name , path ]
3157}
3258
3359export async function getSecretValue (
3460 api : Secret . v1alpha1 . API ,
35- secretName : string
61+ secret : Secret
3662) : Promise < string > {
37- const secretResponse = await api . accessSecretVersionByName ( {
38- secretName : secretName ,
39- revision : "latest" ,
40- } ) ;
63+
64+ const secretList = await api . listSecrets ( {
65+ name : secret . name ,
66+ path : secret . path ,
67+ page : 1 ,
68+ pageSize : 1
69+ } )
70+
71+ if ( secretList . totalCount < 1 ) {
72+ throw new Error ( `No secret found with '${ secret . name } ' name and '${ secret . path } ' path` )
73+ }
74+
75+ const secretResponse = await api . accessSecretVersion ( {
76+ secretId : secretList . secrets [ 0 ] . id ,
77+ revision : "latest_enabled"
78+ } )
4179
4280 return Buffer . from ( secretResponse . data , "base64" ) . toString ( "binary" ) ;
4381}
0 commit comments